summaryrefslogtreecommitdiffstats
path: root/luni/src/test/java
diff options
context:
space:
mode:
Diffstat (limited to 'luni/src/test/java')
-rw-r--r--luni/src/test/java/com/google/coretests/Main.java50
-rw-r--r--luni/src/test/java/com/google/coretests/PerfStatCollector.java257
-rw-r--r--luni/src/test/java/com/google/coretests/ResultPrinter.java157
-rw-r--r--luni/src/test/java/com/google/coretests/StatTestRunner.java230
-rw-r--r--luni/src/test/java/com/google/coretests/StatsStore.java309
-rw-r--r--luni/src/test/java/com/google/coretests/Version.java30
-rw-r--r--luni/src/test/java/junit/runner/BaseTestRunner.java326
-rw-r--r--luni/src/test/java/junit/runner/ClassPathTestCollector.java80
-rw-r--r--luni/src/test/java/junit/runner/FailureDetailView.java27
-rw-r--r--luni/src/test/java/junit/runner/LoadingTestCollector.java69
-rw-r--r--luni/src/test/java/junit/runner/ReloadingTestSuiteLoader.java19
-rw-r--r--luni/src/test/java/junit/runner/SimpleTestCollector.java20
-rw-r--r--luni/src/test/java/junit/runner/Sorter.java38
-rw-r--r--luni/src/test/java/junit/runner/StandardTestSuiteLoader.java19
-rw-r--r--luni/src/test/java/junit/runner/TestCaseClassLoader.java226
-rw-r--r--luni/src/test/java/junit/runner/TestCollector.java16
-rw-r--r--luni/src/test/java/junit/runner/TestRunListener.java19
-rw-r--r--luni/src/test/java/junit/runner/TestSuiteLoader.java9
-rw-r--r--luni/src/test/java/junit/runner/Version.java14
-rw-r--r--luni/src/test/java/junit/runner/excluded.properties12
-rw-r--r--luni/src/test/java/junit/runner/logo.gifbin964 -> 0 bytes
-rw-r--r--luni/src/test/java/junit/runner/smalllogo.gifbin883 -> 0 bytes
-rw-r--r--luni/src/test/java/junit/textui/ResultPrinter.java142
-rw-r--r--luni/src/test/java/junit/textui/TestRunner.java189
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/AllTests.java41
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/HttpURLConnectionTest.java340
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/AllTests.java42
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java1513
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/AllTests.java50
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/BufferedReaderTest.java134
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/FilePermissionTest.java49
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/FileTest.java190
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/InputStreamReaderTest.java82
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectInputStreamTest.java309
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectStreamConstantsTest.java43
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/OutputStreamWriterTest.java81
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/PushBackInputStreamTest.java108
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/RandomAccessFileTest.java51
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/ReaderTest.java379
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/WriterTest.java91
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AbstractMethodErrorTest.java51
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AllTests.java124
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArithmeticExceptionTest.java59
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArrayIndexOutOfBoundsExceptionTest.java76
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArrayStoreExceptionTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AssertionErrorTest.java125
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/BooleanTest.java235
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ByteTest.java900
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CharacterImplTest.java52
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CharacterTest.java2332
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/Character_SubsetTest.java99
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/Character_UnicodeBlockTest.java913
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassCastExceptionTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassCircularityErrorTest.java51
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassFormatErrorTest.java51
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassLoaderTest.java1251
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassNotFoundExceptionTest.java130
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassTest.java2265
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassTest2.java99
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CloneNotSupportedExceptionTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CompilerTest.java133
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/DoubleTest.java1663
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/EnumConstantNotPresentExceptionTest.java86
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/EnumTest.java346
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ErrorTest.java86
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExceptionInInitializerErrorTest.java107
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExceptionTest.java87
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExtendTestClass.java29
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExtendTestClass1.java21
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/FloatTest.java1282
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalAccessErrorTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalAccessExceptionTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalArgumentExceptionTest.java117
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalMonitorStateExceptionTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalStateExceptionTest.java122
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalThreadStateExceptionTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IncompatibleClassChangeErrorTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IndexOutOfBoundsExceptionTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InheritableThreadLocalTest.java78
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InstantiationErrorTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InstantiationExceptionTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IntegerTest.java1472
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InternalErrorTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InterruptedExceptionTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/LinkageErrorTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/LongTest.java1332
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MathTest.java1276
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MockEnum.java57
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MockEnum2.java61
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MockSecurityManager.java69
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MutableSecurityManager.java102
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NegativeArraySizeExceptionTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoClassDefFoundErrorTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchFieldErrorTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchFieldExceptionTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchMethodErrorTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchMethodExceptionTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NullPointerExceptionTest.java59
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NumberFormatExceptionTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NumberTest.java124
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ObjectTest.java671
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/OutOfMemoryErrorTest.java64
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/PackageTest.java495
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ProcessBuilderTest.java279
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/PublicClassLoader.java97
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/PublicTestClass.java73
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimeExceptionTest.java95
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimePermissionTest.java62
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimeTest.java1096
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SecurityExceptionTest.java122
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SecurityManagerTest.java1589
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ShortTest.java841
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StackOverflowErrorTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StackTraceElementOriginal.java30
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StackTraceElementTest.java285
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StrictMathTest.java1462
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/String2Test.java1741
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBuffer2Test.java1107
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBufferTest.java718
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBuilderTest.java2191
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringIndexOutOfBoundsExceptionTest.java71
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringTest.java704
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SystemTest.java1236
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestAnnotation.java25
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestAssertions.java29
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestAssertions1.java29
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass1.java25
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass1B.java25
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass1C.java25
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass2.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass3.java21
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass4.java0
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestLibrary.java50
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadDeathTest.java42
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadGroupTest.java1920
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadLocalTest.java218
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadStateTest.java80
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadTest.java2166
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThrowableTest.java413
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TypeNotPresentExceptionTest.java72
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnknownErrorTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsatisfiedLinkErrorTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsupportedClassVersionErrorTest.java55
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsupportedOperationExceptionTest.java118
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/VerifyErrorTest.java60
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/VirtualMachineErrorTest.java61
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/AllTests.java51
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerFactoryTest.java169
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerTest.java115
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/HttpRetryExceptionTest.java81
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/HttpURLConnectionTest.java1144
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/Inet4AddressTest.java542
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/Inet6AddressTest.java1242
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/InetAddressTest.java1096
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/InetSocketAddressTest.java421
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/URITest.java177
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLConnectionTest.java2190
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLEncoderTest.java57
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLTest.java1285
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/test_protocol/Handler.java30
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/AbstractCollectionTest.java523
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/AbstractMapTest.java533
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/AbstractSetTest.java142
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/AllTests.java73
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArrayListTest.java37
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArraysTest.java588
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/BitSetTest.java94
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/CollectionsTest.java1003
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/DateTest.java49
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/DictionaryTest.java82
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/DuplicateFormatFlagsExceptionTest.java132
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/EventListenerProxyTest.java68
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatFlagsConversionMismatchExceptionTest.java160
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormattableTest.java70
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatterClosedExceptionTest.java71
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatterTest.java72
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/HashMapTest.java95
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/IdentityHashMapTest.java511
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatCodePointExceptionTest.java127
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatConversionExceptionTest.java159
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatFlagsExceptionTest.java132
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatPrecisionExceptionTest.java128
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatWidthExceptionTest.java129
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/InputMismatchExceptionTest.java97
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/InvalidPropertiesFormatExceptionTest.java53
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/LinkedHashMapTest.java846
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/ListIteratorTest.java313
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/LocaleTest.java49
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/MapEntryTest.java148
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/MissingFormatArgumentExceptionTest.java134
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/MissingFormatWidthExceptionTest.java132
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/ObserverTest.java70
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/UUIDTest.java571
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/UnknownFormatConversionExceptionTest.java132
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/UnknownFormatFlagsExceptionTest.java131
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/VectorTest.java48
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/WeakHashMapTest.java134
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/pkg1/TestClass.java30
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/pkg2/TestClass.java29
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/util/Base64Test.java61
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/util/MsgHelpTest.java85
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/util/NYITest.java53
-rw-r--r--luni/src/test/java/tests/AllTests.java60
-rw-r--r--luni/src/test/java/tests/TestSuiteFactory.java355
-rw-r--r--luni/src/test/java/tests/api/java/io/AllTests.java114
-rw-r--r--luni/src/test/java/tests/api/java/io/BufferedInputStreamTest.java578
-rw-r--r--luni/src/test/java/tests/api/java/io/BufferedOutputStreamTest.java253
-rw-r--r--luni/src/test/java/tests/api/java/io/BufferedReaderTest.java515
-rw-r--r--luni/src/test/java/tests/api/java/io/BufferedWriterTest.java412
-rw-r--r--luni/src/test/java/tests/api/java/io/ByteArrayInputStreamTest.java325
-rw-r--r--luni/src/test/java/tests/api/java/io/ByteArrayOutputStreamTest.java327
-rw-r--r--luni/src/test/java/tests/api/java/io/CharArrayReaderTest.java342
-rw-r--r--luni/src/test/java/tests/api/java/io/CharArrayWriterTest.java436
-rw-r--r--luni/src/test/java/tests/api/java/io/CharConversionExceptionTest.java66
-rw-r--r--luni/src/test/java/tests/api/java/io/ComputeSerialVersionUIDTest.java183
-rw-r--r--luni/src/test/java/tests/api/java/io/DataInputOutputStreamTest.java529
-rw-r--r--luni/src/test/java/tests/api/java/io/DataInputStreamTest.java517
-rw-r--r--luni/src/test/java/tests/api/java/io/DataOutputStreamTest.java297
-rw-r--r--luni/src/test/java/tests/api/java/io/EOFExceptionTest.java84
-rw-r--r--luni/src/test/java/tests/api/java/io/ExternalizableTest.java33
-rw-r--r--luni/src/test/java/tests/api/java/io/FileDescriptorTest.java152
-rw-r--r--luni/src/test/java/tests/api/java/io/FileFilterTest.java25
-rw-r--r--luni/src/test/java/tests/api/java/io/FileInputStreamTest.java511
-rw-r--r--luni/src/test/java/tests/api/java/io/FileNotFoundExceptionTest.java66
-rw-r--r--luni/src/test/java/tests/api/java/io/FileOutputStreamTest.java451
-rw-r--r--luni/src/test/java/tests/api/java/io/FilePermissionTest.java261
-rw-r--r--luni/src/test/java/tests/api/java/io/FileReaderTest.java169
-rw-r--r--luni/src/test/java/tests/api/java/io/FileTest.java2533
-rw-r--r--luni/src/test/java/tests/api/java/io/FileWriterTest.java409
-rw-r--r--luni/src/test/java/tests/api/java/io/FilenameFilterTest.java25
-rw-r--r--luni/src/test/java/tests/api/java/io/FilterInputStreamTest.java454
-rw-r--r--luni/src/test/java/tests/api/java/io/FilterOutputStreamTest.java269
-rw-r--r--luni/src/test/java/tests/api/java/io/FilterReaderTest.java279
-rw-r--r--luni/src/test/java/tests/api/java/io/FilterWriterTest.java228
-rw-r--r--luni/src/test/java/tests/api/java/io/IOExceptionTest.java68
-rw-r--r--luni/src/test/java/tests/api/java/io/InputStreamReaderTest.java698
-rw-r--r--luni/src/test/java/tests/api/java/io/InputStreamTest.java402
-rw-r--r--luni/src/test/java/tests/api/java/io/InterruptedIOExceptionTest.java86
-rw-r--r--luni/src/test/java/tests/api/java/io/InvalidClassExceptionTest.java101
-rw-r--r--luni/src/test/java/tests/api/java/io/InvalidObjectExceptionTest.java49
-rw-r--r--luni/src/test/java/tests/api/java/io/LineNumberInputStreamTest.java308
-rw-r--r--luni/src/test/java/tests/api/java/io/LineNumberReaderTest.java310
-rw-r--r--luni/src/test/java/tests/api/java/io/NotActiveExceptionTest.java67
-rw-r--r--luni/src/test/java/tests/api/java/io/NotSerializableExceptionTest.java66
-rw-r--r--luni/src/test/java/tests/api/java/io/ObjectInputOutputStreamTest.java468
-rw-r--r--luni/src/test/java/tests/api/java/io/ObjectInputStreamGetFieldTest.java400
-rw-r--r--luni/src/test/java/tests/api/java/io/ObjectInputStreamTest.java1497
-rw-r--r--luni/src/test/java/tests/api/java/io/ObjectInputValidationTest.java23
-rw-r--r--luni/src/test/java/tests/api/java/io/ObjectOutputStreamPutFieldTest.java209
-rw-r--r--luni/src/test/java/tests/api/java/io/ObjectOutputStreamTest.java1626
-rw-r--r--luni/src/test/java/tests/api/java/io/ObjectStreamClassTest.java245
-rw-r--r--luni/src/test/java/tests/api/java/io/ObjectStreamExceptionTest.java78
-rw-r--r--luni/src/test/java/tests/api/java/io/ObjectStreamFieldTest.java537
-rw-r--r--luni/src/test/java/tests/api/java/io/OpenRandomFileTest.java83
-rw-r--r--luni/src/test/java/tests/api/java/io/OutputStreamTest.java172
-rw-r--r--luni/src/test/java/tests/api/java/io/OutputStreamWriterTest.java786
-rw-r--r--luni/src/test/java/tests/api/java/io/PipedInputStreamTest.java528
-rw-r--r--luni/src/test/java/tests/api/java/io/PipedOutputStreamTest.java339
-rw-r--r--luni/src/test/java/tests/api/java/io/PipedReaderTest.java408
-rw-r--r--luni/src/test/java/tests/api/java/io/PipedWriterTest.java501
-rw-r--r--luni/src/test/java/tests/api/java/io/PrintStreamTest.java1167
-rw-r--r--luni/src/test/java/tests/api/java/io/PrintWriterTest.java1296
-rw-r--r--luni/src/test/java/tests/api/java/io/PushbackInputStreamTest.java466
-rw-r--r--luni/src/test/java/tests/api/java/io/PushbackReaderTest.java673
-rw-r--r--luni/src/test/java/tests/api/java/io/RandomAccessFileTest.java1504
-rw-r--r--luni/src/test/java/tests/api/java/io/SequenceInputStreamTest.java357
-rw-r--r--luni/src/test/java/tests/api/java/io/SerializablePermissionTest.java77
-rw-r--r--luni/src/test/java/tests/api/java/io/SerializationStressTest.java1254
-rw-r--r--luni/src/test/java/tests/api/java/io/SerializationStressTest1.java1894
-rw-r--r--luni/src/test/java/tests/api/java/io/SerializationStressTest2.java2412
-rw-r--r--luni/src/test/java/tests/api/java/io/SerializationStressTest3.java2065
-rw-r--r--luni/src/test/java/tests/api/java/io/SerializationStressTest4.java3130
-rw-r--r--luni/src/test/java/tests/api/java/io/SerializationStressTest5.java390
-rw-r--r--luni/src/test/java/tests/api/java/io/SerializationTestClass.java335
-rw-r--r--luni/src/test/java/tests/api/java/io/StreamCorruptedExceptionTest.java66
-rw-r--r--luni/src/test/java/tests/api/java/io/StreamTokenizerTest.java757
-rw-r--r--luni/src/test/java/tests/api/java/io/StringBufferInputStreamTest.java176
-rw-r--r--luni/src/test/java/tests/api/java/io/StringReaderTest.java279
-rw-r--r--luni/src/test/java/tests/api/java/io/StringWriterTest.java306
-rw-r--r--luni/src/test/java/tests/api/java/io/SyncFailedExceptionTest.java47
-rw-r--r--luni/src/test/java/tests/api/java/io/UTFDataFormatExceptionTest.java66
-rw-r--r--luni/src/test/java/tests/api/java/io/UnsupportedEncodingExceptionTest.java66
-rw-r--r--luni/src/test/java/tests/api/java/io/WriteAbortedExceptionTest.java102
-rw-r--r--luni/src/test/java/tests/api/java/io/WriterTest.java338
-rw-r--r--luni/src/test/java/tests/api/java/lang/AllTests.java47
-rw-r--r--luni/src/test/java/tests/api/java/lang/BooleanTest.java53
-rw-r--r--luni/src/test/java/tests/api/java/lang/Process2Test.java128
-rw-r--r--luni/src/test/java/tests/api/java/lang/ProcessManagerTest.java255
-rw-r--r--luni/src/test/java/tests/api/java/lang/ProcessTest.java240
-rw-r--r--luni/src/test/java/tests/api/java/lang/StringTest.java85
-rw-r--r--luni/src/test/java/tests/api/java/lang/ref/AllTests.java47
-rw-r--r--luni/src/test/java/tests/api/java/lang/ref/PhantomReferenceTest.java164
-rw-r--r--luni/src/test/java/tests/api/java/lang/ref/ReferenceQueueTest.java283
-rw-r--r--luni/src/test/java/tests/api/java/lang/ref/ReferenceTest.java461
-rw-r--r--luni/src/test/java/tests/api/java/lang/ref/SoftReferenceTest.java170
-rw-r--r--luni/src/test/java/tests/api/java/lang/ref/WeakReferenceTest.java98
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/AccessibleObjectTest.java269
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/AllTests.java60
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/ArrayTest.java1133
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/BoundedGenericMethodsTests.java164
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/ConstructorTest.java573
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/FieldTest.java2157
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/GenericArrayTypeTest.java82
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/GenericMethodsTests.java199
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/GenericReflectionCornerCases.java287
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/GenericReflectionTestsBase.java74
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/GenericSignatureFormatErrorTest.java110
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/GenericTypesTest.java288
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/InvocationTargetExceptionTest.java359
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/MalformedParameterizedTypeExceptionTests.java33
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/MethodTest.java980
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/ModifierTest.java289
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/ParameterizedTypeTest.java143
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/ProxyTest.java395
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/ReflectPermissionTest.java77
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/TypeVariableTest.java218
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/UndeclaredThrowableExceptionTests.java83
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/WildcardTypeTest.java196
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/dex1.bytesbin886 -> 0 bytes
-rw-r--r--luni/src/test/java/tests/api/java/net/AllTests.java84
-rw-r--r--luni/src/test/java/tests/api/java/net/AuthenticatorRequestorTypeTest.java70
-rw-r--r--luni/src/test/java/tests/api/java/net/AuthenticatorTest.java423
-rw-r--r--luni/src/test/java/tests/api/java/net/BindExceptionTest.java85
-rw-r--r--luni/src/test/java/tests/api/java/net/CacheRequestTest.java87
-rw-r--r--luni/src/test/java/tests/api/java/net/CacheResponseTest.java83
-rw-r--r--luni/src/test/java/tests/api/java/net/ConnectExceptionTest.java56
-rw-r--r--luni/src/test/java/tests/api/java/net/CookieHandlerTest.java236
-rw-r--r--luni/src/test/java/tests/api/java/net/DatagramPacketTest.java612
-rw-r--r--luni/src/test/java/tests/api/java/net/DatagramSocketImplFactoryTest.java257
-rw-r--r--luni/src/test/java/tests/api/java/net/DatagramSocketImplTest.java347
-rw-r--r--luni/src/test/java/tests/api/java/net/DatagramSocketTest.java2851
-rw-r--r--luni/src/test/java/tests/api/java/net/ExcludedProxyTest.java238
-rw-r--r--luni/src/test/java/tests/api/java/net/FileNameMapTest.java53
-rw-r--r--luni/src/test/java/tests/api/java/net/HttpRetryExceptionTest.java106
-rw-r--r--luni/src/test/java/tests/api/java/net/JarURLConnectionTest.java548
-rw-r--r--luni/src/test/java/tests/api/java/net/MalformedURLExceptionTest.java91
-rw-r--r--luni/src/test/java/tests/api/java/net/MulticastSocketTest.java1612
-rw-r--r--luni/src/test/java/tests/api/java/net/NetPermissionTest.java81
-rw-r--r--luni/src/test/java/tests/api/java/net/NetworkInterfaceTest.java609
-rw-r--r--luni/src/test/java/tests/api/java/net/NoRouteToHostExceptionTest.java88
-rw-r--r--luni/src/test/java/tests/api/java/net/PasswordAuthenticationTest.java94
-rw-r--r--luni/src/test/java/tests/api/java/net/PortUnreachableExceptionTest.java56
-rw-r--r--luni/src/test/java/tests/api/java/net/ProtocolExceptionTest.java85
-rw-r--r--luni/src/test/java/tests/api/java/net/ProxySelectorTest.java737
-rw-r--r--luni/src/test/java/tests/api/java/net/ProxyTest.java343
-rw-r--r--luni/src/test/java/tests/api/java/net/ProxyTypeTest.java84
-rw-r--r--luni/src/test/java/tests/api/java/net/ResponseCacheTest.java300
-rw-r--r--luni/src/test/java/tests/api/java/net/SecureCacheResponseTest.java181
-rw-r--r--luni/src/test/java/tests/api/java/net/ServerSocketTest.java1504
-rw-r--r--luni/src/test/java/tests/api/java/net/SocketExceptionTest.java83
-rw-r--r--luni/src/test/java/tests/api/java/net/SocketImplFactoryTest.java211
-rw-r--r--luni/src/test/java/tests/api/java/net/SocketImplTest.java265
-rw-r--r--luni/src/test/java/tests/api/java/net/SocketPermissionTest.java288
-rw-r--r--luni/src/test/java/tests/api/java/net/SocketTest.java3395
-rw-r--r--luni/src/test/java/tests/api/java/net/SocketTestCase.java172
-rw-r--r--luni/src/test/java/tests/api/java/net/SocketTimeoutExceptionTest.java40
-rw-r--r--luni/src/test/java/tests/api/java/net/TestServerSocketInit.java30
-rw-r--r--luni/src/test/java/tests/api/java/net/URISyntaxExceptionTest.java166
-rw-r--r--luni/src/test/java/tests/api/java/net/URITest.java2174
-rw-r--r--luni/src/test/java/tests/api/java/net/URLClassLoaderTest.java718
-rw-r--r--luni/src/test/java/tests/api/java/net/URLDecoderTest.java120
-rw-r--r--luni/src/test/java/tests/api/java/net/URLEncoderTest.java121
-rw-r--r--luni/src/test/java/tests/api/java/net/URLStreamHandlerFactoryTest.java132
-rw-r--r--luni/src/test/java/tests/api/java/net/URLStreamHandlerTest.java328
-rw-r--r--luni/src/test/java/tests/api/java/net/UnknownHostExceptionTest.java87
-rw-r--r--luni/src/test/java/tests/api/java/net/UnknownServiceExceptionTest.java88
-rw-r--r--luni/src/test/java/tests/api/java/util/AbstractListTest.java353
-rw-r--r--luni/src/test/java/tests/api/java/util/AbstractMapTest.java310
-rw-r--r--luni/src/test/java/tests/api/java/util/AbstractQueueTest.java425
-rw-r--r--luni/src/test/java/tests/api/java/util/AbstractSequentialListTest.java659
-rw-r--r--luni/src/test/java/tests/api/java/util/AllTests.java91
-rw-r--r--luni/src/test/java/tests/api/java/util/ArrayListTest.java846
-rw-r--r--luni/src/test/java/tests/api/java/util/ArraysTest.java2462
-rw-r--r--luni/src/test/java/tests/api/java/util/BitSetTest.java1564
-rw-r--r--luni/src/test/java/tests/api/java/util/CalendarTest.java1282
-rw-r--r--luni/src/test/java/tests/api/java/util/CollectionsTest.java2491
-rw-r--r--luni/src/test/java/tests/api/java/util/ConcurrentModTest.java753
-rw-r--r--luni/src/test/java/tests/api/java/util/ConcurrentModificationExceptionTest.java125
-rw-r--r--luni/src/test/java/tests/api/java/util/CurrencyTest.java449
-rw-r--r--luni/src/test/java/tests/api/java/util/DateTest.java718
-rw-r--r--luni/src/test/java/tests/api/java/util/EmptyStackExceptionTest.java75
-rw-r--r--luni/src/test/java/tests/api/java/util/EnumMapTest.java1288
-rw-r--r--luni/src/test/java/tests/api/java/util/EnumSetTest.java2112
-rw-r--r--luni/src/test/java/tests/api/java/util/EventObjectTest.java98
-rw-r--r--luni/src/test/java/tests/api/java/util/FormattableFlagsTest.java43
-rw-r--r--luni/src/test/java/tests/api/java/util/FormatterTest.java4692
-rw-r--r--luni/src/test/java/tests/api/java/util/GregorianCalendarTest.java952
-rw-r--r--luni/src/test/java/tests/api/java/util/HashMapTest.java640
-rw-r--r--luni/src/test/java/tests/api/java/util/HashSetTest.java341
-rw-r--r--luni/src/test/java/tests/api/java/util/HashtableTest.java992
-rw-r--r--luni/src/test/java/tests/api/java/util/IdentityHashMapTest.java613
-rw-r--r--luni/src/test/java/tests/api/java/util/InvalidPropertiesFormatExceptionTest.java51
-rw-r--r--luni/src/test/java/tests/api/java/util/LinkedHashMapTest.java839
-rw-r--r--luni/src/test/java/tests/api/java/util/LinkedHashSetTest.java446
-rw-r--r--luni/src/test/java/tests/api/java/util/LinkedListTest.java841
-rw-r--r--luni/src/test/java/tests/api/java/util/ListResourceBundleTest.java124
-rw-r--r--luni/src/test/java/tests/api/java/util/LocaleTest.java646
-rw-r--r--luni/src/test/java/tests/api/java/util/MissingResourceExceptionTest.java109
-rw-r--r--luni/src/test/java/tests/api/java/util/NoSuchElementExceptionTest.java91
-rw-r--r--luni/src/test/java/tests/api/java/util/ObservableTest.java322
-rw-r--r--luni/src/test/java/tests/api/java/util/PriorityQueueTest.java1026
-rw-r--r--luni/src/test/java/tests/api/java/util/PropertiesTest.java629
-rw-r--r--luni/src/test/java/tests/api/java/util/PropertyPermissionTest.java216
-rw-r--r--luni/src/test/java/tests/api/java/util/PropertyResourceBundleTest.java122
-rw-r--r--luni/src/test/java/tests/api/java/util/RandomTest.java376
-rw-r--r--luni/src/test/java/tests/api/java/util/ResourceBundleTest.java492
-rw-r--r--luni/src/test/java/tests/api/java/util/SampleBundleClass.java43
-rw-r--r--luni/src/test/java/tests/api/java/util/ScannerTest.java6796
-rw-r--r--luni/src/test/java/tests/api/java/util/SimpleTimeZoneTest.java977
-rw-r--r--luni/src/test/java/tests/api/java/util/StackTest.java230
-rw-r--r--luni/src/test/java/tests/api/java/util/StringTokenizerTest.java285
-rw-r--r--luni/src/test/java/tests/api/java/util/TimeZoneTest.java401
-rw-r--r--luni/src/test/java/tests/api/java/util/TimerTaskTest.java276
-rw-r--r--luni/src/test/java/tests/api/java/util/TimerTest.java1273
-rw-r--r--luni/src/test/java/tests/api/java/util/TooManyListenersExceptionTest.java82
-rw-r--r--luni/src/test/java/tests/api/java/util/TreeMapTest.java890
-rw-r--r--luni/src/test/java/tests/api/java/util/TreeSetTest.java611
-rw-r--r--luni/src/test/java/tests/api/java/util/VectorTest.java1498
-rw-r--r--luni/src/test/java/tests/api/java/util/WeakHashMapTest.java525
-rw-r--r--luni/src/test/java/tests/api/java/util/support/A.java13
-rw-r--r--luni/src/test/java/tests/api/java/util/support/B.java4
-rw-r--r--luni/src/test/java/tests/api/java/util/support/I.java5
-rw-r--r--luni/src/test/java/tests/api/java/util/support/P.java28
-rw-r--r--luni/src/test/java/tests/java/lang/StrictMath/Fdlibm53Test.java47
-rw-r--r--luni/src/test/java/tests/java/lang/String/Tests.java84
-rw-r--r--luni/src/test/java/tests/luni/AllTests.java44
-rw-r--r--luni/src/test/java/tests/luni/AllTestsIo.java42
-rw-r--r--luni/src/test/java/tests/luni/AllTestsLang.java46
-rw-r--r--luni/src/test/java/tests/luni/AllTestsNet.java45
-rw-r--r--luni/src/test/java/tests/luni/AllTestsUtil.java41
430 files changed, 0 insertions, 178049 deletions
diff --git a/luni/src/test/java/com/google/coretests/Main.java b/luni/src/test/java/com/google/coretests/Main.java
deleted file mode 100644
index 8dba719..0000000
--- a/luni/src/test/java/com/google/coretests/Main.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.coretests;
-
-import junit.textui.TestRunner;
-import tests.AllTests;
-
-/**
- * Main class to run the core tests.
- */
-public class Main
-{
- public static void main(String[] args) {
- if (args.length == 0) {
- System.out.println("Running all tests...");
- TestRunner.run(AllTests.suite());
- } else if ("--stats".equals(args[0])) {
- // Delegate to new stats test runner
- String[] args2 = new String[args.length - 1];
- System.arraycopy(args, 1, args2, 0, args2.length);
-
- if (args2.length == 0) {
- System.out.println("Running all tests with stats...");
- StatTestRunner.run(AllTests.suite());
- } else {
- System.out.println("Running selected tests with stats...");
- StatTestRunner.main(args2);
- }
- } else {
- System.out.println("Running selected tests...");
- TestRunner.main(args);
- }
-
- Runtime.getRuntime().halt(0);
- }
-}
diff --git a/luni/src/test/java/com/google/coretests/PerfStatCollector.java b/luni/src/test/java/com/google/coretests/PerfStatCollector.java
deleted file mode 100644
index 11f745e..0000000
--- a/luni/src/test/java/com/google/coretests/PerfStatCollector.java
+++ /dev/null
@@ -1,257 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.coretests;
-
-import dalvik.system.VMDebug;
-
-import junit.framework.AssertionFailedError;
-import junit.framework.Test;
-import junit.framework.TestListener;
-
-import java.io.PrintStream;
-import java.util.ArrayList;
-import java.util.Iterator;
-
-public class PerfStatCollector implements TestListener {
-
- public boolean listAll = false;
- public boolean listBad = false;
- public long thresholdDuration = 3600 * 1000; // in milliseconds
- public boolean twoLines = true;
- public boolean bigMarking = true;
-
- private static boolean havePreciseTime =
- VMDebug.threadCpuTimeNanos() != -1;
-
- public class Item {
- Test test;
- long startTime, duration;
- int res;
- public boolean existsInStore;
- public int id;
- public int bestRes;
- public long lastBestAt;
- public int lastRes;
- public long lastDuration;
- public int statCount;
- public double statAvgDuration;
- public long statMinDuration;
- public long statMaxDuration;
- int adhocRelevance;
- public int histRelevance;
- public boolean isTransition;
- boolean printed = false;
-
- void update(boolean rBad, long rthDurat) {
- // AdHoc Evaluation:
- if (rBad && (res != 0)) {
- // no success:
- adhocRelevance = 2;
- }
- else if (duration >= rthDurat) {
- // long duration:
- adhocRelevance = 1;
- }
- else {
- adhocRelevance = 0;
- }
-
- StatsStore.use1(this);
- }
-
- void print1(PrintStream out, boolean bigMarking) {
- switch (histRelevance) {
- case -4:
- if (bigMarking) {
- out.println();
- out.println("*** *** *** *** *** ATTENTION *** *** *** *** ***");
- out.println("*** *** *** *** *** ATTENTION *** *** *** *** ***");
- out.println("*** *** *** *** *** ATTENTION *** *** *** *** ***");
- out.println("Test ran SUCCESSFULLY once, but NOT this time!!!!");
- out.println("*** *** *** *** *** ATTENTION *** *** *** *** ***");
- out.println("*** *** *** *** *** ATTENTION *** *** *** *** ***");
- out.println("*** *** *** *** *** ATTENTION *** *** *** *** ***");
- }
- out.print("-4 VBAD"); break;
- case 4: out.print(" 4 Good"); break;
- case 3: out.print(" 3 good"); break;
- case -2: out.print("-2 SLOW"); break;
- case 2: out.print(" 2 Fast"); break;
- case 1: out.print(" 1 fast"); break;
- case -3:
- if (res == -2) out.print("-3 FAIL");
- else out.print("-3 ERR ");
- break;
- default:
- if (res == 0) out.print(" ");
- else if (res == -2) out.print(" fail");
- else out.print(" err ");
- }
- if (isTransition) out.print("! ");
- else out.print(" ");
- out.print(test.toString());
- out.format(": %d# %d(%d) [%d..%d] %.1f ms",
- statCount, duration, lastDuration,
- statMinDuration, statMaxDuration, statAvgDuration);
- out.println();
- printed = true;
- }
-
- void print2(PrintStream out, boolean bigMarking) {
- out.format("%5d. ", id);
-
- out.println(test.toString());
- out.print(" ");
-
- switch (histRelevance) {
- case -4: out.print("FAIL"); break;
- case 4: out.print("PASS"); break;
- case 3: out.print("PASS"); break;
- case -2: out.print("SLOW"); break;
- case 2: out.print("FAST"); break;
- case 1: out.print("PASS"); break;
- case -3:
- if (res == -2) out.print("FAIL");
- else out.print("ERR ");
- break;
- default:
- if (res == 0) out.print("PASS");
- else if (res == -2) out.print("FAIL");
- else out.print("XCPT");
- }
-
- out.format(" %d ms (min %d ms, max %d ms, avg %#.1f ms, %d runs)",
- duration,
- statMinDuration, statMaxDuration, statAvgDuration,
- statCount);
- out.println();
-
- printed = true;
- }
-
- void print(PrintStream out, boolean bigMarking) {
- if (twoLines) print2(out, bigMarking);
- else print1(out, bigMarking);
- }
-
- boolean checkPrint(PrintStream out) {
- if (printed) return false;
- print(out, false);
- return true;
- }
- }
-
- ArrayList<Item> items;
- Item current;
-
- PrintStream fWriter;
- int fColumn= 0;
-
- public PerfStatCollector(PrintStream writer) {
- fWriter= writer;
- items = new ArrayList();
- }
-
- synchronized void digest() {
- int totalCnt = 0;
- int adhocRelevantCnt = 0;
- int histRelevantCnt = 0;
- long evalStartTime = System.currentTimeMillis();
- PrintStream out = fWriter;
- out.println("Failure and Performance Statistics:");
- Iterator<Item> r = items.iterator();
- while (r.hasNext()) {
- Item item = r.next();
- item.update(listBad, thresholdDuration);
- if (item.histRelevance != 0) {
- item.print(out, bigMarking);
- histRelevantCnt++;
- }
- if (item.adhocRelevance != 0) {
- if (item.checkPrint(out))
- adhocRelevantCnt++;
- }
- if (listAll) item.checkPrint(out);
- totalCnt++;
- }
- long evalDuration = System.currentTimeMillis() - evalStartTime;
- out.println();
- out.print(totalCnt); out.println(" tests run totally.");
- out.print(histRelevantCnt);
- out.println(" tests listed due to historical relevance.");
-// out.print(adhocRelevantCnt);
-// out.println(" tests listed due to ad-hoc-relevance.");
-// out.print(totalCnt - histRelevantCnt - adhocRelevantCnt);
-// out.println(" tests NOT listed due to relevance.");
- out.println();
- out.print("Time used in Statistics Acquisition: ");
- out.print(evalDuration);
- out.print("ms");
- out.println();
- }
-
-
- public PrintStream getWriter() {
- return fWriter;
- }
-
- /**
- * @see junit.framework.TestListener#addError(Test, Throwable)
- */
- public void addError(Test test, Throwable t) {
- current.res = -1;
- }
-
- /**
- * @see junit.framework.TestListener#addFailure(Test, AssertionFailedError)
- */
- public void addFailure(Test test, AssertionFailedError t) {
- current.res = -2;
- }
-
- /**
- * @see junit.framework.TestListener#startTest(Test)
- */
- public void startTest(Test test) {
- System.gc();
- current = new Item();
- current.test = test;
- current.startTime = currentTimeMillis();
- items.add(current);
- }
-
- /**
- * @see junit.framework.TestListener#endTest(Test)
- */
- public void endTest(Test test) {
- current.duration = currentTimeMillis() - current.startTime;
- }
-
- /*
- * Returns a "current time" in ms. Depending on the environment, this is
- * either the actual CPU time out current thread has used so far, or the
- * wall clock time of the system.
- */
- private long currentTimeMillis() {
- if (havePreciseTime) {
- return VMDebug.threadCpuTimeNanos() / 1000;
- } else {
- return System.currentTimeMillis();
- }
- }
-
-}
diff --git a/luni/src/test/java/com/google/coretests/ResultPrinter.java b/luni/src/test/java/com/google/coretests/ResultPrinter.java
deleted file mode 100644
index cfd5227..0000000
--- a/luni/src/test/java/com/google/coretests/ResultPrinter.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.coretests;
-
-import java.io.PrintStream;
-// The following line was removed for compatibility with Android libraries.
-//import java.text.NumberFormat;
-import java.util.Enumeration;
-
-import junit.framework.AssertionFailedError;
-import junit.framework.Test;
-import junit.framework.TestFailure;
-import junit.framework.TestListener;
-import junit.framework.TestResult;
-import junit.runner.BaseTestRunner;
-
-public class ResultPrinter implements TestListener {
- PrintStream fWriter;
- int fColumn= 0;
-
- public ResultPrinter(PrintStream writer) {
- fWriter= writer;
- }
-
- /* API for use by textui.TestRunner
- */
-
- synchronized void print(TestResult result, long runTime) {
- printHeader(runTime);
- printErrors(result);
- printFailures(result);
- printFooter(result);
- }
-
- void printWaitPrompt() {
- getWriter().println();
- getWriter().println("<RETURN> to continue");
- }
-
- /* Internal methods
- */
-
- protected void printHeader(long runTime) {
- getWriter().println();
- getWriter().println("Time: "+elapsedTimeAsString(runTime));
- }
-
- protected void printErrors(TestResult result) {
- printDefects(result.errors(), result.errorCount(), "error");
- }
-
- protected void printFailures(TestResult result) {
- printDefects(result.failures(), result.failureCount(), "failure");
- }
-
- protected void printDefects(Enumeration booBoos, int count, String type) {
- if (count == 0) return;
- if (count == 1)
- getWriter().println("There was " + count + " " + type + ":");
- else
- getWriter().println("There were " + count + " " + type + "s:");
- for (int i= 1; booBoos.hasMoreElements(); i++) {
- printDefect((TestFailure) booBoos.nextElement(), i);
- }
- }
-
- public void printDefect(TestFailure booBoo, int count) { // only public for testing purposes
- printDefectHeader(booBoo, count);
- printDefectTrace(booBoo);
- }
-
- protected void printDefectHeader(TestFailure booBoo, int count) {
- // I feel like making this a println, then adding a line giving the throwable a chance to print something
- // before we get to the stack trace.
- getWriter().print(count + ") " + booBoo.failedTest());
- }
-
- protected void printDefectTrace(TestFailure booBoo) {
- getWriter().print(BaseTestRunner.getFilteredTrace(booBoo.trace()));
- }
-
- protected void printFooter(TestResult result) {
- if (result.wasSuccessful()) {
- getWriter().println();
- getWriter().print("OK");
- getWriter().println (" (" + result.runCount() + " test" + (result.runCount() == 1 ? "": "s") + ")");
-
- } else {
- getWriter().println();
- getWriter().println("FAILURES!!!");
- getWriter().println("Tests run: "+result.runCount()+
- ", Failures: "+result.failureCount()+
- ", Errors: "+result.errorCount());
- }
- getWriter().println();
- }
-
-
- /**
- * Returns the formatted string of the elapsed time.
- * Duplicated from BaseTestRunner. Fix it.
- */
- protected String elapsedTimeAsString(long runTime) {
- // The following line was altered for compatibility with
- // Android libraries.
- return Double.toString((double)runTime/1000);
- }
-
- public PrintStream getWriter() {
- return fWriter;
- }
- /**
- * @see junit.framework.TestListener#addError(Test, Throwable)
- */
- public void addError(Test test, Throwable t) {
- getWriter().print("E");
- }
-
- /**
- * @see junit.framework.TestListener#addFailure(Test, AssertionFailedError)
- */
- public void addFailure(Test test, AssertionFailedError t) {
- getWriter().print("F");
- }
-
- /**
- * @see junit.framework.TestListener#endTest(Test)
- */
- public void endTest(Test test) {
- }
-
- /**
- * @see junit.framework.TestListener#startTest(Test)
- */
- public void startTest(Test test) {
- getWriter().print(".");
- if (fColumn++ >= 40) {
- getWriter().println();
- fColumn= 0;
- }
- }
-
-}
diff --git a/luni/src/test/java/com/google/coretests/StatTestRunner.java b/luni/src/test/java/com/google/coretests/StatTestRunner.java
deleted file mode 100644
index b4642b8..0000000
--- a/luni/src/test/java/com/google/coretests/StatTestRunner.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.coretests;
-
-import junit.framework.Test;
-import junit.framework.TestResult;
-import junit.framework.TestSuite;
-import junit.runner.BaseTestRunner;
-import junit.runner.StandardTestSuiteLoader;
-import junit.runner.TestSuiteLoader;
-
-import java.io.PrintStream;
-
-/**
- * A command line based tool to run tests.
- * <pre>
- * java junit.textui.TestRunner [-wait] TestCaseClass
- * </pre>
- * TestRunner expects the name of a TestCase class as argument.
- * If this class defines a static <code>suite</code> method it
- * will be invoked and the returned test is run. Otherwise all
- * the methods starting with "test" having no arguments are run.
- * <p>
- * When the wait command line argument is given TestRunner
- * waits until the users types RETURN.
- * <p>
- * TestRunner prints a trace as the tests are executed followed by a
- * summary at the end.
- */
-public class StatTestRunner extends BaseTestRunner {
- private ResultPrinter fPrinter;
- private PerfStatCollector fPerfStatCollector;
-
- public static final int SUCCESS_EXIT= 0;
- public static final int FAILURE_EXIT= 1;
- public static final int EXCEPTION_EXIT= 2;
-
- public static final String DEFAULT_DATABASE = "sqlite:/coretests.db";
- public static final String DEFAULT_DRIVER = "SQLite.JDBCDriver";
-
- public static String connectionURL;
- public static String jdbcDriver;
-
- /**
- * Constructs a TestRunner.
- */
- public StatTestRunner() {
- this(System.out);
- }
-
- /**
- * Constructs a TestRunner using the given stream for all the output
- */
- public StatTestRunner(PrintStream writer) {
- this(new ResultPrinter(writer));
- }
-
- /**
- * Constructs a TestRunner using the given ResultPrinter all the output
- */
- public StatTestRunner(ResultPrinter printer) {
- fPrinter= printer;
- fPerfStatCollector = new PerfStatCollector(printer.getWriter());
- }
-
- /**
- * Runs a suite extracted from a TestCase subclass.
- */
- static public void run(Class testClass) {
- run(new TestSuite(testClass));
- }
-
- /**
- * Runs a single test and collects its results.
- * This method can be used to start a test run
- * from your program.
- * <pre>
- * public static void main (String[] args) {
- * test.textui.TestRunner.run(suite());
- * }
- * </pre>
- */
- static public TestResult run(Test test) {
- StatTestRunner runner= new StatTestRunner();
- try {
- return runner.doRun(test, false);
- }
- catch (Exception e) {
- return null;
- }
- }
-
- /**
- * Runs a single test and waits until the user
- * types RETURN.
- */
- static public void runAndWait(Test suite) {
- StatTestRunner aTestRunner= new StatTestRunner();
- try {
- aTestRunner.doRun(suite, true);
- }
- catch (Exception e) {}
- }
-
- /**
- * Always use the StandardTestSuiteLoader. Overridden from
- * BaseTestRunner.
- */
- public TestSuiteLoader getLoader() {
- return new StandardTestSuiteLoader();
- }
-
- public void testFailed(int status, Test test, Throwable t) {
- }
-
- public void testStarted(String testName) {
- }
-
- public void testEnded(String testName) {
- }
-
- public TestResult doRun(Test suite, boolean wait) throws Exception {
- StatsStore.open(jdbcDriver, connectionURL);
- TestResult result = new TestResult();
- result.addListener(fPrinter);
- result.addListener(fPerfStatCollector);
- long startTime= System.currentTimeMillis();
- StatsStore.now = startTime;
- suite.run(result);
- long endTime= System.currentTimeMillis();
- long runTime= endTime-startTime;
- fPrinter.print(result, runTime);
- fPerfStatCollector.digest();
- StatsStore.close();
-
- pause(wait);
- return result;
- }
-
- protected void pause(boolean wait) {
- if (!wait) return;
- fPrinter.printWaitPrompt();
- try {
- System.in.read();
- }
- catch(Exception e) {
- }
- }
-
- public static void main(String args[]) {
- StatTestRunner aTestRunner= new StatTestRunner();
- try {
- TestResult r= aTestRunner.start(args);
- if (!r.wasSuccessful())
- System.exit(FAILURE_EXIT);
- System.exit(SUCCESS_EXIT);
- } catch(Exception e) {
- System.err.println(e.getMessage());
- System.exit(EXCEPTION_EXIT);
- }
- }
-
- /**
- * Starts a test run. Analyzes the command line arguments
- * and runs the given test suite.
- */
- protected TestResult start(String args[]) throws Exception {
- String testCase= "";
- boolean wait= false;
-
- jdbcDriver = System.getProperty("android.coretests.driver", DEFAULT_DRIVER);
- connectionURL = System.getProperty("android.coretests.database", "jdbc:" + DEFAULT_DATABASE);
-
- for (int i= 0; i < args.length; i++) {
- if (args[i].equals("--all"))
- fPerfStatCollector.listAll = true;
- else if (args[i].equals("--bad"))
- fPerfStatCollector.listBad = true;
- else if (args[i].equals("--nobig"))
- fPerfStatCollector.bigMarking = false;
- else if (args[i].equals("--s")) {
- fPerfStatCollector.thresholdDuration =
- Integer.valueOf(args[++i]);
- } else if (args[i].equals("-wait"))
- wait= true;
- else if (args[i].equals("-c"))
- testCase= extractClassName(args[++i]);
- else if (args[i].equals("-v"))
- System.err.println("JUnit "+Version.id()+" (plus Android performance stats)");
- else
- testCase= args[i];
- }
-
- if (testCase.equals(""))
- throw new Exception("Usage: TestRunner [-wait] testCaseName, where name is the name of the TestCase class");
-
- try {
- Test suite= getTest(testCase);
- return doRun(suite, wait);
- }
- catch (Exception e) {
- throw new Exception("Exception: " + e);
- }
- }
-
- protected void runFailed(String message) {
- System.err.println(message);
- System.exit(FAILURE_EXIT);
- }
-
- public void setPrinter(ResultPrinter printer) {
- fPrinter= printer;
- }
-
-
-}
diff --git a/luni/src/test/java/com/google/coretests/StatsStore.java b/luni/src/test/java/com/google/coretests/StatsStore.java
deleted file mode 100644
index 2c18ab3..0000000
--- a/luni/src/test/java/com/google/coretests/StatsStore.java
+++ /dev/null
@@ -1,309 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.coretests;
-
-
-import junit.framework.Test;
-
-import java.io.File;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-
-
-public class StatsStore {
-
- static final String sysVersion = "1.0";
-
- static Connection conn;
- static Statement stmt;
- static PreparedStatement insertStmt, selectByNameStmt, updateStmt;
- static PreparedStatement insertDetStmt, insertEventStmt;
- static PreparedStatement selectAllStmt;
-
- public static long now;
-
- static int compareDuration(long dur, long refDur) {
- long diff = dur - refDur;
- if (diff <= 0) {
- if ((double)-diff / refDur > 0.5) return 1; // remarkably faster
- else return 0; // equivalent duration (maybe a bit faster)
- }
- else if (diff < 20) return 0; // not measurably slower: equivalent duration
- else if ((double)diff / refDur < 0.2) return 0; // just little slower: equivalent duration
- else return -1; // relevantly SLOWer
- }
-
- static void initStats(PerfStatCollector.Item a) {
- a.statMinDuration = a.duration;
- a.statMaxDuration = a.duration;
- a.statAvgDuration = a.duration;
- a.statCount = 1;
- }
-
- static void adjustStats(PerfStatCollector.Item a) {
- if (a.duration < a.statMinDuration) a.statMinDuration = a.duration;
- else
- if (a.duration > a.statMaxDuration) a.statMaxDuration = a.duration;
- a.statAvgDuration = ((a.statAvgDuration * a.statCount + a.duration) / (a.statCount + 1));
- a.statCount++;
- }
-
- static void adjustStatsOptimistic(PerfStatCollector.Item a) {
- adjustStats(a);
- // Could consider reducing a.statMaxDuration.
- }
-
- static void use1(PerfStatCollector.Item a) {
- Test test;
- int pos;
- PreparedStatement selectStmt = selectByNameStmt;
- try {
- try {
- insertStmt.setString(1, a.test.toString());
- insertStmt.execute();
- } catch (SQLException e) {}
- selectStmt.setString(1, a.test.toString());
- ResultSet row = selectStmt.executeQuery();
- row.first();
- pos = 1;
- a.id = row.getInt(pos); pos++;
- a.bestRes = row.getInt(pos); pos++;
- a.lastBestAt = row.getLong(pos); pos++;
- a.lastRes = row.getInt(pos); pos++;
- a.lastDuration = row.getLong(pos); pos++;
- a.statCount = row.getInt(pos); pos++;
- a.statAvgDuration = row.getDouble(pos); pos++;
- a.statMinDuration = row.getLong(pos); pos++;
- a.statMaxDuration = row.getLong(pos); pos++;
- if (a.res == 0) {
- if (a.bestRes == 100) {
- a.bestRes = 0; a.lastBestAt = now;
- a.histRelevance = 0; // Good from scratch.
- a.isTransition = false;
- initStats(a);
- } else if (a.bestRes != 0) {
- a.bestRes = 0; a.lastBestAt = now;
- a.histRelevance = 4; // "Good" for the first time:
- a.isTransition = true; // was bad before.
- initStats(a);
- } else if (a.lastRes != 0) {
- a.bestRes = 0; a.lastBestAt = now;
- a.histRelevance = 3; // "good" again:
- a.isTransition = true; // was bad in between.
- adjustStats(a);
- } else {
- // res == lastRes == bestRes == 0:
- int cmp = compareDuration(a.duration, a.statMinDuration);
- if (cmp >= 0) {
- a.bestRes = 0; a.lastBestAt = now;
- if (cmp > 0) {
- a.histRelevance = 2; // "Fast"er than ever before.
- a.isTransition = true;
- adjustStatsOptimistic(a);
- } else if (compareDuration(a.duration, a.lastDuration) > 0) {
- // As fast as best but faster than last run:
- a.histRelevance = 1; // "fast" again.
- a.isTransition = true;
- adjustStatsOptimistic(a);
- } else {
- a.histRelevance = 0; // Equivalent Duration:
- a.isTransition = false; // usual good case.
- adjustStats(a);
- }
- } else {
- if (compareDuration(a.duration, a.lastDuration) < 0) {
- a.histRelevance = -2; // "SLOW"!!!
- a.isTransition = true;
- adjustStats(a);
- } else {
- a.histRelevance = -2; // Still "SLOW"!!!
- a.isTransition = false; // (But NO transition!)
- adjustStats(a);
- }
- }
- }
- } else if (a.bestRes == 0) {
- if (a.lastRes == 0) {
- a.histRelevance = -4; // "VBAD"!!!
- a.isTransition = true;
- } else {
- a.histRelevance = -4; // Still "VBAD"!!!
- a.isTransition = false; // (But NO transition!)
- }
- // DON'T adjust statistics: they should reflect good runs, only.
- } else if (a.bestRes == 100) {
- a.bestRes = -3; // Just mark as NOT good.
- a.histRelevance = -3; // Bad (initial run).
- a.isTransition = true;
- initStats(a);
- } else {
- a.histRelevance = 0; // Still Failure or Error:
- a.isTransition = false; // usual bad case.
- adjustStats(a);
- }
- pos = 1;
- updateStmt.setInt(pos, a.bestRes); pos++;
- updateStmt.setLong(pos, a.lastBestAt); pos++;
- updateStmt.setInt(pos, a.res); pos++;
- updateStmt.setLong(pos, a.duration); pos++;
- updateStmt.setInt(pos, a.statCount); pos++;
- updateStmt.setDouble(pos, a.statAvgDuration); pos++;
- updateStmt.setLong(pos, a.statMinDuration); pos++;
- updateStmt.setLong(pos, a.statMaxDuration); pos++;
- updateStmt.setInt(pos, a.id); pos++;
- updateStmt.execute();
- pos = 1;
- insertDetStmt.setInt(pos, a.id); pos++;
- insertDetStmt.setLong(pos, now); pos++;
- insertDetStmt.setInt(pos, a.statCount); pos++;
- insertDetStmt.setInt(pos, a.res); pos++;
- insertDetStmt.setLong(pos, a.duration); pos++;
- insertDetStmt.execute();
- if (a.isTransition) {
- pos = 1;
- insertEventStmt.setInt(pos, a.id); pos++;
- insertEventStmt.setLong(pos, now); pos++;
- insertEventStmt.setInt(pos, a.histRelevance); pos++;
- insertEventStmt.setInt(pos, a.res); pos++;
- insertEventStmt.setLong(pos, a.duration); pos++;
- insertEventStmt.execute();
- }
- }
- catch (SQLException e) {
- int x = 0;
- }
- }
-
-// static void use2(PerfStatCollector.Item a) {
-// }
-
- static void execOrIgnore(String sql) {
- try { stmt.execute(sql); }
- catch (SQLException e) {}
- }
-
- static void open(String jdbcDriver, String connectionURL)
- throws Exception {
-// try {
- Class.forName(jdbcDriver).newInstance();
- conn = DriverManager.getConnection(connectionURL);
- stmt = conn.createStatement();
- String dbVersion;
- try {
- ResultSet res = stmt.executeQuery("SELECT id FROM Version");
- res.first();
- dbVersion = res.getString(1);
- }
- catch (SQLException e) {
- dbVersion = "";
- }
- if (!dbVersion.equals(sysVersion)) {
- execOrIgnore("DROP TABLE Test_Cases;");
- stmt.execute("CREATE TABLE Test_Cases (" +
- " id INTEGER PRIMARY KEY AUTOINCREMENT, " +
- " name VARCHAR(255) UNIQUE, " +
- // (best_Res != 0) ==> (last_Best_At == 0) never ran good!
- " best_Res INTEGER, last_Best_At INTEGER, " +
- " last_Res INTEGER, last_Duration INTEGER, " +
- " stat_Cnt INTEGER, stat_Avg NUMBER(20, 2), " +
- " stat_Min INTEGER, stat_Max INTEGER);");
- execOrIgnore("DROP TABLE Test_Case_Runs;");
- stmt.execute("CREATE TABLE Test_Case_Runs (" +
- " test_Id INTEGER, run_At INTEGER, " +
- " iteration INTEGER, res INTEGER, duration INTEGER, " +
- " PRIMARY KEY (test_Id, run_At));");
- execOrIgnore("DROP TABLE Test_Case_Events;");
- stmt.execute("CREATE TABLE Test_Case_Events (" +
- " test_Id INTEGER, run_At INTEGER, " +
- " relevance INTEGER, " +
- " res INTEGER, duration INTEGER, " +
- " PRIMARY KEY (test_Id, run_At));");
-// stmt.execute("CREATE PROCEDURE useSample (IN pName TEXT, " +
-// "pRes INTEGER, pDuration INTEGER, pTime INTEGER) " +
-// "BEGIN " +
-// " INSERT OR IGNORE INTO TestCases (name)" +
-// " VALUES (pName);" +
-// "END;");
- execOrIgnore("DROP TABLE Version;");
- stmt.execute("CREATE TABLE Version(id VARCHAR(31));");
- stmt.execute("INSERT INTO Version (id) VALUES ('" + sysVersion + "');");
- }
-// updateStmt = conn.prepareStatement("useSample(:name, :res, :duration, :time)");
- // firstConnection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
- // firstStmt = firstConnection.createStatement();
- // firstStmt.execute("create table tbl1(one varchar(10), two smallint)");
- insertStmt = conn.prepareStatement("INSERT " +
- "INTO Test_Cases (name, stat_Cnt) VALUES (?, 0);");
- selectByNameStmt = conn.prepareStatement("SELECT id, " +
- " IFNULL(best_Res, 100), IFNULL(last_Best_At, 0), " +
- " IFNULL(last_Res, 100), IFNULL(last_Duration, 0), " +
- " IFNULL(stat_Cnt, 0), IFNULL(stat_Avg, 0), " +
- " IFNULL(stat_Min, 0), IFNULL(stat_Max, 0) " +
- "FROM Test_Cases WHERE name = ?;");
- updateStmt = conn.prepareStatement("UPDATE Test_Cases SET " +
- " best_Res = ?, last_Best_At = ?, " +
- " last_Res = ?, last_Duration = ?, " +
- " stat_Cnt = ?, stat_Avg = ?, " +
- " stat_Min = ?, stat_Max = ? " +
- "WHERE id = ?;");
- insertDetStmt = conn.prepareStatement("INSERT " +
- "INTO Test_Case_Runs (test_Id, run_At, iteration, res, duration) " +
- "VALUES (?, ?, ?, ?, ?);");
- insertEventStmt = conn.prepareStatement("INSERT " +
- "INTO Test_Case_Events (test_Id, run_At, relevance, res, duration) " +
- "VALUES (?, ?, ?, ?, ?);");
- selectAllStmt = conn.prepareStatement("SELECT id, name, " +
- "last_Res, stat_Cnt, " +
- "last_Duration, stat_Avg, stat_Min, stat_Max " +
- "FROM Test_Cases;");
-
- try {
-// ResultSet res = stmt.executeQuery("PRAGMA CACHE_SIZE;");
-// res.first();
-// System.out.print("CACHE_SIZE = ");
-// System.out.println(res.getString(1));
-// stmt.execute("PRAGMA CACHE_SIZE = 5000;");
- stmt.execute("PRAGMA SYNCHRONOUS = OFF;");
- stmt.execute("PRAGMA temp_store = MEMORY;");
- }
- catch (SQLException e) {
- dbVersion = "";
- }
- stmt.close();
- conn.commit();
-// }
-// catch (Exception e) {
-// conn = null;
-// }
-// return conn != null;
- }
-
- static void close() {
- try {
- conn.commit();
- conn.close();
- conn = null;
- }
- catch (Exception e) {
- conn = null;
- }
- }
-}
diff --git a/luni/src/test/java/com/google/coretests/Version.java b/luni/src/test/java/com/google/coretests/Version.java
deleted file mode 100644
index e76a6bb..0000000
--- a/luni/src/test/java/com/google/coretests/Version.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.coretests;
-
-/**
- * This class defines the current version of JUnit
- */
-public class Version {
- private Version() {
- // don't instantiate
- }
-
- public static String id() {
- return "0.1";
- }
-}
diff --git a/luni/src/test/java/junit/runner/BaseTestRunner.java b/luni/src/test/java/junit/runner/BaseTestRunner.java
deleted file mode 100644
index 7e69b11..0000000
--- a/luni/src/test/java/junit/runner/BaseTestRunner.java
+++ /dev/null
@@ -1,326 +0,0 @@
-package junit.runner;
-
-import junit.framework.*;
-import java.lang.reflect.*;
-import java.text.NumberFormat;
-import java.io.*;
-import java.util.*;
-
-/**
- * Base class for all test runners.
- * This class was born live on stage in Sardinia during XP2000.
- */
-public abstract class BaseTestRunner implements TestListener {
- public static final String SUITE_METHODNAME= "suite";
-
- private static Properties fPreferences;
- static int fgMaxMessageLength= 500;
- static boolean fgFilterStack= true;
- boolean fLoading= true;
-
- /*
- * Implementation of TestListener
- */
- public synchronized void startTest(Test test) {
- testStarted(test.toString());
- }
-
- protected static void setPreferences(Properties preferences) {
- fPreferences= preferences;
- }
-
- protected static Properties getPreferences() {
- if (fPreferences == null) {
- fPreferences= new Properties();
- fPreferences.put("loading", "true");
- fPreferences.put("filterstack", "true");
- readPreferences();
- }
- return fPreferences;
- }
-
- public static void savePreferences() throws IOException {
- FileOutputStream fos= new FileOutputStream(getPreferencesFile());
- try {
- getPreferences().store(fos, "");
- } finally {
- fos.close();
- }
- }
-
- public void setPreference(String key, String value) {
- getPreferences().setProperty(key, value);
- }
-
- public synchronized void endTest(Test test) {
- testEnded(test.toString());
- }
-
- public synchronized void addError(final Test test, final Throwable t) {
- testFailed(TestRunListener.STATUS_ERROR, test, t);
- }
-
- public synchronized void addFailure(final Test test, final AssertionFailedError t) {
- testFailed(TestRunListener.STATUS_FAILURE, test, t);
- }
-
- // TestRunListener implementation
-
- public abstract void testStarted(String testName);
-
- public abstract void testEnded(String testName);
-
- public abstract void testFailed(int status, Test test, Throwable t);
-
- /**
- * Returns the Test corresponding to the given suite. This is
- * a template method, subclasses override runFailed(), clearStatus().
- */
- public Test getTest(String suiteClassName) {
- if (suiteClassName.length() <= 0) {
- clearStatus();
- return null;
- }
- Class testClass= null;
- try {
- testClass= loadSuiteClass(suiteClassName);
- } catch (ClassNotFoundException e) {
- String clazz= e.getMessage();
- if (clazz == null)
- clazz= suiteClassName;
- runFailed("Class not found \""+clazz+"\"");
- return null;
- } catch(Exception e) {
- runFailed("Error: "+e.toString());
- return null;
- }
- Method suiteMethod= null;
- try {
- suiteMethod= testClass.getMethod(SUITE_METHODNAME, new Class[0]);
- } catch(Exception e) {
- // try to extract a test suite automatically
- clearStatus();
- return new TestSuite(testClass);
- }
- if (! Modifier.isStatic(suiteMethod.getModifiers())) {
- runFailed("Suite() method must be static");
- return null;
- }
- Test test= null;
- try {
- test= (Test)suiteMethod.invoke(null); // static method
- if (test == null)
- return test;
- }
- catch (InvocationTargetException e) {
- runFailed("Failed to invoke suite():" + e.getTargetException().toString());
- return null;
- }
- catch (IllegalAccessException e) {
- runFailed("Failed to invoke suite():" + e.toString());
- return null;
- }
-
- clearStatus();
- return test;
- }
-
- /**
- * Returns the formatted string of the elapsed time.
- */
- public String elapsedTimeAsString(long runTime) {
- return NumberFormat.getInstance().format((double)runTime/1000);
- }
-
- /**
- * Processes the command line arguments and
- * returns the name of the suite class to run or null
- */
- protected String processArguments(String[] args) {
- String suiteName= null;
- for (int i= 0; i < args.length; i++) {
- if (args[i].equals("-noloading")) {
- setLoading(false);
- } else if (args[i].equals("-nofilterstack")) {
- fgFilterStack= false;
- } else if (args[i].equals("-c")) {
- if (args.length > i+1)
- suiteName= extractClassName(args[i+1]);
- else
- System.out.println("Missing Test class name");
- i++;
- } else {
- suiteName= args[i];
- }
- }
- return suiteName;
- }
-
- /**
- * Sets the loading behaviour of the test runner
- */
- public void setLoading(boolean enable) {
- fLoading= enable;
- }
- /**
- * Extract the class name from a String in VA/Java style
- */
- public String extractClassName(String className) {
- if(className.startsWith("Default package for"))
- return className.substring(className.lastIndexOf(".")+1);
- return className;
- }
-
- /**
- * Truncates a String to the maximum length.
- */
- public static String truncate(String s) {
- if (fgMaxMessageLength != -1 && s.length() > fgMaxMessageLength)
- s= s.substring(0, fgMaxMessageLength)+"...";
- return s;
- }
-
- /**
- * Override to define how to handle a failed loading of
- * a test suite.
- */
- protected abstract void runFailed(String message);
-
- /**
- * Returns the loaded Class for a suite name.
- */
- protected Class loadSuiteClass(String suiteClassName) throws ClassNotFoundException {
- return getLoader().load(suiteClassName);
- }
-
- /**
- * Clears the status message.
- */
- protected void clearStatus() { // Belongs in the GUI TestRunner class
- }
-
- /**
- * Returns the loader to be used.
- */
- public TestSuiteLoader getLoader() {
- if (useReloadingTestSuiteLoader())
- return new ReloadingTestSuiteLoader();
- return new StandardTestSuiteLoader();
- }
-
- protected boolean useReloadingTestSuiteLoader() {
- return getPreference("loading").equals("true") && !inVAJava() && fLoading;
- }
-
- private static File getPreferencesFile() {
- String home= System.getProperty("user.home");
- return new File(home, "junit.properties");
- }
-
- private static void readPreferences() {
- InputStream is= null;
- try {
- is= new FileInputStream(getPreferencesFile());
- setPreferences(new Properties(getPreferences()));
- getPreferences().load(is);
- } catch (IOException e) {
- try {
- if (is != null)
- is.close();
- } catch (IOException e1) {
- }
- }
- }
-
- public static String getPreference(String key) {
- return getPreferences().getProperty(key);
- }
-
- public static int getPreference(String key, int dflt) {
- String value= getPreference(key);
- int intValue= dflt;
- if (value == null)
- return intValue;
- try {
- intValue= Integer.parseInt(value);
- } catch (NumberFormatException ne) {
- }
- return intValue;
- }
-
- public static boolean inVAJava() {
- try {
- Class.forName("com.ibm.uvm.tools.DebugSupport");
- }
- catch (Exception e) {
- return false;
- }
- return true;
- }
-
- /**
- * Returns a filtered stack trace
- */
- public static String getFilteredTrace(Throwable t) {
- StringWriter stringWriter= new StringWriter();
- PrintWriter writer= new PrintWriter(stringWriter);
- t.printStackTrace(writer);
- StringBuffer buffer= stringWriter.getBuffer();
- String trace= buffer.toString();
- return BaseTestRunner.getFilteredTrace(trace);
- }
-
- /**
- * Filters stack frames from internal JUnit classes
- */
- public static String getFilteredTrace(String stack) {
- if (showStackRaw())
- return stack;
-
- StringWriter sw= new StringWriter();
- PrintWriter pw= new PrintWriter(sw);
- StringReader sr= new StringReader(stack);
- // BEGIN android-changed
- // Use a sensible default buffer size
- BufferedReader br= new BufferedReader(sr, 1000);
- // END android-changed
-
- String line;
- try {
- while ((line= br.readLine()) != null) {
- if (!filterLine(line))
- pw.println(line);
- }
- } catch (Exception IOException) {
- return stack; // return the stack unfiltered
- }
- return sw.toString();
- }
-
- protected static boolean showStackRaw() {
- return !getPreference("filterstack").equals("true") || fgFilterStack == false;
- }
-
- static boolean filterLine(String line) {
- String[] patterns= new String[] {
- "junit.framework.TestCase",
- "junit.framework.TestResult",
- "junit.framework.TestSuite",
- "junit.framework.Assert.", // don't filter AssertionFailure
- "junit.swingui.TestRunner",
- "junit.awtui.TestRunner",
- "junit.textui.TestRunner",
- "java.lang.reflect.Method.invoke("
- };
- for (int i= 0; i < patterns.length; i++) {
- if (line.indexOf(patterns[i]) > 0)
- return true;
- }
- return false;
- }
-
- static {
- fgMaxMessageLength= getPreference("maxmessage", fgMaxMessageLength);
- }
-
-}
diff --git a/luni/src/test/java/junit/runner/ClassPathTestCollector.java b/luni/src/test/java/junit/runner/ClassPathTestCollector.java
deleted file mode 100644
index 7143368..0000000
--- a/luni/src/test/java/junit/runner/ClassPathTestCollector.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package junit.runner;
-
-import java.util.*;
-import java.io.*;
-
-/**
- * An implementation of a TestCollector that consults the
- * class path. It considers all classes on the class path
- * excluding classes in JARs. It leaves it up to subclasses
- * to decide whether a class is a runnable Test.
- *
- * @see TestCollector
- */
-public abstract class ClassPathTestCollector implements TestCollector {
-
- static final int SUFFIX_LENGTH= ".class".length();
-
- public ClassPathTestCollector() {
- }
-
- public Enumeration collectTests() {
- String classPath= System.getProperty("java.class.path");
- Hashtable result = collectFilesInPath(classPath);
- return result.elements();
- }
-
- public Hashtable collectFilesInPath(String classPath) {
- Hashtable result= collectFilesInRoots(splitClassPath(classPath));
- return result;
- }
-
- Hashtable collectFilesInRoots(Vector roots) {
- Hashtable result= new Hashtable(100);
- Enumeration e= roots.elements();
- while (e.hasMoreElements())
- gatherFiles(new File((String)e.nextElement()), "", result);
- return result;
- }
-
- void gatherFiles(File classRoot, String classFileName, Hashtable result) {
- File thisRoot= new File(classRoot, classFileName);
- if (thisRoot.isFile()) {
- if (isTestClass(classFileName)) {
- String className= classNameFromFile(classFileName);
- result.put(className, className);
- }
- return;
- }
- String[] contents= thisRoot.list();
- if (contents != null) {
- for (int i= 0; i < contents.length; i++)
- gatherFiles(classRoot, classFileName+File.separatorChar+contents[i], result);
- }
- }
-
- Vector splitClassPath(String classPath) {
- Vector result= new Vector();
- String separator= System.getProperty("path.separator");
- StringTokenizer tokenizer= new StringTokenizer(classPath, separator);
- while (tokenizer.hasMoreTokens())
- result.addElement(tokenizer.nextToken());
- return result;
- }
-
- protected boolean isTestClass(String classFileName) {
- return
- classFileName.endsWith(".class") &&
- classFileName.indexOf('$') < 0 &&
- classFileName.indexOf("Test") > 0;
- }
-
- protected String classNameFromFile(String classFileName) {
- // convert /a/b.class to a.b
- String s= classFileName.substring(0, classFileName.length()-SUFFIX_LENGTH);
- String s2= s.replace(File.separatorChar, '.');
- if (s2.startsWith("."))
- return s2.substring(1);
- return s2;
- }
-}
diff --git a/luni/src/test/java/junit/runner/FailureDetailView.java b/luni/src/test/java/junit/runner/FailureDetailView.java
deleted file mode 100644
index b57df75..0000000
--- a/luni/src/test/java/junit/runner/FailureDetailView.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package junit.runner;
-
-// The following line was removed for compatibility with Android libraries.
-//import java.awt.Component;
-
-import junit.framework.*;
-
-/**
- * A view to show a details about a failure
- */
-public interface FailureDetailView {
- // The following definition was removed for compatibility with Android
- // libraries.
- // /**
- // * Returns the component used to present the TraceView
- // */
- // public Component getComponent();
-
- /**
- * Shows details of a TestFailure
- */
- public void showFailure(TestFailure failure);
- /**
- * Clears the view
- */
- public void clear();
-}
diff --git a/luni/src/test/java/junit/runner/LoadingTestCollector.java b/luni/src/test/java/junit/runner/LoadingTestCollector.java
deleted file mode 100644
index 056b7da..0000000
--- a/luni/src/test/java/junit/runner/LoadingTestCollector.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package junit.runner;
-
-import java.lang.reflect.*;
-import junit.runner.*;
-import junit.framework.*;
-
-/**
- * An implementation of a TestCollector that loads
- * all classes on the class path and tests whether
- * it is assignable from Test or provides a static suite method.
- * @see TestCollector
- */
-public class LoadingTestCollector extends ClassPathTestCollector {
-
- TestCaseClassLoader fLoader;
-
- public LoadingTestCollector() {
- fLoader= new TestCaseClassLoader();
- }
-
- protected boolean isTestClass(String classFileName) {
- try {
- if (classFileName.endsWith(".class")) {
- Class testClass= classFromFile(classFileName);
- return (testClass != null) && isTestClass(testClass);
- }
- }
- catch (ClassNotFoundException expected) {
- }
- catch (NoClassDefFoundError notFatal) {
- }
- return false;
- }
-
- Class classFromFile(String classFileName) throws ClassNotFoundException {
- String className= classNameFromFile(classFileName);
- if (!fLoader.isExcluded(className))
- return fLoader.loadClass(className, false);
- return null;
- }
-
- boolean isTestClass(Class testClass) {
- if (hasSuiteMethod(testClass))
- return true;
- if (Test.class.isAssignableFrom(testClass) &&
- Modifier.isPublic(testClass.getModifiers()) &&
- hasPublicConstructor(testClass))
- return true;
- return false;
- }
-
- boolean hasSuiteMethod(Class testClass) {
- try {
- testClass.getMethod(BaseTestRunner.SUITE_METHODNAME, new Class[0]);
- } catch(Exception e) {
- return false;
- }
- return true;
- }
-
- boolean hasPublicConstructor(Class testClass) {
- try {
- TestSuite.getTestConstructor(testClass);
- } catch(NoSuchMethodException e) {
- return false;
- }
- return true;
- }
-}
diff --git a/luni/src/test/java/junit/runner/ReloadingTestSuiteLoader.java b/luni/src/test/java/junit/runner/ReloadingTestSuiteLoader.java
deleted file mode 100644
index 93891b4..0000000
--- a/luni/src/test/java/junit/runner/ReloadingTestSuiteLoader.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package junit.runner;
-
-/**
- * A TestSuite loader that can reload classes.
- */
-public class ReloadingTestSuiteLoader implements TestSuiteLoader {
-
- public Class load(String suiteClassName) throws ClassNotFoundException {
- return createLoader().loadClass(suiteClassName, true);
- }
-
- public Class reload(Class aClass) throws ClassNotFoundException {
- return createLoader().loadClass(aClass.getName(), true);
- }
-
- protected TestCaseClassLoader createLoader() {
- return new TestCaseClassLoader();
- }
-}
diff --git a/luni/src/test/java/junit/runner/SimpleTestCollector.java b/luni/src/test/java/junit/runner/SimpleTestCollector.java
deleted file mode 100644
index 2f76296..0000000
--- a/luni/src/test/java/junit/runner/SimpleTestCollector.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package junit.runner;
-
-/**
- * An implementation of a TestCollector that considers
- * a class to be a test class when it contains the
- * pattern "Test" in its name
- * @see TestCollector
- */
-public class SimpleTestCollector extends ClassPathTestCollector {
-
- public SimpleTestCollector() {
- }
-
- protected boolean isTestClass(String classFileName) {
- return
- classFileName.endsWith(".class") &&
- classFileName.indexOf('$') < 0 &&
- classFileName.indexOf("Test") > 0;
- }
-}
diff --git a/luni/src/test/java/junit/runner/Sorter.java b/luni/src/test/java/junit/runner/Sorter.java
deleted file mode 100644
index 36ca7d3..0000000
--- a/luni/src/test/java/junit/runner/Sorter.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package junit.runner;
-
-import java.util.*;
-
-import junit.runner.*;
-
-/**
- * A custom quick sort with support to customize the swap behaviour.
- * NOTICE: We can't use the the sorting support from the JDK 1.2 collection
- * classes because of the JDK 1.1.7 compatibility.
- */
-public class Sorter {
- public static interface Swapper {
- public void swap(Vector values, int left, int right);
- }
-
- public static void sortStrings(Vector values , int left, int right, Swapper swapper) {
- int oleft= left;
- int oright= right;
- String mid= (String)values.elementAt((left + right) / 2);
- do {
- while (((String)(values.elementAt(left))).compareTo(mid) < 0)
- left++;
- while (mid.compareTo((String)(values.elementAt(right))) < 0)
- right--;
- if (left <= right) {
- swapper.swap(values, left, right);
- left++;
- right--;
- }
- } while (left <= right);
-
- if (oleft < right)
- sortStrings(values, oleft, right, swapper);
- if (left < oright)
- sortStrings(values, left, oright, swapper);
- }
-}
diff --git a/luni/src/test/java/junit/runner/StandardTestSuiteLoader.java b/luni/src/test/java/junit/runner/StandardTestSuiteLoader.java
deleted file mode 100644
index 1137675..0000000
--- a/luni/src/test/java/junit/runner/StandardTestSuiteLoader.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package junit.runner;
-
-/**
- * The standard test suite loader. It can only load the same class once.
- */
-public class StandardTestSuiteLoader implements TestSuiteLoader {
- /**
- * Uses the system class loader to load the test class
- */
- public Class load(String suiteClassName) throws ClassNotFoundException {
- return Class.forName(suiteClassName);
- }
- /**
- * Uses the system class loader to load the test class
- */
- public Class reload(Class aClass) throws ClassNotFoundException {
- return aClass;
- }
-}
diff --git a/luni/src/test/java/junit/runner/TestCaseClassLoader.java b/luni/src/test/java/junit/runner/TestCaseClassLoader.java
deleted file mode 100644
index 7e4e2b1..0000000
--- a/luni/src/test/java/junit/runner/TestCaseClassLoader.java
+++ /dev/null
@@ -1,226 +0,0 @@
-package junit.runner;
-
-import java.util.*;
-import java.io.*;
-import java.net.URL;
-import java.util.zip.*;
-
-/**
- * A custom class loader which enables the reloading
- * of classes for each test run. The class loader
- * can be configured with a list of package paths that
- * should be excluded from loading. The loading
- * of these packages is delegated to the system class
- * loader. They will be shared across test runs.
- * <p>
- * The list of excluded package paths is specified in
- * a properties file "excluded.properties" that is located in
- * the same place as the TestCaseClassLoader class.
- * <p>
- * <b>Known limitation:</b> the TestCaseClassLoader cannot load classes
- * from jar files.
- */
-
-
-public class TestCaseClassLoader extends ClassLoader {
- /** scanned class path */
- private Vector fPathItems;
- /** default excluded paths */
- private String[] defaultExclusions= {
- "junit.framework.",
- "junit.extensions.",
- "junit.runner."
- };
- /** name of excluded properties file */
- static final String EXCLUDED_FILE= "excluded.properties";
- /** excluded paths */
- private Vector fExcluded;
-
- /**
- * Constructs a TestCaseLoader. It scans the class path
- * and the excluded package paths
- */
- public TestCaseClassLoader() {
- this(System.getProperty("java.class.path"));
- }
-
- /**
- * Constructs a TestCaseLoader. It scans the class path
- * and the excluded package paths
- */
- public TestCaseClassLoader(String classPath) {
- scanPath(classPath);
- readExcludedPackages();
- }
-
- private void scanPath(String classPath) {
- String separator= System.getProperty("path.separator");
- fPathItems= new Vector(10);
- StringTokenizer st= new StringTokenizer(classPath, separator);
- while (st.hasMoreTokens()) {
- fPathItems.addElement(st.nextToken());
- }
- }
-
- public URL getResource(String name) {
- return ClassLoader.getSystemResource(name);
- }
-
- public InputStream getResourceAsStream(String name) {
- return ClassLoader.getSystemResourceAsStream(name);
- }
-
- public boolean isExcluded(String name) {
- for (int i= 0; i < fExcluded.size(); i++) {
- if (name.startsWith((String) fExcluded.elementAt(i))) {
- return true;
- }
- }
- return false;
- }
-
- public synchronized Class loadClass(String name, boolean resolve)
- throws ClassNotFoundException {
-
- Class c= findLoadedClass(name);
- if (c != null)
- return c;
- //
- // Delegate the loading of excluded classes to the
- // standard class loader.
- //
- if (isExcluded(name)) {
- try {
- c= findSystemClass(name);
- return c;
- } catch (ClassNotFoundException e) {
- // keep searching
- }
- }
- if (c == null) {
- byte[] data= lookupClassData(name);
- if (data == null)
- throw new ClassNotFoundException();
- c= defineClass(name, data, 0, data.length);
- }
- if (resolve)
- resolveClass(c);
- return c;
- }
-
- private byte[] lookupClassData(String className) throws ClassNotFoundException {
- byte[] data= null;
- for (int i= 0; i < fPathItems.size(); i++) {
- String path= (String) fPathItems.elementAt(i);
- String fileName= className.replace('.', '/')+".class";
- if (isJar(path)) {
- data= loadJarData(path, fileName);
- } else {
- data= loadFileData(path, fileName);
- }
- if (data != null)
- return data;
- }
- throw new ClassNotFoundException(className);
- }
-
- boolean isJar(String pathEntry) {
- return pathEntry.endsWith(".jar") ||
- pathEntry.endsWith(".apk") ||
- pathEntry.endsWith(".zip");
- }
-
- private byte[] loadFileData(String path, String fileName) {
- File file= new File(path, fileName);
- if (file.exists()) {
- return getClassData(file);
- }
- return null;
- }
-
- private byte[] getClassData(File f) {
- try {
- FileInputStream stream= new FileInputStream(f);
- ByteArrayOutputStream out= new ByteArrayOutputStream(1000);
- byte[] b= new byte[1000];
- int n;
- while ((n= stream.read(b)) != -1)
- out.write(b, 0, n);
- stream.close();
- out.close();
- return out.toByteArray();
-
- } catch (IOException e) {
- }
- return null;
- }
-
- private byte[] loadJarData(String path, String fileName) {
- ZipFile zipFile= null;
- InputStream stream= null;
- File archive= new File(path);
- if (!archive.exists())
- return null;
- try {
- zipFile= new ZipFile(archive);
- } catch(IOException io) {
- return null;
- }
- ZipEntry entry= zipFile.getEntry(fileName);
- if (entry == null)
- return null;
- int size= (int) entry.getSize();
- try {
- stream= zipFile.getInputStream(entry);
- byte[] data= new byte[size];
- int pos= 0;
- while (pos < size) {
- int n= stream.read(data, pos, data.length - pos);
- pos += n;
- }
- zipFile.close();
- return data;
- } catch (IOException e) {
- } finally {
- try {
- if (stream != null)
- stream.close();
- } catch (IOException e) {
- }
- }
- return null;
- }
-
- private void readExcludedPackages() {
- fExcluded= new Vector(10);
- for (int i= 0; i < defaultExclusions.length; i++)
- fExcluded.addElement(defaultExclusions[i]);
-
- InputStream is= getClass().getResourceAsStream(EXCLUDED_FILE);
- if (is == null)
- return;
- Properties p= new Properties();
- try {
- p.load(is);
- }
- catch (IOException e) {
- return;
- } finally {
- try {
- is.close();
- } catch (IOException e) {
- }
- }
- for (Enumeration e= p.propertyNames(); e.hasMoreElements(); ) {
- String key= (String)e.nextElement();
- if (key.startsWith("excluded.")) {
- String path= p.getProperty(key);
- path= path.trim();
- if (path.endsWith("*"))
- path= path.substring(0, path.length()-1);
- if (path.length() > 0)
- fExcluded.addElement(path);
- }
- }
- }
-}
diff --git a/luni/src/test/java/junit/runner/TestCollector.java b/luni/src/test/java/junit/runner/TestCollector.java
deleted file mode 100644
index 1f7de09..0000000
--- a/luni/src/test/java/junit/runner/TestCollector.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package junit.runner;
-
-import java.util.*;
-
-
-/**
- * Collects Test class names to be presented
- * by the TestSelector.
- * @see TestSelector
- */
-public interface TestCollector {
- /**
- * Returns an enumeration of Strings with qualified class names
- */
- public Enumeration collectTests();
-}
diff --git a/luni/src/test/java/junit/runner/TestRunListener.java b/luni/src/test/java/junit/runner/TestRunListener.java
deleted file mode 100644
index b11ef07..0000000
--- a/luni/src/test/java/junit/runner/TestRunListener.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package junit.runner;
-/**
- * A listener interface for observing the
- * execution of a test run. Unlike TestListener,
- * this interface using only primitive objects,
- * making it suitable for remote test execution.
- */
- public interface TestRunListener {
- /* test status constants*/
- public static final int STATUS_ERROR= 1;
- public static final int STATUS_FAILURE= 2;
-
- public void testRunStarted(String testSuiteName, int testCount);
- public void testRunEnded(long elapsedTime);
- public void testRunStopped(long elapsedTime);
- public void testStarted(String testName);
- public void testEnded(String testName);
- public void testFailed(int status, String testName, String trace);
-}
diff --git a/luni/src/test/java/junit/runner/TestSuiteLoader.java b/luni/src/test/java/junit/runner/TestSuiteLoader.java
deleted file mode 100644
index 581ea23..0000000
--- a/luni/src/test/java/junit/runner/TestSuiteLoader.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package junit.runner;
-
-/**
- * An interface to define how a test suite should be loaded.
- */
-public interface TestSuiteLoader {
- abstract public Class load(String suiteClassName) throws ClassNotFoundException;
- abstract public Class reload(Class aClass) throws ClassNotFoundException;
-}
diff --git a/luni/src/test/java/junit/runner/Version.java b/luni/src/test/java/junit/runner/Version.java
deleted file mode 100644
index e231750..0000000
--- a/luni/src/test/java/junit/runner/Version.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package junit.runner;
-
-/**
- * This class defines the current version of JUnit
- */
-public class Version {
- private Version() {
- // don't instantiate
- }
-
- public static String id() {
- return "3.8.1";
- }
-}
diff --git a/luni/src/test/java/junit/runner/excluded.properties b/luni/src/test/java/junit/runner/excluded.properties
deleted file mode 100644
index 3284628..0000000
--- a/luni/src/test/java/junit/runner/excluded.properties
+++ /dev/null
@@ -1,12 +0,0 @@
-#
-# The list of excluded package paths for the TestCaseClassLoader
-#
-excluded.0=sun.*
-excluded.1=com.sun.*
-excluded.2=org.omg.*
-excluded.3=javax.*
-excluded.4=sunw.*
-excluded.5=java.*
-excluded.6=org.w3c.dom.*
-excluded.7=org.xml.sax.*
-excluded.8=net.jini.*
diff --git a/luni/src/test/java/junit/runner/logo.gif b/luni/src/test/java/junit/runner/logo.gif
deleted file mode 100644
index d0e1547..0000000
--- a/luni/src/test/java/junit/runner/logo.gif
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/java/junit/runner/smalllogo.gif b/luni/src/test/java/junit/runner/smalllogo.gif
deleted file mode 100644
index 7b25eaf..0000000
--- a/luni/src/test/java/junit/runner/smalllogo.gif
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/java/junit/textui/ResultPrinter.java b/luni/src/test/java/junit/textui/ResultPrinter.java
deleted file mode 100644
index df3d99f..0000000
--- a/luni/src/test/java/junit/textui/ResultPrinter.java
+++ /dev/null
@@ -1,142 +0,0 @@
-
-package junit.textui;
-
-import java.io.PrintStream;
-// The following line was removed for compatibility with Android libraries.
-//import java.text.NumberFormat;
-import java.util.Enumeration;
-
-import junit.framework.AssertionFailedError;
-import junit.framework.Test;
-import junit.framework.TestFailure;
-import junit.framework.TestListener;
-import junit.framework.TestResult;
-import junit.runner.BaseTestRunner;
-
-public class ResultPrinter implements TestListener {
- PrintStream fWriter;
- int fColumn= 0;
-
- public ResultPrinter(PrintStream writer) {
- fWriter= writer;
- }
-
- /* API for use by textui.TestRunner
- */
-
- synchronized void print(TestResult result, long runTime) {
- printHeader(runTime);
- printErrors(result);
- printFailures(result);
- printFooter(result);
- }
-
- void printWaitPrompt() {
- getWriter().println();
- getWriter().println("<RETURN> to continue");
- }
-
- /* Internal methods
- */
-
- protected void printHeader(long runTime) {
- getWriter().println();
- getWriter().println("Time: "+elapsedTimeAsString(runTime));
- }
-
- protected void printErrors(TestResult result) {
- printDefects(result.errors(), result.errorCount(), "error");
- }
-
- protected void printFailures(TestResult result) {
- printDefects(result.failures(), result.failureCount(), "failure");
- }
-
- protected void printDefects(Enumeration booBoos, int count, String type) {
- if (count == 0) return;
- if (count == 1)
- getWriter().println("There was " + count + " " + type + ":");
- else
- getWriter().println("There were " + count + " " + type + "s:");
- for (int i= 1; booBoos.hasMoreElements(); i++) {
- printDefect((TestFailure) booBoos.nextElement(), i);
- }
- }
-
- public void printDefect(TestFailure booBoo, int count) { // only public for testing purposes
- printDefectHeader(booBoo, count);
- printDefectTrace(booBoo);
- }
-
- protected void printDefectHeader(TestFailure booBoo, int count) {
- // I feel like making this a println, then adding a line giving the throwable a chance to print something
- // before we get to the stack trace.
- getWriter().print(count + ") " + booBoo.failedTest());
- }
-
- protected void printDefectTrace(TestFailure booBoo) {
- getWriter().print(BaseTestRunner.getFilteredTrace(booBoo.trace()));
- }
-
- protected void printFooter(TestResult result) {
- if (result.wasSuccessful()) {
- getWriter().println();
- getWriter().print("OK");
- getWriter().println (" (" + result.runCount() + " test" + (result.runCount() == 1 ? "": "s") + ")");
-
- } else {
- getWriter().println();
- getWriter().println("FAILURES!!!");
- getWriter().println("Tests run: "+result.runCount()+
- ", Failures: "+result.failureCount()+
- ", Errors: "+result.errorCount());
- }
- getWriter().println();
- }
-
-
- /**
- * Returns the formatted string of the elapsed time.
- * Duplicated from BaseTestRunner. Fix it.
- */
- protected String elapsedTimeAsString(long runTime) {
- // The following line was altered for compatibility with
- // Android libraries.
- return Double.toString((double)runTime/1000);
- }
-
- public PrintStream getWriter() {
- return fWriter;
- }
- /**
- * @see junit.framework.TestListener#addError(Test, Throwable)
- */
- public void addError(Test test, Throwable t) {
- getWriter().print("E");
- }
-
- /**
- * @see junit.framework.TestListener#addFailure(Test, AssertionFailedError)
- */
- public void addFailure(Test test, AssertionFailedError t) {
- getWriter().print("F");
- }
-
- /**
- * @see junit.framework.TestListener#endTest(Test)
- */
- public void endTest(Test test) {
- }
-
- /**
- * @see junit.framework.TestListener#startTest(Test)
- */
- public void startTest(Test test) {
- getWriter().print(".");
- if (fColumn++ >= 40) {
- getWriter().println();
- fColumn= 0;
- }
- }
-
-}
diff --git a/luni/src/test/java/junit/textui/TestRunner.java b/luni/src/test/java/junit/textui/TestRunner.java
deleted file mode 100644
index e966bcb..0000000
--- a/luni/src/test/java/junit/textui/TestRunner.java
+++ /dev/null
@@ -1,189 +0,0 @@
-package junit.textui;
-
-
-import java.io.PrintStream;
-
-import junit.framework.*;
-import junit.runner.*;
-
-/**
- * A command line based tool to run tests.
- * <pre>
- * java junit.textui.TestRunner [-wait] TestCaseClass
- * </pre>
- * TestRunner expects the name of a TestCase class as argument.
- * If this class defines a static <code>suite</code> method it
- * will be invoked and the returned test is run. Otherwise all
- * the methods starting with "test" having no arguments are run.
- * <p>
- * When the wait command line argument is given TestRunner
- * waits until the users types RETURN.
- * <p>
- * TestRunner prints a trace as the tests are executed followed by a
- * summary at the end.
- */
-public class TestRunner extends BaseTestRunner {
- private ResultPrinter fPrinter;
-
- public static final int SUCCESS_EXIT= 0;
- public static final int FAILURE_EXIT= 1;
- public static final int EXCEPTION_EXIT= 2;
-
- /**
- * Constructs a TestRunner.
- */
- public TestRunner() {
- this(System.out);
- }
-
- /**
- * Constructs a TestRunner using the given stream for all the output
- */
- public TestRunner(PrintStream writer) {
- this(new ResultPrinter(writer));
- }
-
- /**
- * Constructs a TestRunner using the given ResultPrinter all the output
- */
- public TestRunner(ResultPrinter printer) {
- fPrinter= printer;
- }
-
- /**
- * Runs a suite extracted from a TestCase subclass.
- */
- static public void run(Class testClass) {
- run(new TestSuite(testClass));
- }
-
- /**
- * Runs a single test and collects its results.
- * This method can be used to start a test run
- * from your program.
- * <pre>
- * public static void main (String[] args) {
- * test.textui.TestRunner.run(suite());
- * }
- * </pre>
- */
- static public TestResult run(Test test) {
- TestRunner runner= new TestRunner();
- return runner.doRun(test);
- }
-
- /**
- * Runs a single test and waits until the user
- * types RETURN.
- */
- static public void runAndWait(Test suite) {
- TestRunner aTestRunner= new TestRunner();
- aTestRunner.doRun(suite, true);
- }
-
- /**
- * Always use the StandardTestSuiteLoader. Overridden from
- * BaseTestRunner.
- */
- public TestSuiteLoader getLoader() {
- return new StandardTestSuiteLoader();
- }
-
- public void testFailed(int status, Test test, Throwable t) {
- }
-
- public void testStarted(String testName) {
- }
-
- public void testEnded(String testName) {
- }
-
- /**
- * Creates the TestResult to be used for the test run.
- */
- protected TestResult createTestResult() {
- return new TestResult();
- }
-
- public TestResult doRun(Test test) {
- return doRun(test, false);
- }
-
- public TestResult doRun(Test suite, boolean wait) {
- TestResult result= createTestResult();
- result.addListener(fPrinter);
- long startTime= System.currentTimeMillis();
- suite.run(result);
- long endTime= System.currentTimeMillis();
- long runTime= endTime-startTime;
- fPrinter.print(result, runTime);
-
- pause(wait);
- return result;
- }
-
- protected void pause(boolean wait) {
- if (!wait) return;
- fPrinter.printWaitPrompt();
- try {
- System.in.read();
- }
- catch(Exception e) {
- }
- }
-
- public static void main(String args[]) {
- TestRunner aTestRunner= new TestRunner();
- try {
- TestResult r= aTestRunner.start(args);
- if (!r.wasSuccessful())
- System.exit(FAILURE_EXIT);
- System.exit(SUCCESS_EXIT);
- } catch(Exception e) {
- System.err.println(e.getMessage());
- System.exit(EXCEPTION_EXIT);
- }
- }
-
- /**
- * Starts a test run. Analyzes the command line arguments
- * and runs the given test suite.
- */
- protected TestResult start(String args[]) throws Exception {
- String testCase= "";
- boolean wait= false;
-
- for (int i= 0; i < args.length; i++) {
- if (args[i].equals("-wait"))
- wait= true;
- else if (args[i].equals("-c"))
- testCase= extractClassName(args[++i]);
- else if (args[i].equals("-v"))
- System.err.println("JUnit "+Version.id()+" by Kent Beck and Erich Gamma");
- else
- testCase= args[i];
- }
-
- if (testCase.equals(""))
- throw new Exception("Usage: TestRunner [-wait] testCaseName, where name is the name of the TestCase class");
-
- try {
- Test suite= getTest(testCase);
- return doRun(suite, wait);
- }
- catch(Exception e) {
- throw new Exception("Could not create and run test suite: "+e);
- }
- }
-
- protected void runFailed(String message) {
- System.err.println(message);
- System.exit(FAILURE_EXIT);
- }
-
- public void setPrinter(ResultPrinter printer) {
- fPrinter= printer;
- }
-
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/AllTests.java b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/AllTests.java
deleted file mode 100644
index 6b4cbd0..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/AllTests.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.internal.net.www.protocol.http;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-/**
- * This is autogenerated source file. Includes tests for package tests.api.javax.net.ssl;
- */
-
-public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(AllTests.suite());
- }
-
- public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for HttpURLConnecton, HttpsURLConnection.");
- // $JUnit-BEGIN$
-
- suite.addTestSuite(HttpURLConnectionTest.class);
-
- // $JUnit-END$
- return suite;
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/HttpURLConnectionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/HttpURLConnectionTest.java
deleted file mode 100644
index 258062f..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/HttpURLConnectionTest.java
+++ /dev/null
@@ -1,340 +0,0 @@
-/*
- * 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.harmony.luni.tests.internal.net.www.protocol.http;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.IOException;
-import java.net.Authenticator;
-import java.net.HttpURLConnection;
-import java.net.InetSocketAddress;
-import java.net.PasswordAuthentication;
-import java.net.Proxy;
-import java.net.ProxySelector;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.SocketAddress;
-import java.net.SocketTimeoutException;
-import java.net.URI;
-import java.net.URL;
-import java.util.ArrayList;
-
-import junit.framework.TestCase;
-
-
-/**
- * Tests for <code>HTTPURLConnection</code> class constructors and methods.
- *
- */
-@TestTargetClass(HttpURLConnection.class)
-public class HttpURLConnectionTest extends TestCase {
-
- private final static Object bound = new Object();
-
- static class MockServer extends Thread {
- ServerSocket serverSocket;
- boolean accepted = false;
- boolean started = false;
-
- public MockServer(String name) throws IOException {
- super(name);
- serverSocket = new ServerSocket(0);
- serverSocket.setSoTimeout(1000);
- }
-
- public int port() {
- return serverSocket.getLocalPort();
- }
-
- @Override
- public void run() {
- try {
- synchronized (bound) {
- started = true;
- bound.notify();
- }
- try {
- serverSocket.accept().close();
- accepted = true;
- } catch (SocketTimeoutException ignore) {
- }
- serverSocket.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- static class MockProxyServer extends MockServer {
-
- boolean acceptedAuthorizedRequest;
-
- public MockProxyServer(String name) throws Exception {
- super(name);
- }
-
- @Override
- public void run() {
- try {
- Socket socket = serverSocket.accept();
- socket.setSoTimeout(1000);
- byte[] buff = new byte[1024];
- int num = socket.getInputStream().read(buff);
- socket.getOutputStream().write((
- "HTTP/1.0 407 Proxy authentication required\n"
- + "Proxy-authenticate: Basic realm=\"remotehost\"\n\n")
- .getBytes());
- num = socket.getInputStream().read(buff);
- if (num == -1) {
- // this connection was closed, create new one:
- socket = serverSocket.accept();
- socket.setSoTimeout(1000);
- num = socket.getInputStream().read(buff);
- }
- String request = new String(buff, 0, num);
- acceptedAuthorizedRequest =
- request.toLowerCase().indexOf("proxy-authorization:") > 0;
- if (acceptedAuthorizedRequest) {
- socket.getOutputStream().write((
- "HTTP/1.1 200 OK\n\n").getBytes());
- }
- } catch (IOException e) {
- }
- }
- }
-
- /**
- * ProxySelector implementation used in the test.
- */
- static class TestProxySelector extends ProxySelector {
- // proxy port
- private int proxy_port;
- // server port
- private int server_port;
-
- /**
- * Creates proxy selector instance.
- * Selector will return the proxy, only if the connection
- * is made to localhost:server_port. Otherwise it will
- * return NO_PROXY.
- * Address of the returned proxy will be localhost:proxy_port.
- */
- public TestProxySelector(int server_port, int proxy_port) {
- this.server_port = server_port;
- this.proxy_port = proxy_port;
- }
-
- @Override
- public java.util.List<Proxy> select(URI uri) {
- Proxy proxy = Proxy.NO_PROXY;
- if (("localhost".equals(uri.getHost()))
- && (server_port == uri.getPort())) {
- proxy = new Proxy(Proxy.Type.HTTP,
- new InetSocketAddress("localhost", proxy_port));
- }
- ArrayList<Proxy> result = new ArrayList<Proxy>();
- result.add(proxy);
- return result;
- }
-
- @Override
- public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
- // do nothing
- }
- }
-
- /**
- * @tests org.apache.harmony.luni.internal.net.www.http.getOutputStream()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Regression test.",
- method = "getOutputStream",
- args = {}
- )
- public void testGetOutputStream() throws Exception {
- // Regression for HARMONY-482
- MockServer httpServer =
- new MockServer("ServerSocket for HttpURLConnectionTest");
- httpServer.start();
- synchronized(bound) {
- if (!httpServer.started) {
- bound.wait(5000);
- }
- }
- HttpURLConnection c = (HttpURLConnection)
- new URL("http://127.0.0.1:" + httpServer.port()).openConnection();
- c.setDoOutput(true);
- //use new String("POST") instead of simple "POST" to obtain other
- //object instances then those that are in HttpURLConnection classes
- c.setRequestMethod(new String("POST"));
- c.getOutputStream();
- httpServer.join();
- }
-
-
- /**
- * Test checks if the proxy specified in openConnection
- * method will be used for connection to the server
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies if the proxy specified in openConnection method will be used for connection to the server.",
- method = "usingProxy",
- args = {}
- )
- public void testUsingProxy() throws Exception {
- // Regression for HARMONY-570
- MockServer server = new MockServer("server");
- MockServer proxy = new MockServer("proxy");
-
- URL url = new URL("http://localhost:" + server.port());
-
- HttpURLConnection connection = (HttpURLConnection) url
- .openConnection(new Proxy(Proxy.Type.HTTP,
- new InetSocketAddress("localhost",
- proxy.port())));
- connection.setConnectTimeout(2000);
- connection.setReadTimeout(2000);
-
- server.start();
- synchronized(bound) {
- if (!server.started) bound.wait(5000);
- }
- proxy.start();
- synchronized(bound) {
- if (!proxy.started) bound.wait(5000);
- }
-
- connection.connect();
-
- // wait while server and proxy run
- server.join();
- proxy.join();
-
- assertTrue("Connection does not use proxy", connection.usingProxy());
- assertTrue("Proxy server was not used", proxy.accepted);
-
- HttpURLConnection huc = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
- assertFalse(huc.usingProxy());
- }
-
- /**
- * Test checks if the proxy provided by proxy selector
- * will be used for connection to the server
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies if the proxy provided by proxy selector will be used for connection to the server.",
- method = "usingProxy",
- args = {}
- )
- public void testUsingProxySelector() throws Exception {
- // Regression for HARMONY-570
- MockServer server = new MockServer("server");
- MockServer proxy = new MockServer("proxy");
-
- URL url = new URL("http://localhost:" + server.port());
-
- // keep default proxy selector
- ProxySelector defPS = ProxySelector.getDefault();
- // replace selector
- ProxySelector.setDefault(
- new TestProxySelector(server.port(), proxy.port()));
-
- try {
- HttpURLConnection connection =
- (HttpURLConnection) url.openConnection();
- connection.setConnectTimeout(2000);
- connection.setReadTimeout(2000);
-
- server.start();
- synchronized(bound) {
- if (!server.started) bound.wait(5000);
- }
- proxy.start();
- synchronized(bound) {
- if (!proxy.started) bound.wait(5000);
- }
- connection.connect();
-
- // wait while server and proxy run
- server.join();
- proxy.join();
-
- assertTrue("Connection does not use proxy",
- connection.usingProxy());
- assertTrue("Proxy server was not used", proxy.accepted);
- } finally {
- // restore default proxy selector
- ProxySelector.setDefault(defPS);
- }
- }
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Regression test.",
- method = "getResponseCode",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Regression test.",
- method = "connect",
- args = {}
- )
- })
- public void testProxyAuthorization() throws Exception {
- // Set up test Authenticator
- Authenticator.setDefault(new Authenticator() {
- @Override
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(
- "user", "password".toCharArray());
- }
- });
-
- try {
- MockProxyServer proxy = new MockProxyServer("ProxyServer");
-
- URL url = new URL("http://remotehost:55555/requested.data");
- HttpURLConnection connection =
- (HttpURLConnection) url.openConnection(
- new Proxy(Proxy.Type.HTTP,
- new InetSocketAddress("localhost", proxy.port())));
- connection.setConnectTimeout(1000);
- connection.setReadTimeout(1000);
-
- proxy.start();
-
- connection.connect();
- assertEquals("unexpected response code",
- 200, connection.getResponseCode());
- proxy.join();
- assertTrue("Connection did not send proxy authorization request",
- proxy.acceptedAuthorizedRequest);
- } finally {
- // remove previously set authenticator
- Authenticator.setDefault(null);
- }
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/AllTests.java b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/AllTests.java
deleted file mode 100644
index a58850b..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/AllTests.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.internal.net.www.protocol.https;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-
-/**
- * This is autogenerated source file. Includes tests for package tests.api.javax.net.ssl;
- */
-
-public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(AllTests.suite());
- }
-
- public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for HttpURLConnecton, HttpsURLConnection.");
- // $JUnit-BEGIN$
-
- suite.addTestSuite(HttpsURLConnectionTest.class);
-
- // $JUnit-END$
- return suite;
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java
deleted file mode 100644
index 319418f..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/HttpsURLConnectionTest.java
+++ /dev/null
@@ -1,1513 +0,0 @@
-/*
- * 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.harmony.luni.tests.internal.net.www.protocol.https;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.net.Authenticator;
-import java.net.HttpURLConnection;
-import java.net.InetSocketAddress;
-import java.net.PasswordAuthentication;
-import java.net.Proxy;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.SocketTimeoutException;
-import java.net.URL;
-import java.security.KeyStore;
-import java.security.cert.Certificate;
-import java.util.Arrays;
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLServerSocket;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.TrustManagerFactory;
-
-import junit.framework.TestCase;
-
-/**
- * Implementation independent test for HttpsURLConnection.
- * The test needs certstore file placed in system classpath
- * and named as "key_store." + the type of the
- * default KeyStore installed in the system in lower case.
- * <br>
- * For example: if default KeyStore type in the system is BKS
- * (i.e. java.security file sets up the property keystore.type=BKS),
- * thus classpath should point to the directory with "key_store.bks"
- * file.
- * <br>
- * This certstore file should contain self-signed certificate
- * generated by keytool utility in a usual way.
- * <br>
- * The password to the certstore should be "password" (without quotes).
- */
-@TestTargetClass(HttpsURLConnection.class)
-@AndroidOnly("we only have a .bks key store in the test resources")
-public class HttpsURLConnectionTest extends TestCase {
-
- // the password to the store
- private static final String KS_PASSWORD = "password";
-
- // turn on/off logging
- private static final boolean DO_LOG = false;
-
- // read/connection timeout value
- private static final int TIMEOUT = 5000;
-
- // OK response code
- private static final int OK_CODE = 200;
-
- // Not Found response code
- private static final int NOT_FOUND_CODE = 404;
-
- // Proxy authentication required response code
- private static final int AUTHENTICATION_REQUIRED_CODE = 407;
-
- // fields keeping the system values of corresponding properties
- private static String systemKeyStoreType;
-
- private static String systemKeyStore;
-
- private static String systemKeyStorePassword;
-
- private static String systemTrustStoreType;
-
- private static String systemTrustStore;
-
- private static String systemTrustStorePassword;
-
- private static File store;
-
- static {
- try {
- store = File.createTempFile("key_store", "bks");
- } catch (Exception e) {
- // ignore
- }
- }
-
- /**
- * Checks that HttpsURLConnection's default SSLSocketFactory is operable.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies that HttpsURLConnection's default SSLSocketFactory is operable.",
- method = "getDefaultSSLSocketFactory",
- args = {}
- )
- public void testGetDefaultSSLSocketFactory() throws Exception {
- // set up the properties defining the default values needed by SSL stuff
- setUpStoreProperties();
-
- try {
- SSLSocketFactory defaultSSLSF = HttpsURLConnection
- .getDefaultSSLSocketFactory();
- ServerSocket ss = new ServerSocket(0);
- Socket s = defaultSSLSF
- .createSocket("localhost", ss.getLocalPort());
- ss.accept();
- s.close();
- ss.close();
- } finally {
- // roll the properties back to system values
- tearDownStoreProperties();
- }
- }
-
- /**
- * Checks if HTTPS connection performs initial SSL handshake with the
- * server working over SSL, sends encrypted HTTP request,
- * and receives expected HTTP response. After HTTPS session if finished
- * test checks connection state parameters established by
- * HttpsURLConnection.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies if HTTPS connection performs initial SSL handshake with the server working over SSL, sends encrypted HTTP request, and receives expected HTTP response.",
- method = "setDefaultHostnameVerifier",
- args = {javax.net.ssl.HostnameVerifier.class}
- )
- @KnownFailure("VM aborts after more than one test was run.")
- public void testHttpsConnection() throws Throwable {
- // set up the properties defining the default values needed by SSL stuff
- setUpStoreProperties();
-
- try {
- // create the SSL server socket acting as a server
- SSLContext ctx = getContext();
- ServerSocket ss = ctx.getServerSocketFactory()
- .createServerSocket(0);
-
- // create the HostnameVerifier to check hostname verification
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
-
- // create url connection to be tested
- URL url = new URL("https://localhost:" + ss.getLocalPort());
- HttpsURLConnection connection = (HttpsURLConnection) url
- .openConnection();
-
- // perform the interaction between the peers
- SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss);
-
- // check the connection state
- checkConnectionStateParameters(connection, peerSocket);
-
- // should silently exit
- connection.connect();
- } finally {
- // roll the properties back to system values
- tearDownStoreProperties();
- }
- }
-
- /**
- * Tests the behaviour of HTTPS connection in case of unavailability
- * of requested resource.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies the behaviour of HTTPS connection in case of unavailability of requested resource.",
- method = "setDoInput",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies the behaviour of HTTPS connection in case of unavailability of requested resource.",
- method = "setConnectTimeout",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies the behaviour of HTTPS connection in case of unavailability of requested resource.",
- method = "setReadTimeout",
- args = {int.class}
- )
- })
- @KnownFailure("VM aborts after more than one test was run.")
- public void testHttpsConnection_Not_Found_Response() throws Throwable {
- // set up the properties defining the default values needed by SSL stuff
- setUpStoreProperties();
-
- try {
- // create the SSL server socket acting as a server
- SSLContext ctx = getContext();
- ServerSocket ss = ctx.getServerSocketFactory()
- .createServerSocket(0);
-
- // create the HostnameVerifier to check hostname verification
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
-
- // create url connection to be tested
- URL url = new URL("https://localhost:" + ss.getLocalPort());
- HttpsURLConnection connection = (HttpsURLConnection) url
- .openConnection();
-
- try {
- doInteraction(connection, ss, NOT_FOUND_CODE);
- fail("Expected exception was not thrown.");
- } catch (FileNotFoundException e) {
- if (DO_LOG) {
- System.out.println("Expected exception was thrown: "
- + e.getMessage());
- }
- }
-
- // should silently exit
- connection.connect();
- } finally {
- // roll the properties back to system values
- tearDownStoreProperties();
- }
- }
-
- /**
- * Tests possibility to set up the default SSLSocketFactory
- * to be used by HttpsURLConnection.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies possibility to set up the default SSLSocketFactory to be used by HttpsURLConnection.",
- method = "setDefaultSSLSocketFactory",
- args = {javax.net.ssl.SSLSocketFactory.class}
- )
- public void testSetDefaultSSLSocketFactory() throws Throwable {
- // create the SSLServerSocket which will be used by server side
- SSLContext ctx = getContext();
- SSLServerSocket ss = (SSLServerSocket) ctx.getServerSocketFactory()
- .createServerSocket(0);
-
- SSLSocketFactory socketFactory = (SSLSocketFactory) ctx
- .getSocketFactory();
- // set up the factory as default
- HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
- // check the result
- assertSame("Default SSLSocketFactory differs from expected",
- socketFactory, HttpsURLConnection.getDefaultSSLSocketFactory());
-
- // create the HostnameVerifier to check hostname verification
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
-
- // create HttpsURLConnection to be tested
- URL url = new URL("https://localhost:" + ss.getLocalPort());
- HttpsURLConnection connection = (HttpsURLConnection) url
- .openConnection();
-
- TestHostnameVerifier hnv_late = new TestHostnameVerifier();
- // late initialization: should not be used for created connection
- HttpsURLConnection.setDefaultHostnameVerifier(hnv_late);
-
- // perform the interaction between the peers
- SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss);
- // check the connection state
- checkConnectionStateParameters(connection, peerSocket);
- // check the verification process
- assertTrue("Hostname verification was not done", hnv.verified);
- assertFalse(
- "Hostname verification should not be done by this verifier",
- hnv_late.verified);
- // check the used SSLSocketFactory
- assertSame("Default SSLSocketFactory should be used",
- HttpsURLConnection.getDefaultSSLSocketFactory(), connection
- .getSSLSocketFactory());
-
- // should silently exit
- connection.connect();
- }
-
- /**
- * Tests possibility to set up the SSLSocketFactory
- * to be used by HttpsURLConnection.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies possibility to set up the SSLSocketFactory to be used by HttpsURLConnection.",
- method = "setSSLSocketFactory",
- args = {javax.net.ssl.SSLSocketFactory.class}
- )
- public void testSetSSLSocketFactory() throws Throwable {
- // create the SSLServerSocket which will be used by server side
- SSLContext ctx = getContext();
- SSLServerSocket ss = (SSLServerSocket) ctx.getServerSocketFactory()
- .createServerSocket(0);
-
- // create the HostnameVerifier to check hostname verification
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
-
- // create HttpsURLConnection to be tested
- URL url = new URL("https://localhost:" + ss.getLocalPort());
- HttpsURLConnection connection = (HttpsURLConnection) url
- .openConnection();
-
- SSLSocketFactory socketFactory = (SSLSocketFactory) ctx
- .getSocketFactory();
- connection.setSSLSocketFactory(socketFactory);
-
- TestHostnameVerifier hnv_late = new TestHostnameVerifier();
- // late initialization: should not be used for created connection
- HttpsURLConnection.setDefaultHostnameVerifier(hnv_late);
-
- // perform the interaction between the peers
- SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss);
- // check the connection state
- checkConnectionStateParameters(connection, peerSocket);
- // check the verification process
- assertTrue("Hostname verification was not done", hnv.verified);
- assertFalse(
- "Hostname verification should not be done by this verifier",
- hnv_late.verified);
- // check the used SSLSocketFactory
- assertNotSame("Default SSLSocketFactory should not be used",
- HttpsURLConnection.getDefaultSSLSocketFactory(), connection
- .getSSLSocketFactory());
- assertSame("Result differs from expected", socketFactory, connection
- .getSSLSocketFactory());
-
- // should silently exit
- connection.connect();
- }
-
- /**
- * Tests the behaviour of HttpsURLConnection in case of retrieving
- * of the connection state parameters before connection has been made.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the behaviour of HttpsURLConnection in case of retrieving of the connection state parameters before connection has been made.",
- method = "getCipherSuite",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the behaviour of HttpsURLConnection in case of retrieving of the connection state parameters before connection has been made.",
- method = "getPeerPrincipal",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the behaviour of HttpsURLConnection in case of retrieving of the connection state parameters before connection has been made.",
- method = "getLocalPrincipal",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the behaviour of HttpsURLConnection in case of retrieving of the connection state parameters before connection has been made.",
- method = "getServerCertificates",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the behaviour of HttpsURLConnection in case of retrieving of the connection state parameters before connection has been made.",
- method = "getLocalCertificates",
- args = {}
- )
- })
- public void testUnconnectedStateParameters() throws Throwable {
- // create HttpsURLConnection to be tested
- URL url = new URL("https://localhost:55555");
- HttpsURLConnection connection = (HttpsURLConnection) url
- .openConnection();
-
- try {
- connection.getCipherSuite();
- fail("Expected IllegalStateException was not thrown");
- } catch (IllegalStateException e) {}
- try {
- connection.getPeerPrincipal();
- fail("Expected IllegalStateException was not thrown");
- } catch (IllegalStateException e) {}
- try {
- connection.getLocalPrincipal();
- fail("Expected IllegalStateException was not thrown");
- } catch (IllegalStateException e) {}
-
- try {
- connection.getServerCertificates();
- fail("Expected IllegalStateException was not thrown");
- } catch (IllegalStateException e) {}
- try {
- connection.getLocalCertificates();
- fail("Expected IllegalStateException was not thrown");
- } catch (IllegalStateException e) {}
- }
-
- /**
- * Tests if setHostnameVerifier() method replaces default verifier.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies if setHostnameVerifier() method replaces default verifier.",
- method = "setHostnameVerifier",
- args = {javax.net.ssl.HostnameVerifier.class}
- )
- @KnownFailure("VM aborts after more than one test was run.")
- public void testSetHostnameVerifier() throws Throwable {
- // setting up the properties pointing to the key/trust stores
- setUpStoreProperties();
-
- try {
- // create the SSLServerSocket which will be used by server side
- SSLServerSocket ss = (SSLServerSocket) getContext()
- .getServerSocketFactory().createServerSocket(0);
-
- // create the HostnameVerifier to check that Hostname verification
- // is done
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
-
- // create HttpsURLConnection to be tested
- URL url = new URL("https://localhost:" + ss.getLocalPort());
- HttpsURLConnection connection = (HttpsURLConnection) url
- .openConnection();
-
- TestHostnameVerifier hnv_late = new TestHostnameVerifier();
- // replace default verifier
- connection.setHostnameVerifier(hnv_late);
-
- // perform the interaction between the peers and check the results
- SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss);
- assertTrue("Hostname verification was not done", hnv_late.verified);
- assertFalse(
- "Hostname verification should not be done by this verifier",
- hnv.verified);
- checkConnectionStateParameters(connection, peerSocket);
-
- // should silently exit
- connection.connect();
- } finally {
- // roll the properties back to system values
- tearDownStoreProperties();
- }
- }
-
- /**
- * Tests the behaviour in case of sending the data to the server.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies the behaviour in case of sending the data to the server.",
- method = "setDoOutput",
- args = {boolean.class}
- )
- @KnownFailure("VM aborts after more than one test was run.")
- public void test_doOutput() throws Throwable {
- // setting up the properties pointing to the key/trust stores
- setUpStoreProperties();
-
- try {
- // create the SSLServerSocket which will be used by server side
- SSLServerSocket ss = (SSLServerSocket) getContext()
- .getServerSocketFactory().createServerSocket(0);
-
- // create the HostnameVerifier to check that Hostname verification
- // is done
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
-
- // create HttpsURLConnection to be tested
- URL url = new URL("https://localhost:" + ss.getLocalPort());
- HttpsURLConnection connection = (HttpsURLConnection) url
- .openConnection();
- connection.setDoOutput(true);
-
- // perform the interaction between the peers and check the results
- SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss);
- checkConnectionStateParameters(connection, peerSocket);
-
- // should silently exit
- connection.connect();
- } finally {
- // roll the properties back to system values
- tearDownStoreProperties();
- }
- }
-
- /**
- * Tests HTTPS connection process made through the proxy server.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies HTTPS connection process made through the proxy server.",
- method = "setDoInput",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies HTTPS connection process made through the proxy server.",
- method = "setConnectTimeout",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies HTTPS connection process made through the proxy server.",
- method = "setReadTimeout",
- args = {int.class}
- )
- })
- @KnownFailure("VM aborts after more than one test was run.")
- public void testProxyConnection() throws Throwable {
- // setting up the properties pointing to the key/trust stores
- setUpStoreProperties();
-
- try {
- // create the SSLServerSocket which will be used by server side
- ServerSocket ss = new ServerSocket(0);
-
- // create the HostnameVerifier to check that Hostname verification
- // is done
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
-
- // create HttpsURLConnection to be tested
- URL url = new URL("https://requested.host:55556/requested.data");
- HttpsURLConnection connection = (HttpsURLConnection) url
- .openConnection(new Proxy(Proxy.Type.HTTP,
- new InetSocketAddress("localhost", ss
- .getLocalPort())));
-
- // perform the interaction between the peers and check the results
- SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss);
- checkConnectionStateParameters(connection, peerSocket);
-
- // should silently exit
- connection.connect();
- } finally {
- // roll the properties back to system values
- tearDownStoreProperties();
- }
- }
-
- /**
- * Tests HTTPS connection process made through the proxy server.
- * Proxy server needs authentication.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies HTTPS connection process made through the proxy server. Proxy server needs authentication.",
- method = "setDoInput",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies HTTPS connection process made through the proxy server. Proxy server needs authentication.",
- method = "setConnectTimeout",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies HTTPS connection process made through the proxy server. Proxy server needs authentication.",
- method = "setReadTimeout",
- args = {int.class}
- )
- })
- @KnownFailure("VM aborts after more than one test was run.")
- public void testProxyAuthConnection() throws Throwable {
- // setting up the properties pointing to the key/trust stores
- setUpStoreProperties();
-
- try {
- // create the SSLServerSocket which will be used by server side
- ServerSocket ss = new ServerSocket(0);
-
- // create the HostnameVerifier to check that Hostname verification
- // is done
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
-
- Authenticator.setDefault(new Authenticator() {
-
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication("user", "password"
- .toCharArray());
- }
- });
-
- // create HttpsURLConnection to be tested
- URL url = new URL("https://requested.host:55555/requested.data");
- HttpsURLConnection connection = (HttpsURLConnection) url
- .openConnection(new Proxy(Proxy.Type.HTTP,
- new InetSocketAddress("localhost", ss
- .getLocalPort())));
-
- // perform the interaction between the peers and check the results
- SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss);
- checkConnectionStateParameters(connection, peerSocket);
-
- // should silently exit
- connection.connect();
- } finally {
- // roll the properties back to system values
- tearDownStoreProperties();
- }
- }
-
- /**
- * Tests HTTPS connection process made through the proxy server.
- * 2 HTTPS connections are opened for one URL. For the first time
- * the connection is opened through one proxy,
- * for the second time through another.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies HTTPS connection process made through the proxy server.",
- method = "getCipherSuite",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies HTTPS connection process made through the proxy server.",
- method = "getLocalPrincipal",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies HTTPS connection process made through the proxy server.",
- method = "getPeerPrincipal",
- args = {}
- )
- })
- @KnownFailure("VM aborts after more than one test was run.")
- public void testConsequentProxyConnection() throws Throwable {
- // setting up the properties pointing to the key/trust stores
- setUpStoreProperties();
-
- try {
- // create the SSLServerSocket which will be used by server side
- ServerSocket ss = new ServerSocket(0);
-
- // create the HostnameVerifier to check that Hostname verification
- // is done
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
-
- // create HttpsURLConnection to be tested
- URL url = new URL("https://requested.host:55555/requested.data");
- HttpsURLConnection connection = (HttpsURLConnection) url
- .openConnection(new Proxy(Proxy.Type.HTTP,
- new InetSocketAddress("localhost", ss
- .getLocalPort())));
-
- // perform the interaction between the peers and check the results
- SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss);
- checkConnectionStateParameters(connection, peerSocket);
-
- // create another SSLServerSocket which will be used by server side
- ss = new ServerSocket(0);
-
- connection = (HttpsURLConnection) url.openConnection(new Proxy(
- Proxy.Type.HTTP, new InetSocketAddress("localhost", ss
- .getLocalPort())));
-
- // perform the interaction between the peers and check the results
- peerSocket = (SSLSocket) doInteraction(connection, ss);
- checkConnectionStateParameters(connection, peerSocket);
- } finally {
- // roll the properties back to system values
- tearDownStoreProperties();
- }
- }
-
- /**
- * Tests HTTPS connection process made through the proxy server.
- * Proxy server needs authentication.
- * Client sends data to the server.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies HTTPS connection process made through the proxy server. Proxy server needs authentication. Client sends data to the server.",
- method = "setDoInput",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies HTTPS connection process made through the proxy server. Proxy server needs authentication. Client sends data to the server.",
- method = "setConnectTimeout",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies HTTPS connection process made through the proxy server. Proxy server needs authentication. Client sends data to the server.",
- method = "setReadTimeout",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies HTTPS connection process made through the proxy server. Proxy server needs authentication. Client sends data to the server.",
- method = "setDoOutput",
- args = {boolean.class}
- )
- })
- @KnownFailure("VM aborts after more than one test was run.")
- public void testProxyAuthConnection_doOutput() throws Throwable {
- // setting up the properties pointing to the key/trust stores
- setUpStoreProperties();
-
- try {
- // create the SSLServerSocket which will be used by server side
- ServerSocket ss = new ServerSocket(0);
-
- // create the HostnameVerifier to check that Hostname verification
- // is done
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
-
- Authenticator.setDefault(new Authenticator() {
-
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication("user", "password"
- .toCharArray());
- }
- });
-
- // create HttpsURLConnection to be tested
- URL url = new URL("https://requested.host:55554/requested.data");
- HttpsURLConnection connection = (HttpsURLConnection) url
- .openConnection(new Proxy(Proxy.Type.HTTP,
- new InetSocketAddress("localhost", ss
- .getLocalPort())));
- connection.setDoOutput(true);
-
- // perform the interaction between the peers and check the results
- SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss,
- OK_CODE, true);
- checkConnectionStateParameters(connection, peerSocket);
- } finally {
- // roll the properties back to system values
- tearDownStoreProperties();
- }
- }
-
- /**
- * Tests HTTPS connection process made through the proxy server.
- * Proxy server needs authentication but client fails to authenticate
- * (Authenticator was not set up in the system).
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies HTTPS connection process made through the proxy server. Proxy server needs authentication but client fails to authenticate (Authenticator was not set up in the system).",
- method = "setDoInput",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies HTTPS connection process made through the proxy server. Proxy server needs authentication but client fails to authenticate (Authenticator was not set up in the system).",
- method = "setConnectTimeout",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies HTTPS connection process made through the proxy server. Proxy server needs authentication but client fails to authenticate (Authenticator was not set up in the system).",
- method = "setReadTimeout",
- args = {int.class}
- )
- })
- @KnownFailure("VM aborts after more than one test was run.")
- public void testProxyAuthConnectionFailed() throws Throwable {
- // setting up the properties pointing to the key/trust stores
- setUpStoreProperties();
-
- try {
- // create the SSLServerSocket which will be used by server side
- ServerSocket ss = new ServerSocket(0);
-
- // create the HostnameVerifier to check that Hostname verification
- // is done
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
-
- // create HttpsURLConnection to be tested
- URL url = new URL("https://requested.host:55555/requested.data");
- HttpURLConnection connection = (HttpURLConnection) url
- .openConnection(new Proxy(Proxy.Type.HTTP,
- new InetSocketAddress("localhost", ss
- .getLocalPort())));
-
- // perform the interaction between the peers and check the results
- try {
- doInteraction(connection, ss, AUTHENTICATION_REQUIRED_CODE,
- true);
- } catch (IOException e) {
- // SSL Tunnelling failed
- if (DO_LOG) {
- System.out.println("Got expected IOException: "
- + e.getMessage());
- }
- }
- } finally {
- // roll the properties back to system values
- tearDownStoreProperties();
- }
- }
-
- /**
- * Tests the behaviour of HTTPS connection in case of unavailability
- * of requested resource.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies the behaviour of HTTPS connection in case of unavailability of requested resource.",
- method = "setDoInput",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies the behaviour of HTTPS connection in case of unavailability of requested resource.",
- method = "setConnectTimeout",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies the behaviour of HTTPS connection in case of unavailability of requested resource.",
- method = "setReadTimeout",
- args = {int.class}
- )
- })
- @KnownFailure("VM aborts after more than one test was run.")
- public void testProxyConnection_Not_Found_Response() throws Throwable {
- // setting up the properties pointing to the key/trust stores
- setUpStoreProperties();
-
- try {
- // create the SSLServerSocket which will be used by server side
- ServerSocket ss = new ServerSocket(0);
-
- // create the HostnameVerifier to check that Hostname verification
- // is done
- TestHostnameVerifier hnv = new TestHostnameVerifier();
- HttpsURLConnection.setDefaultHostnameVerifier(hnv);
-
- // create HttpsURLConnection to be tested
- URL url = new URL("https://localhost:" + ss.getLocalPort());
- HttpURLConnection connection = (HttpURLConnection) url
- .openConnection(new Proxy(Proxy.Type.HTTP,
- new InetSocketAddress("localhost", ss
- .getLocalPort())));
-
- try {
- doInteraction(connection, ss, NOT_FOUND_CODE); // NOT FOUND
- fail("Expected exception was not thrown.");
- } catch (FileNotFoundException e) {
- if (DO_LOG) {
- System.out.println("Expected exception was thrown: "
- + e.getMessage());
- }
- }
- } finally {
- // roll the properties back to system values
- tearDownStoreProperties();
- }
- }
-
- // ---------------------------------------------------------------------
- // ------------------------ Staff Methods ------------------------------
- // ---------------------------------------------------------------------
-
- /**
- * Log the name of the test case to be executed.
- */
- public void setUp() throws Exception {
- if (DO_LOG) {
- System.out.println();
- System.out.println("------------------------");
- System.out.println("------ " + getName());
- System.out.println("------------------------");
- }
-
- if (store != null) {
- String ksFileName = "org/apache/harmony/luni/tests/key_store."
- + KeyStore.getDefaultType().toLowerCase();
- InputStream in = ClassLoader.getSystemClassLoader()
- .getResourceAsStream(ksFileName);
- FileOutputStream out = new FileOutputStream(store);
- BufferedInputStream bufIn = new BufferedInputStream(in, 8192);
- while (bufIn.available() > 0) {
- byte[] buf = new byte[128];
- int read = bufIn.read(buf);
- out.write(buf, 0, read);
- }
- bufIn.close();
- out.close();
- } else {
- fail("couldn't set up key store");
- }
- }
-
- public void tearDown() {
- if (store != null) {
- store.delete();
- }
- }
-
- /**
- * Checks the HttpsURLConnection getter's values and compares
- * them with actual corresponding values of remote peer.
- */
- public static void checkConnectionStateParameters(
- HttpsURLConnection clientConnection, SSLSocket serverPeer)
- throws Exception {
- SSLSession session = serverPeer.getSession();
-
- assertEquals(session.getCipherSuite(), clientConnection
- .getCipherSuite());
-
- assertEquals(session.getLocalPrincipal(), clientConnection
- .getPeerPrincipal());
-
- assertEquals(session.getPeerPrincipal(), clientConnection
- .getLocalPrincipal());
-
- Certificate[] serverCertificates = clientConnection
- .getServerCertificates();
- Certificate[] localCertificates = session.getLocalCertificates();
- assertTrue("Server certificates differ from expected", Arrays.equals(
- serverCertificates, localCertificates));
-
- localCertificates = clientConnection.getLocalCertificates();
- serverCertificates = session.getPeerCertificates();
- assertTrue("Local certificates differ from expected", Arrays.equals(
- serverCertificates, localCertificates));
- }
-
- /**
- * Returns the file name of the key/trust store. The key store file
- * (named as "key_store." + extension equals to the default KeyStore
- * type installed in the system in lower case) is searched in classpath.
- * @throws AssertionFailedError if property was not set
- * or file does not exist.
- */
- private static String getKeyStoreFileName() {
- return store.getAbsolutePath();
- }
-
- /**
- * Builds and returns the context used for secure socket creation.
- */
- private static SSLContext getContext() throws Exception {
- String type = KeyStore.getDefaultType();
- SSLContext ctx;
-
- String keyStore = getKeyStoreFileName();
- File keyStoreFile = new File(keyStore);
-
- FileInputStream fis = new FileInputStream(keyStoreFile);
-
- KeyStore ks = KeyStore.getInstance(type);
- ks.load(fis, KS_PASSWORD.toCharArray());
-
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory
- .getDefaultAlgorithm());
- kmf.init(ks, KS_PASSWORD.toCharArray());
-
- TrustManagerFactory tmf = TrustManagerFactory
- .getInstance(TrustManagerFactory.getDefaultAlgorithm());
- tmf.init(ks);
-
- ctx = SSLContext.getInstance("TLSv1");
- ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
-
- return ctx;
- }
-
- /**
- * Sets up the properties pointing to the key store and trust store
- * and used as default values by JSSE staff. This is needed to test
- * HTTPS behaviour in the case of default SSL Socket Factories.
- */
- private static void setUpStoreProperties() throws Exception {
- String type = KeyStore.getDefaultType();
-
- systemKeyStoreType = System.getProperty("javax.net.ssl.keyStoreType");
- systemKeyStore = System.getProperty("javax.net.ssl.keyStore");
- systemKeyStorePassword = System
- .getProperty("javax.net.ssl.keyStorePassword");
-
- systemTrustStoreType = System
- .getProperty("javax.net.ssl.trustStoreType");
- systemTrustStore = System.getProperty("javax.net.ssl.trustStore");
- systemTrustStorePassword = System
- .getProperty("javax.net.ssl.trustStorePassword");
-
- System.setProperty("javax.net.ssl.keyStoreType", type);
- System.setProperty("javax.net.ssl.keyStore", getKeyStoreFileName());
- System.setProperty("javax.net.ssl.keyStorePassword", KS_PASSWORD);
-
- System.setProperty("javax.net.ssl.trustStoreType", type);
- System.setProperty("javax.net.ssl.trustStore", getKeyStoreFileName());
- System.setProperty("javax.net.ssl.trustStorePassword", KS_PASSWORD);
- }
-
- /**
- * Rolls back the values of system properties.
- */
- private static void tearDownStoreProperties() {
- if (systemKeyStoreType == null) {
- System.clearProperty("javax.net.ssl.keyStoreType");
- } else {
- System
- .setProperty("javax.net.ssl.keyStoreType",
- systemKeyStoreType);
- }
- if (systemKeyStore == null) {
- System.clearProperty("javax.net.ssl.keyStore");
- } else {
- System.setProperty("javax.net.ssl.keyStore", systemKeyStore);
- }
- if (systemKeyStorePassword == null) {
- System.clearProperty("javax.net.ssl.keyStorePassword");
- } else {
- System.setProperty("javax.net.ssl.keyStorePassword",
- systemKeyStorePassword);
- }
-
- if (systemTrustStoreType == null) {
- System.clearProperty("javax.net.ssl.trustStoreType");
- } else {
- System.setProperty("javax.net.ssl.trustStoreType",
- systemTrustStoreType);
- }
- if (systemTrustStore == null) {
- System.clearProperty("javax.net.ssl.trustStore");
- } else {
- System.setProperty("javax.net.ssl.trustStore", systemTrustStore);
- }
- if (systemTrustStorePassword == null) {
- System.clearProperty("javax.net.ssl.trustStorePassword");
- } else {
- System.setProperty("javax.net.ssl.trustStorePassword",
- systemTrustStorePassword);
- }
- }
-
- /**
- * Performs interaction between client's HttpURLConnection and
- * servers side (ServerSocket).
- */
- public static Socket doInteraction(
- final HttpURLConnection clientConnection,
- final ServerSocket serverSocket) throws Throwable {
- return doInteraction(clientConnection, serverSocket, OK_CODE, false);
- }
-
- /**
- * Performs interaction between client's HttpURLConnection and
- * servers side (ServerSocket). Server will response with specified
- * response code.
- */
- public static Socket doInteraction(
- final HttpURLConnection clientConnection,
- final ServerSocket serverSocket, final int responseCode)
- throws Throwable {
- return doInteraction(clientConnection, serverSocket, responseCode,
- false);
- }
-
- /**
- * Performs interaction between client's HttpURLConnection and
- * servers side (ServerSocket). Server will response with specified
- * response code.
- * @param doAuthentication specifies
- * if the server needs client authentication.
- */
- public static Socket doInteraction(
- final HttpURLConnection clientConnection,
- final ServerSocket serverSocket, final int responseCode,
- final boolean doAuthentication) throws Throwable {
-
- // set up the connection
- clientConnection.setDoInput(true);
- clientConnection.setConnectTimeout(TIMEOUT);
- clientConnection.setReadTimeout(TIMEOUT);
-
- ServerWork server = new ServerWork(serverSocket, responseCode,
- doAuthentication);
-
- ClientConnectionWork client = new ClientConnectionWork(clientConnection);
-
- server.start();
- client.start();
-
- client.join();
- server.join();
-
- if (client.thrown != null) {
- if (responseCode != OK_CODE) { // not OK response expected
- // it is probably expected exception, keep it as is
- throw client.thrown;
- }
- if ((client.thrown instanceof SocketTimeoutException)
- && (server.thrown != null)) {
- // server's exception is more informative in this case
- throw new Exception(server.thrown);
- } else {
- throw new Exception(client.thrown);
- }
- }
- if (server.thrown != null) {
- throw server.thrown;
- }
- return server.peerSocket;
- }
-
- /**
- * The host name verifier used in test.
- */
- static class TestHostnameVerifier implements HostnameVerifier {
-
- boolean verified = false;
-
- public boolean verify(String hostname, SSLSession session) {
- if (DO_LOG) {
- System.out.println("***> verification " + hostname + " "
- + session.getPeerHost());
- }
- verified = true;
- return true;
- }
- }
-
- /**
- * The base class for mock Client and Server.
- */
- static class Work extends Thread {
-
- /**
- * The header of OK HTTP response.
- */
- static String responseHead = "HTTP/1.1 200 OK\n";
-
- /**
- * The content of the response.
- */
- static String plainResponseContent = "<HTML>\n"
- + "<HEAD><TITLE>Plain Response Content</TITLE></HEAD>\n"
- + "</HTML>";
-
- /**
- * The tail of the response.
- */
- static String plainResponseTail = "Content-type: text/html\n"
- + "Content-length: " + plainResponseContent.length() + "\n\n"
- + plainResponseContent;
-
- /**
- * The response message to be sent in plain (HTTP) format.
- */
- static String plainResponse = responseHead + plainResponseTail;
-
- /**
- * The content of the response to be sent during HTTPS session.
- */
- static String httpsResponseContent = "<HTML>\n"
- + "<HEAD><TITLE>HTTPS Response Content</TITLE></HEAD>\n"
- + "</HTML>";
-
- /**
- * The tail of the response to be sent during HTTPS session.
- */
- static String httpsResponseTail = "Content-type: text/html\n"
- + "Content-length: " + httpsResponseContent.length() + "\n\n"
- + httpsResponseContent;
-
- /**
- * The response requiring client's proxy authentication.
- */
- static String respAuthenticationRequired = "HTTP/1.0 407 Proxy authentication required\n"
- + "Proxy-authenticate: Basic realm=\"localhost\"\n\n";
-
- /**
- * The data to be posted by client to the server.
- */
- static String clientsData = "_.-^ Client's Data ^-._";
-
- /**
- * The exception thrown during peers interaction.
- */
- protected Throwable thrown;
-
- /**
- * The print stream used for debug log.
- * If it is null debug info will not be printed.
- */
- private PrintStream out = new PrintStream(System.out);
-
- /**
- * Prints log message.
- */
- public synchronized void log(String message) {
- if (DO_LOG && (out != null)) {
- System.out.println("[" + getName() + "]: " + message);
- }
- }
- }
-
- /**
- * The class used for server side works.
- */
- static class ServerWork extends Work {
-
- // the server socket used for connection
- private ServerSocket serverSocket;
-
- // the socket connected with client peer
- private Socket peerSocket;
-
- // indicates if the server acts as proxy server
- private boolean actAsProxy;
-
- // indicates if the server needs proxy authentication
- private boolean needProxyAuthentication;
-
- // response code to be send to the client peer
- private int responseCode;
-
- /**
- * Creates the thread acting as a server side.
- */
- public ServerWork(ServerSocket serverSocket) {
- // the server does not require proxy authentication
- // and sends OK_CODE (OK) response code
- this(serverSocket, OK_CODE, false);
- }
-
- /**
- * Creates the thread acting as a server side.
- * @param serverSocket the server socket to be used during connection
- * @param responseCode the response code to be sent to the client
- * @param needProxyAuthentication
- * indicates if the server needs proxy authentication
- */
- public ServerWork(ServerSocket serverSocket, int responseCode,
- boolean needProxyAuthentication) {
- this.serverSocket = serverSocket;
- this.responseCode = responseCode;
- this.needProxyAuthentication = needProxyAuthentication;
- // will act as a proxy server if the specified server socket
- // is not a secure server socket
- if (serverSocket instanceof SSLServerSocket) {
- // demand client to send its certificate
- ((SSLServerSocket) serverSocket).setNeedClientAuth(true);
- // work as a HTTPS server, not as HTTP proxy
- this.actAsProxy = false;
- } else {
- this.actAsProxy = true;
- }
- this.actAsProxy = !(serverSocket instanceof SSLServerSocket);
- setName(this.actAsProxy ? "Proxy Server" : "Server");
- }
-
- /**
- * Closes the connection.
- */
- public void closeSocket(Socket socket) {
- try {
- socket.getInputStream().close();
- } catch (IOException e) {}
- try {
- socket.getOutputStream().close();
- } catch (IOException e) {}
- try {
- socket.close();
- } catch (IOException e) {}
- }
-
- /**
- * Performs the actual server work.
- * If some exception occurs during the work it will be
- * stored in the <code>thrown</code> field.
- */
- public void run() {
- // the buffer used for reading the messages
- byte[] buff = new byte[2048];
- // the number of bytes read into the buffer
- int num;
- try {
- // configure the server socket to avoid blocking
- serverSocket.setSoTimeout(TIMEOUT);
- // accept client connection
- peerSocket = serverSocket.accept();
- // configure the client connection to avoid blocking
- peerSocket.setSoTimeout(TIMEOUT);
- log("Client connection ACCEPTED");
-
- InputStream is = peerSocket.getInputStream();
- OutputStream os = peerSocket.getOutputStream();
-
- num = is.read(buff);
- String message = new String(buff, 0, num);
- log("Got request:\n" + message);
- log("------------------");
-
- if (!actAsProxy) {
- // Act as Server (not Proxy) side
- if (message.startsWith("POST")) {
- // client connection sent some data
- log("try to read client data");
- num = is.read(buff);
- message = new String(buff, 0, num);
- log("client's data: '" + message + "'");
- // check the received data
- assertEquals(clientsData, message);
- }
- // just send the response
- os
- .write(("HTTP/1.1 " + responseCode + "\n" + httpsResponseTail)
- .getBytes());
- // and return
- log("Work is DONE");
- return;
- }
-
- // Do proxy work
- if (needProxyAuthentication) {
- log("Authentication required ...");
- // send Authentication Request
- os.write(respAuthenticationRequired.getBytes());
- // read response
- num = is.read(buff);
- if (num == -1) {
- // this connection was closed,
- // do clean up and create new one:
- closeSocket(peerSocket);
- peerSocket = serverSocket.accept();
- peerSocket.setSoTimeout(TIMEOUT);
- log("New client connection ACCEPTED");
- is = peerSocket.getInputStream();
- os = peerSocket.getOutputStream();
- num = is.read(buff);
- }
- message = new String(buff, 0, num);
- log("Got authenticated request:\n" + message);
- log("------------------");
- // check provided authorization credentials
- assertTrue("Received message does not contain "
- + "authorization credentials", message
- .toLowerCase().indexOf("proxy-authorization:") > 0);
- }
-
- // The content of this response will reach proxied HTTPUC
- // but will not reach proxied HTTPSUC
- // In case of HTTP connection it will be the final message,
- // in case of HTTPS connection this message will just indicate
- // that connection with remote host has been done
- // (i.e. SSL tunnel has been established).
- os.write(plainResponse.getBytes());
- log("Sent OK RESPONSE");
-
- if (message.startsWith("CONNECT")) { // request for SSL tunnel
- log("Perform SSL Handshake...");
- // create sslSocket acting as a remote server peer
- SSLSocket sslSocket = (SSLSocket) getContext()
- .getSocketFactory().createSocket(peerSocket,
- "localhost", peerSocket.getPort(), true); // do autoclose
- sslSocket.setUseClientMode(false);
- // demand client authentication
- sslSocket.setNeedClientAuth(true);
- sslSocket.startHandshake();
- peerSocket = sslSocket;
- is = peerSocket.getInputStream();
- os = peerSocket.getOutputStream();
-
- // read the HTTP request sent by secure connection
- // (HTTPS request)
- num = is.read(buff);
- message = new String(buff, 0, num);
- log("[Remote Server] Request from SSL tunnel:\n" + message);
- log("------------------");
-
- if (message.startsWith("POST")) {
- // client connection sent some data
- log("[Remote Server] try to read client data");
- num = is.read(buff);
- message = new String(buff, 0, num);
- log("[Remote Server] client's data: '" + message + "'");
- // check the received data
- assertEquals(clientsData, message);
- }
-
- log("[Remote Server] Sending the response by SSL tunnel..");
- // send the response with specified response code
- os
- .write(("HTTP/1.1 " + responseCode + "\n" + httpsResponseTail)
- .getBytes());
- }
- log("Work is DONE");
- } catch (Throwable e) {
- if (DO_LOG) {
- e.printStackTrace();
- }
- thrown = e;
- } finally {
- closeSocket(peerSocket);
- try {
- serverSocket.close();
- } catch (IOException e) {}
- }
- }
- }
-
- /**
- * The class used for client side works. It could be used to test
- * both HttpURLConnection and HttpsURLConnection.
- */
- static class ClientConnectionWork extends Work {
-
- // connection to be used to contact the server side
- private HttpURLConnection connection;
-
- /**
- * Creates the thread acting as a client side.
- * @param connection connection to be used to contact the server side
- */
- public ClientConnectionWork(HttpURLConnection connection) {
- this.connection = connection;
- setName("Client Connection");
- log("Created over connection: " + connection.getClass());
- }
-
- /**
- * Performs the actual client work.
- * If some exception occurs during the work it will be
- * stored in the <code>thrown<code> field.
- */
- public void run() {
- try {
- log("Opening the connection..");
- connection.connect();
- log("Connection has been ESTABLISHED, using proxy: "
- + connection.usingProxy());
- if (connection.getDoOutput()) {
- // connection configured to post data, do so
- connection.getOutputStream().write(clientsData.getBytes());
- }
- // read the content of HTTP(s) response
- InputStream is = connection.getInputStream();
- log("Input Stream obtained");
- byte[] buff = new byte[2048];
- int num = 0;
- int byt = 0;
- while ((num < buff.length) && (is.available() > 0)
- && ((byt = is.read()) != -1)) {
- buff[num++] = (byte) byt;
- }
- String message = new String(buff, 0, num);
- log("Got content:\n" + message);
- log("------------------");
- log("Response code: " + connection.getResponseCode());
-
- if (connection instanceof HttpsURLConnection) {
- assertEquals(httpsResponseContent, message);
- } else {
- assertEquals(plainResponseContent, message);
- }
- } catch (Throwable e) {
- if (DO_LOG) {
- e.printStackTrace();
- }
- thrown = e;
- }
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/AllTests.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/AllTests.java
deleted file mode 100644
index 778e527..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/AllTests.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.io;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-import junit.textui.TestRunner;
-
-/**
- * Listing of all the tests that are to be run.
- */
-public class AllTests
-{
-
- public static void run() {
- TestRunner.main(new String[] { AllTests.class.getName() });
- }
-
- public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.io");
-
- suite.addTestSuite(BufferedReaderTest.class);
- suite.addTestSuite(FilePermissionTest.class);
- suite.addTestSuite(FileTest.class);
- suite.addTestSuite(InputStreamReaderTest.class);
- suite.addTestSuite(ObjectInputStreamTest.class);
- suite.addTestSuite(ObjectStreamConstantsTest.class);
- suite.addTestSuite(OutputStreamWriterTest.class);
- suite.addTestSuite(PushBackInputStreamTest.class);
- suite.addTestSuite(RandomAccessFileTest.class);
- suite.addTestSuite(ReaderTest.class);
- suite.addTestSuite(WriterTest.class);
-
- return suite;
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/BufferedReaderTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/BufferedReaderTest.java
deleted file mode 100644
index 55e8c6f..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/BufferedReaderTest.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/* 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.harmony.luni.tests.java.io;
-
-import java.io.BufferedReader;
-import java.io.CharArrayReader;
-import java.io.IOException;
-import java.io.StringReader;
-
-import junit.framework.TestCase;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-@TestTargetClass(BufferedReader.class)
-public class BufferedReaderTest extends TestCase {
-
- /**
- * @tests java.io.BufferedReader#read(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks exceptions.",
- method = "read",
- args = {char[].class, int.class, int.class}
- )
- public void test_read$CII() throws IOException {
- char[] in = {'L', 'o', 'r', 'e', 'm'};
- char[] ch = new char[3];
- BufferedReader reader = new BufferedReader(new CharArrayReader(in));
-
- try {
- reader.read(null, 1, 0);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
-
- try {
- reader.read(ch , -1, 1);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- reader.read(ch , 1, -1);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- reader.read(ch, 1, 3);
- fail("Test 4: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- reader.close();
- try {
- reader.read(ch, 1, 1);
- fail("Test 5: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.BufferedReader#mark(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "mark",
- args = {int.class}
- )
- public void test_markI() throws IOException {
- BufferedReader buf = new BufferedReader(new StringReader("01234"), 2);
-
- try {
- buf.mark(-1);
- fail("Test 1: IllegalArgumentException expected.");
- } catch (IllegalArgumentException e) {
- // Expected.
- }
-
- buf.mark(3);
- char[] chars = new char[3];
- int result = buf.read(chars);
- assertEquals(3, result);
- assertEquals("Assert 0:", '0', chars[0]);
- assertEquals("Assert 1:", '1', chars[1]);
- assertEquals("Assert 2:", '2', chars[2]);
- assertEquals("Assert 3:", '3', buf.read());
-
- buf = new BufferedReader(new StringReader("01234"), 2);
- buf.mark(3);
- chars = new char[4];
- result = buf.read(chars);
- assertEquals("Assert 4:", 4, result);
- assertEquals("Assert 5:", '0', chars[0]);
- assertEquals("Assert 6:", '1', chars[1]);
- assertEquals("Assert 7:", '2', chars[2]);
- assertEquals("Assert 8:", '3', chars[3]);
- assertEquals("Assert 9:", '4', buf.read());
- assertEquals("Assert 10:", -1, buf.read());
-
- BufferedReader reader = new BufferedReader(new StringReader("01234"));
- reader.mark(Integer.MAX_VALUE);
- reader.read();
- reader.close();
-
- try {
- reader.mark(1);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FilePermissionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FilePermissionTest.java
deleted file mode 100644
index a358cc5..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FilePermissionTest.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/* 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.harmony.luni.tests.java.io;
-
-import java.io.File;
-import java.io.FilePermission;
-
-import junit.framework.TestCase;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-@TestTargetClass(FilePermission.class)
-public class FilePermissionTest extends TestCase {
-
- /**
- * @tests java.io.FilePermission#implies(java.security.Permission)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "implies",
- args = {java.security.Permission.class}
- )
- public void test_impliesLjava_io_FilePermission() {
- // Regression for HARMONY-47
- char separator = File.separatorChar;
- char nonSeparator = (separator == '/') ? '\\' : '/';
-
- FilePermission fp1 = new FilePermission(nonSeparator + "*", "read");
- FilePermission fp2 = new FilePermission(separator + "a", "read");
- assertFalse("Assert 0: non-separator worked", fp1.implies(fp2));
- fp1 = new FilePermission(nonSeparator + "-", "read");
- assertFalse("Assert 1: non-separator worked", fp1.implies(fp2));
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FileTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FileTest.java
deleted file mode 100644
index ed81162..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/FileTest.java
+++ /dev/null
@@ -1,190 +0,0 @@
-/* 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.harmony.luni.tests.java.io;
-
-import java.io.File;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(File.class)
-public class FileTest extends TestCase {
-
- /**
- * @tests java.io.File#File(java.io.File, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "File",
- args = {java.io.File.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_io_FileLjava_lang_String() {
- // Regression test for HARMONY-21
- File path = new File("/dir/file");
- File root = new File("/");
- File file = new File(root, "/dir/file");
- assertEquals("Assert 1: wrong path result ", path.getPath(), file
- .getPath());
- assertTrue("Assert 1.1: path not absolute ", new File("\\\\\\a\b").isAbsolute());
-
- // Test data used in a few places below
- String dirName = System.getProperty("java.io.tmpdir");
- String fileName = "input.tst";
-
- // change user.dir to a folder that's writeable on android.
- String oldUserDir = System.getProperty("user.dir");
- System.setProperty("user.dir", dirName);
-
- // Check filename is preserved correctly
- File d = new File(dirName);
- File f = new File(d, fileName);
- if (!dirName
- .regionMatches((dirName.length() - 1), File.separator, 0, 1)) {
- dirName += File.separator;
- }
- dirName += fileName;
- assertTrue("Assert 2: Created incorrect file " + f.getPath(), f
- .getPath().equals(dirName));
-
- // Check null argument is handled
- try {
- f = new File(d, null);
- fail("Assert 3: NullPointerException not thrown.");
- } catch (NullPointerException e) {
- // Expected.
- }
-
- f = new File((File) null, fileName);
- assertEquals("Assert 4: Created incorrect file " + f.getPath(), dirName,
- f.getAbsolutePath());
-
- // Regression for HARMONY-46
- File f1 = new File("a");
- File f2 = new File("a/");
- assertEquals("Assert 5: Trailing slash file name is incorrect", f1, f2);
-
- // reset user.dir
- System.setProperty("user.dir", oldUserDir);
- }
-
- /**
- * @tests java.io.File#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- // Regression for HARMONY-53
- String mixedFname = "SoMe FiLeNaMe";
- File mfile = new File(mixedFname);
- File lfile = new File(mixedFname.toLowerCase());
-
- if (mfile.equals(lfile)) {
- assertTrue("Assert 0: wrong hashcode", mfile.hashCode() == lfile.hashCode());
- } else {
- assertFalse("Assert 1: wrong hashcode", mfile.hashCode() == lfile.hashCode());
- }
- }
-
- /**
- * @tests java.io.File#getPath()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPath",
- args = {}
- )
- public void test_getPath() {
- // Regression for HARMONY-444
- File file;
- String separator = File.separator;
-
- file = new File((File) null, "x/y/z");
- assertEquals("x" + separator + "y" + separator + "z", file.getPath());
-
- file = new File((String) null, "x/y/z");
- assertEquals("x" + separator + "y" + separator + "z", file.getPath());
- }
-
- /**
- * @tests java.io.File#getPath()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPath",
- args = {}
- )
- public void test_getPath_With_Empty_FileName() {
- // Regression for HARMONY-829
- String f1ParentName = "01";
- File f1 = new File(f1ParentName, "");
- assertEquals(f1ParentName, f1.getPath());
-
- String f2ParentName = "0";
- File f2 = new File(f2ParentName, "");
-
- assertEquals(-1, f2.compareTo(f1));
- assertEquals(1, f1.compareTo(f2));
-
- File parent = new File(System.getProperty("java.io.tmpdir"));
- File f3 = new File(parent, "");
-
- assertEquals(parent.getPath(), f3.getPath());
-
-
- }
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies self serialization/deserialization.",
- method = "!SerializationSelf",
- args = {}
- )
- public void test_serialization_self() throws Exception {
- File testFile = new File("test.ser");
- SerializationTest.verifySelf(testFile);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- )
- public void test_serialization_compatibility() throws Exception {
- File file = new File("FileTest.golden.ser");
- SerializationTest.verifyGolden(this, file);
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/InputStreamReaderTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/InputStreamReaderTest.java
deleted file mode 100644
index 08c8627..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/InputStreamReaderTest.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/* 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.harmony.luni.tests.java.io;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.UnsupportedEncodingException;
-
-import junit.framework.TestCase;
-@TestTargetClass(InputStreamReader.class)
-public class InputStreamReaderTest extends TestCase {
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InputStreamReader",
- args = {java.io.InputStream.class, java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getEncoding",
- args = {}
- )
- })
- public void testGetEncoding_StreamClosed() throws IOException {
- InputStreamReader in = null;
- byte b[] = new byte[5];
- in = new InputStreamReader(new ByteArrayInputStream(b), "UTF-16BE");
- in.close();
- String result = in.getEncoding();
- assertNull(result);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InputStreamReader",
- args = {java.io.InputStream.class, java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getEncoding",
- args = {}
- )
- })
- public void testGetEncoding_NotHistorical() {
- InputStreamReader in = null;
- try {
- in = new InputStreamReader(System.in, "UTF-16BE");
- } catch (UnsupportedEncodingException e) {
- // ok
- }
- String result = in.getEncoding();
- assertEquals("UnicodeBigUnmarked", result);
-
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectInputStreamTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectInputStreamTest.java
deleted file mode 100644
index 5710dd3..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectInputStreamTest.java
+++ /dev/null
@@ -1,309 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.io;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InvalidClassException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.ObjectStreamClass;
-import java.io.ObjectStreamException;
-import java.io.OptionalDataException;
-import java.io.Serializable;
-import java.io.StreamCorruptedException;
-import java.util.ArrayList;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-import tests.support.Support_ASimpleInputStream;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(ObjectInputStream.class)
-public class ObjectInputStreamTest extends TestCase {
-
- ObjectInputStream ois;
-
- ObjectOutputStream oos;
-
- ByteArrayOutputStream bao;
-
- private final String testString = "Lorem ipsum...";
-
- protected void setUp() throws Exception {
- super.setUp();
- oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks ObjectStreamException and OptionalDataException.",
- method = "readUnshared",
- args = {}
- )
- public void test_readUnshared_1() throws IOException, ClassNotFoundException {
- oos.writeObject(testString);
- oos.writeObject(testString);
- oos.writeInt(42);
- oos.close();
-
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- try {
- ois.readUnshared();
- ois.readObject();
- fail("Test 1: ObjectStreamException expected.");
- } catch (ObjectStreamException e) {
- // Expected.
- }
-
- try {
- ois.readUnshared();
- fail("Test 2: OptionalDataException expected.");
- } catch (OptionalDataException e) {
- // Expected.
- }
- ois.close();
- }
-
- /**
- * @tests java.io.ObjectInputStream#readUnshared()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks StreamCorruptedException.",
- method = "readUnshared",
- args = {}
- )
- public void test_readUnshared_2() throws IOException, ClassNotFoundException {
- oos.close();
- bao.write(testString.getBytes());
-
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- try {
- ois.readUnshared();
- fail("Test 1: StreamCorruptedException expected.");
- } catch (StreamCorruptedException e) {
- // Expected.
- }
- ois.close();
- }
-
- /**
- * @tests java.io.ObjectInputStream#readUnshared()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks IOException.",
- method = "readUnshared",
- args = {}
- )
- public void test_readUnshared_3() throws IOException, ClassNotFoundException {
- bao.write(testString.getBytes());
- oos.close();
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- ois = new ObjectInputStream(sis);
- sis.throwExceptionOnNextUse = true;
- try {
- ois.readUnshared();
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- ois.close();
- }
-
- /**
- * Micro-scenario of de/serialization of an object with non-serializable superclass.
- * The super-constructor only should be invoked on the deserialized instance.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "readObject",
- args = {}
- )
- public void test_readObject_Hierarchy() throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
- ObjectOutputStream oos = new ObjectOutputStream(baos);
- oos.writeObject(new B());
- oos.close();
-
- ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
- B b = (B) ois.readObject();
- ois.close();
-
- assertTrue("should construct super", A.list.contains(b));
- assertFalse("should not construct self", B.list.contains(b));
- assertEquals("super field A.s", A.DEFAULT, ((A)b).s);
- assertNull("transient field B.s", b.s);
- }
-
- /**
- * @tests {@link java.io.ObjectInputStream#readNewLongString()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!SerializationSelf",
- args = {}
- )
- public void test_readNewLongString() throws Exception {
- LongString longString = new LongString();
- SerializationTest.verifySelf(longString);
- }
-
- private static class LongString implements Serializable{
- private static final long serialVersionUID = 1L;
- String lString;
-
- public LongString() {
- StringBuilder builder = new StringBuilder();
- // construct a string whose length > 64K
- for (int i = 0; i < 65636; i++) {
- builder.append('1');
- }
- lString = builder.toString();
- }
-
- @Override
- public boolean equals(Object o) {
- if (o == this) {
- return true;
- }
- if (o instanceof LongString) {
- LongString l = (LongString) o;
- return l.lString.equals(l.lString);
- }
- return true;
- }
-
- @Override
- public int hashCode() {
- return lString.hashCode();
- }
- }
-
- static class A {
- static final ArrayList<A> list = new ArrayList<A>();
- String s;
- public static final String DEFAULT = "aaa";
- public A() {
- s = DEFAULT;
- list.add(this);
- }
- }
-
- static class B extends A implements Serializable {
- private static final long serialVersionUID = 1L;
- static final ArrayList<A> list = new ArrayList<A>();
- transient String s;
- public B() {
- s = "bbb";
- list.add(this);
- }
- }
-
- class OIS extends ObjectInputStream {
-
- OIS () throws IOException {
- super();
- }
-
- void test() throws ClassNotFoundException,IOException {
- readClassDescriptor();
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "readClassDescriptor",
- args = {}
- )
- public void test_readClassDescriptor() throws ClassNotFoundException, IOException {
- try {
- new OIS().test();
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
- }
-
- static class TestObjectInputStream extends ObjectInputStream {
- public TestObjectInputStream(InputStream in) throws IOException {
- super(in);
- }
-
- protected Class<?> resolveClass(ObjectStreamClass desc)
- throws IOException, ClassNotFoundException {
- if (desc.getName().endsWith("ObjectInputStreamTest$TestClass1")) {
- return TestClass2.class;
- }
- return super.resolveClass(desc);
- }
- }
-
- static class TestClass1 implements Serializable {
- private static final long serialVersionUID = 11111L;
- int i = 0;
- }
-
- static class TestClass2 implements Serializable {
- private static final long serialVersionUID = 11111L;
- int i = 0;
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks InvalidClassException.",
- method = "resolveClass",
- args = {java.io.ObjectStreamClass.class}
- )
- public void test_resolveClass_invalidClassName()
- throws Exception {
- // Regression test for HARMONY-1920
- TestClass1 to1 = new TestClass1();
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStream oos = new ObjectOutputStream(baos);
- ByteArrayInputStream bais;
- ObjectInputStream ois;
-
- to1.i = 555;
- oos.writeObject(to1);
- oos.flush();
- byte[] bytes = baos.toByteArray();
- bais = new ByteArrayInputStream(bytes);
- ois = new TestObjectInputStream(bais);
-
- try {
- ois.readObject();
- fail("Test 1: InvalidClassException expected.");
- } catch (InvalidClassException ice) {
- // Expected.
- }
- }
-}
-
-
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectStreamConstantsTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectStreamConstantsTest.java
deleted file mode 100644
index f13c537..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectStreamConstantsTest.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/* 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.harmony.luni.tests.java.io;
-
-import java.io.ObjectStreamConstants;
-
-import junit.framework.TestCase;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(ObjectStreamConstants.class)
-public class ObjectStreamConstantsTest extends TestCase {
-
- /**
- * @tests java.io.ObjectStreamConstants#TC_ENUM
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Constant test, still many constants not tested",
- method = "!Constants",
- args = {}
- )
- public void test_Constants() {
- assertEquals(126, ObjectStreamConstants.TC_ENUM);
- assertEquals(16, ObjectStreamConstants.SC_ENUM);
- assertEquals(126, ObjectStreamConstants.TC_MAX);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/OutputStreamWriterTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/OutputStreamWriterTest.java
deleted file mode 100644
index 732ee50..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/OutputStreamWriterTest.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/* 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.harmony.luni.tests.java.io;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.io.UnsupportedEncodingException;
-
-import junit.framework.TestCase;
-@TestTargetClass(OutputStreamWriter.class)
-public class OutputStreamWriterTest extends TestCase {
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks IOException",
- method = "getEncoding",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks IOException",
- method = "close",
- args = {}
- )
- })
- public void testGetEncoding_StreamClosed() {
- OutputStreamWriter out = null;
- try {
- out = new OutputStreamWriter(new ByteArrayOutputStream(),
- "UTF-16BE");
- } catch (UnsupportedEncodingException e) {
- fail("Should not throw UnsupportedEncodingException");
- }
- try {
- out.close();
- } catch (IOException e) {
- fail("Should not throw IOException");
- }
- String result = out.getEncoding();
- assertNull(result);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getEncoding",
- args = {}
- )
- public void testGetEncoding_NotHistorical() {
- OutputStreamWriter out = null;
- try {
- out = new OutputStreamWriter(new ByteArrayOutputStream(),
- "UTF-16BE");
- } catch (UnsupportedEncodingException e) {
- // ok
- }
- String result = out.getEncoding();
- assertEquals("UnicodeBigUnmarked", result);
- }
-} \ No newline at end of file
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/PushBackInputStreamTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/PushBackInputStreamTest.java
deleted file mode 100644
index 6973fe6..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/PushBackInputStreamTest.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/* 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.harmony.luni.tests.java.io;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.PushbackInputStream;
-
-import junit.framework.TestCase;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-@TestTargetClass(PushbackInputStream.class)
-public class PushBackInputStreamTest extends TestCase {
-
- /*
- * @tests java.io.PushBackInputStream(InputStream)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks IOException.",
- method = "read",
- args = {}
- )
- public void test_read() {
- PushbackInputStream str = new PushbackInputStream(null);
- try {
- str.read();
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- str = new PushbackInputStream(null, 1);
- try {
- str.read();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.io.PushbackInputStream#unread(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unread",
- args = {byte[].class, int.class, int.class}
- )
- public void test_unread$BII() {
- // Regression for HARMONY-49
- try {
- PushbackInputStream pb = new PushbackInputStream(
- new ByteArrayInputStream(new byte[] { 0 }), 2);
- pb.unread(new byte[1], 0, 5);
- fail("Assert 0: should throw IOE");
- } catch (IOException e) {
- // expected
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reset",
- args = {}
- )
- public void test_reset() {
- PushbackInputStream pb = new PushbackInputStream(
- new ByteArrayInputStream(new byte[] { 0 }), 2);
- try {
- pb.reset();
- fail("Should throw IOException");
- } catch (IOException e) {
- // expected
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "mark",
- args = {int.class}
- )
- public void test_mark() {
- PushbackInputStream pb = new PushbackInputStream(
- new ByteArrayInputStream(new byte[] { 0 }), 2);
- pb.mark(Integer.MAX_VALUE);
- pb.mark(0);
- pb.mark(-1);
- pb.mark(Integer.MIN_VALUE);
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/RandomAccessFileTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/RandomAccessFileTest.java
deleted file mode 100644
index 4756c09..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/RandomAccessFileTest.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/* 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.harmony.luni.tests.java.io;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.RandomAccessFile;
-
-import junit.framework.TestCase;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-@TestTargetClass(RandomAccessFile.class)
-public class RandomAccessFileTest extends TestCase {
-
- /**
- * @tests java.io.RandomAccessFile#RandomAccessFile(java.io.File, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks functionality.",
- method = "RandomAccessFile",
- args = {java.io.File.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_io_FileLjava_lang_String() throws IOException {
- // Regression for HARMONY-50
- File f = File.createTempFile("xxx", "yyy");
- f.deleteOnExit();
- RandomAccessFile raf = new RandomAccessFile(f, "rws");
- raf.close();
-
- f = File.createTempFile("xxx", "yyy");
- f.deleteOnExit();
- raf = new RandomAccessFile(f, "rwd");
- raf.close();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ReaderTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ReaderTest.java
deleted file mode 100644
index 9ea7537..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ReaderTest.java
+++ /dev/null
@@ -1,379 +0,0 @@
-/* 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.harmony.luni.tests.java.io;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.nio.CharBuffer;
-
-import junit.framework.TestCase;
-import tests.support.Support_ASimpleReader;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-@TestTargetClass(Reader.class)
-public class ReaderTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "Reader",
- args = {}
- )
- public void test_Reader() {
- MockReader r = new MockReader();
- assertTrue("Test 1: Lock has not been set correctly.", r.lockSet(r));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "Reader",
- args = {java.lang.Object.class}
- )
- public void test_Reader_CharBuffer_null() throws IOException {
- String s = "MY TEST STRING";
- MockReader mockReader = new MockReader(s.toCharArray());
- CharBuffer charBuffer = null;
- try {
- mockReader.read(charBuffer);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- //expected;
- }
- }
-
- @TestTargets ({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Functional test.",
- method = "Reader",
- args = {java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Functional test.",
- method = "read",
- args = {java.nio.CharBuffer.class}
- )
- })
- public void test_Reader_CharBuffer_ZeroChar() throws IOException {
- // If the charBuffer has a capacity of 0, then the number of char read
- // to the CharBuffer is 0. Furthermore, the MockReader is intact in
- // its content.
- String s = "MY TEST STRING";
- char[] srcBuffer = s.toCharArray();
- MockReader mockReader = new MockReader(srcBuffer);
- CharBuffer charBuffer = CharBuffer.allocate(0);
- int result = mockReader.read(charBuffer);
- assertEquals(0, result);
- char[] destBuffer = new char[srcBuffer.length];
- mockReader.read(destBuffer);
- assertEquals(s, String.valueOf(destBuffer));
- }
-
- @TestTargets ({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Functional test.",
- method = "Reader",
- args = {java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Functional test.",
- method = "read",
- args = {java.nio.CharBuffer.class}
- )
- })
- public void test_Reader_CharBufferChar() throws IOException {
- String s = "MY TEST STRING";
- char[] srcBuffer = s.toCharArray();
- final int CHARBUFFER_SIZE = 10;
- MockReader mockReader = new MockReader(srcBuffer);
- CharBuffer charBuffer = CharBuffer.allocate(CHARBUFFER_SIZE);
- charBuffer.append('A');
- final int CHARBUFFER_REMAINING = charBuffer.remaining();
- int result = mockReader.read(charBuffer);
- assertEquals(CHARBUFFER_REMAINING, result);
- charBuffer.rewind();
- assertEquals(s.substring(0, CHARBUFFER_REMAINING), charBuffer
- .subSequence(CHARBUFFER_SIZE - CHARBUFFER_REMAINING,
- CHARBUFFER_SIZE).toString());
- char[] destBuffer = new char[srcBuffer.length - CHARBUFFER_REMAINING];
- mockReader.read(destBuffer);
- assertEquals(s.substring(CHARBUFFER_REMAINING), String
- .valueOf(destBuffer));
-
- Support_ASimpleReader simple;
- simple = new Support_ASimpleReader("Bla bla, what else?");
- CharBuffer buf = CharBuffer.allocate(4);
- assertEquals("Wrong return value!", 4, simple.read(buf));
- buf.rewind();
- assertEquals("Wrong stuff read!", "Bla ", String.valueOf(buf));
- simple.read(buf);
- buf.rewind();
- assertEquals("Wrong stuff read!", "bla,", String.valueOf(buf));
- simple.throwExceptionOnNextUse = true;
- try {
- simple.read(buf);
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "read",
- args = {char[].class}
- )
- public void test_Read_$C() throws IOException {
- Support_ASimpleReader simple;
- simple = new Support_ASimpleReader("Bla bla, what else?");
- char[] buf = new char[4];
- assertEquals("Wrong return value!", 4, simple.read(buf));
- assertEquals("Wrong stuff read!", "Bla ", new String(buf));
- simple.read(buf);
- assertEquals("Wrong stuff read!", "bla,", new String(buf));
- simple.throwExceptionOnNextUse = true;
- try {
- simple.read(buf);
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests {@link java.io.Reader#mark(int)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "mark",
- args = {int.class}
- )
- public void test_mark() {
- MockReader mockReader = new MockReader();
- try {
- mockReader.mark(0);
- fail("Should throw IOException for Reader do not support mark");
- } catch (IOException e) {
- // Excepted
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "markSupported",
- args = {}
- )
- public void test_markSupported() {
- assertFalse("markSupported must return false", new MockReader().markSupported());
- }
-
- /**
- * @tests {@link java.io.Reader#read()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "read",
- args = {}
- )
- public void test_read() throws IOException {
- MockReader reader = new MockReader();
-
- // return -1 when the stream is null;
- assertEquals("Should be equal to -1", -1, reader.read());
-
- String string = "MY TEST STRING";
- char[] srcBuffer = string.toCharArray();
- MockReader mockReader = new MockReader(srcBuffer);
-
- // normal read
- for (char c : srcBuffer) {
- assertEquals("Should be equal to \'" + c + "\'", c, mockReader
- .read());
- }
-
- // return -1 when read Out of Index
- mockReader.read();
- assertEquals("Should be equal to -1", -1, reader.read());
-
- Support_ASimpleReader simple;
- simple = new Support_ASimpleReader("Bla bla, what else?");
- int res;
- res = simple.read();
- assertEquals("Wrong stuff read!", 'B', res);
- res = simple.read();
- assertEquals("Wrong stuff read!", 'l', res);
- simple.throwExceptionOnNextUse = true;
- try {
- simple.read();
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests {@link java.io.Reader#ready()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ready",
- args = {}
- )
- public void test_ready() throws IOException {
- MockReader mockReader = new MockReader();
- assertFalse("Should always return false", mockReader.ready());
-
- Support_ASimpleReader simple;
- simple = new Support_ASimpleReader("Bla bla, what else?");
- simple.throwExceptionOnNextUse = true;
- try {
- simple.ready();
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @throws IOException
- * @tests {@link java.io.Reader#reset()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reset",
- args = {}
- )
- public void test_reset() throws IOException {
- MockReader mockReader = new MockReader();
- try {
- mockReader.reset();
- fail("Should throw IOException");
- } catch (IOException e) {
- // Excepted
- }
- }
-
- /**
- * @tests {@link java.io.Reader#skip(long)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "skip",
- args = {long.class}
- )
- public void test_skip() throws IOException {
- String string = "MY TEST STRING";
- char[] srcBuffer = string.toCharArray();
- int length = srcBuffer.length;
- MockReader mockReader = new MockReader(srcBuffer);
- assertEquals("Should be equal to \'M\'", 'M', mockReader.read());
-
- // normal skip
- mockReader.skip(length / 2);
- assertEquals("Should be equal to \'S\'", 'S', mockReader.read());
-
- // try to skip a bigger number of characters than the total
- // Should do nothing
- mockReader.skip(length);
-
- // try to skip a negative number of characters throw IllegalArgumentException
- try {
- mockReader.skip(-1);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // Excepted
- }
-
- Support_ASimpleReader simple;
- simple = new Support_ASimpleReader("Bla bla, what else?");
- char[] buf = new char[4];
- simple.read(buf);
- assertEquals("Wrong stuff read!", "Bla ", new String(buf));
- simple.skip(5);
- simple.read(buf);
- assertEquals("Wrong stuff read!", "what", new String(buf));
- simple.throwExceptionOnNextUse = true;
- try {
- simple.skip(1);
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- class MockReader extends Reader {
-
- private char[] contents;
-
- private int current_offset = 0;
-
- private int length = 0;
-
- public MockReader() {
- super();
- }
-
- public MockReader(char[] data) {
- contents = data;
- length = contents.length;
- }
-
- @Override
- public void close() throws IOException {
-
- contents = null;
- }
-
- @Override
- public int read(char[] buf, int offset, int count) throws IOException {
-
- if (null == contents) {
- return -1;
- }
- if (length <= current_offset) {
- return -1;
- }
- if (buf.length < offset + count) {
- throw new IndexOutOfBoundsException();
- }
-
- count = Math.min(count, length - current_offset);
- for (int i = 0; i < count; i++) {
- buf[offset + i] = contents[current_offset + i];
- }
- current_offset += count;
- return count;
- }
-
- public boolean lockSet(Object o) {
- return (lock == o);
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/WriterTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/WriterTest.java
deleted file mode 100644
index 5bad541..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/io/WriterTest.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/* 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.harmony.luni.tests.java.io;
-
-import java.io.IOException;
-import java.io.Writer;
-
-import junit.framework.TestCase;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(Writer.class)
-public class WriterTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "Writer",
- args = {}
- )
- public void test_Writer() {
- MockWriter w = new MockWriter();
- assertTrue("Test 1: Lock has not been set correctly.", w.lockSet(w));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "Writer",
- args = {java.lang.Object.class}
- )
- public void test_WriterLjava_lang_Object() {
- Object o = new Object();
- MockWriter w;
-
- try {
- w = new MockWriter(null);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
- w = new MockWriter(o);
- assertTrue("Test 2: Lock has not been set correctly.", w.lockSet(o));
- }
-
- class MockWriter extends Writer {
- final Object myLock;
-
- MockWriter() {
- super();
- myLock = this;
- }
-
- MockWriter(Object lock) {
- super(lock);
- myLock = lock;
- }
-
- @Override
- public synchronized void close() throws IOException {
- // do nothing
- }
-
- @Override
- public synchronized void flush() throws IOException {
- // do nothing
- }
-
- @Override
- public void write(char[] arg0, int arg1, int arg2) throws IOException {
- assertTrue(Thread.holdsLock(myLock));
- }
-
- public boolean lockSet(Object o) {
- return (lock == o);
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AbstractMethodErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AbstractMethodErrorTest.java
deleted file mode 100644
index c3679f1..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AbstractMethodErrorTest.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(AbstractMethodError.class)
-public class AbstractMethodErrorTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AbstractMethodError",
- args = {}
- )
- public void test_AbstractMethodError() {
- AbstractMethodError ame = new AbstractMethodError();
- assertNull(ame.getMessage());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AbstractMethodError",
- args = {java.lang.String.class}
- )
- public void test_AbstractMethodError_String() {
- String message = "Test Message";
- AbstractMethodError ame = new AbstractMethodError(message);
- assertEquals(message, ame.getMessage());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AllTests.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AllTests.java
deleted file mode 100644
index b4f3e5f..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AllTests.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-import junit.textui.TestRunner;
-
-/**
- * Listing of all the tests that are to be run.
- */
-public class AllTests {
-
- public static void run() {
- TestRunner.main(new String[] { AllTests.class.getName() });
- }
-
- public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.lang");
-
- suite.addTestSuite(AbstractMethodErrorTest.class);
- suite.addTestSuite(ArithmeticExceptionTest.class);
- suite.addTestSuite(ArrayIndexOutOfBoundsExceptionTest.class);
- suite.addTestSuite(ArrayStoreExceptionTest.class);
- suite.addTestSuite(AssertionErrorTest.class);
- suite.addTestSuite(BooleanTest.class);
- suite.addTestSuite(ByteTest.class);
- suite.addTestSuite(CharacterImplTest.class);
- suite.addTestSuite(Character_SubsetTest.class);
- suite.addTestSuite(CharacterTest.class);
- suite.addTestSuite(Character_UnicodeBlockTest.class);
- suite.addTestSuite(ClassCastExceptionTest.class);
- suite.addTestSuite(ClassCircularityErrorTest.class);
- suite.addTestSuite(ClassFormatErrorTest.class);
- suite.addTestSuite(ClassLoaderTest.class);
- suite.addTestSuite(ClassNotFoundExceptionTest.class);
- suite.addTestSuite(ClassTest.class);
- suite.addTestSuite(ClassTest2.class);
- suite.addTestSuite(CloneNotSupportedExceptionTest.class);
- suite.addTestSuite(CompilerTest.class);
- suite.addTestSuite(DoubleTest.class);
- suite.addTestSuite(EnumConstantNotPresentExceptionTest.class);
- suite.addTestSuite(EnumTest.class);
- suite.addTestSuite(ErrorTest.class);
- suite.addTestSuite(ExceptionInInitializerErrorTest.class);
- suite.addTestSuite(ExceptionTest.class);
- suite.addTestSuite(FloatTest.class);
- suite.addTestSuite(IllegalAccessErrorTest.class);
- suite.addTestSuite(IllegalAccessExceptionTest.class);
- suite.addTestSuite(IllegalArgumentExceptionTest.class);
- suite.addTestSuite(IllegalMonitorStateExceptionTest.class);
- suite.addTestSuite(IllegalStateExceptionTest.class);
- suite.addTestSuite(IllegalThreadStateExceptionTest.class);
- suite.addTestSuite(IncompatibleClassChangeErrorTest.class);
- suite.addTestSuite(IndexOutOfBoundsExceptionTest.class);
- suite.addTestSuite(InheritableThreadLocalTest.class);
- suite.addTestSuite(InstantiationErrorTest.class);
- suite.addTestSuite(InstantiationExceptionTest.class);
- suite.addTestSuite(IntegerTest.class);
- suite.addTestSuite(InternalErrorTest.class);
- suite.addTestSuite(InterruptedExceptionTest.class);
- suite.addTestSuite(LinkageErrorTest.class);
- suite.addTestSuite(LongTest.class);
- suite.addTestSuite(MathTest.class);
- suite.addTestSuite(NegativeArraySizeExceptionTest.class);
- suite.addTestSuite(NoClassDefFoundErrorTest.class);
- suite.addTestSuite(NoSuchFieldErrorTest.class);
- suite.addTestSuite(NoSuchFieldExceptionTest.class);
- suite.addTestSuite(NoSuchMethodErrorTest.class);
- suite.addTestSuite(NoSuchMethodExceptionTest.class);
- suite.addTestSuite(NullPointerExceptionTest.class);
- suite.addTestSuite(NumberFormatExceptionTest.class);
- suite.addTestSuite(NumberTest.class);
- suite.addTestSuite(ObjectTest.class);
- suite.addTestSuite(OutOfMemoryErrorTest.class);
- suite.addTestSuite(PackageTest.class);
- suite.addTestSuite(ProcessBuilderTest.class);
- suite.addTestSuite(RuntimeExceptionTest.class);
- suite.addTestSuite(RuntimePermissionTest.class);
- suite.addTestSuite(RuntimeTest.class);
- suite.addTestSuite(SecurityExceptionTest.class);
- suite.addTestSuite(SecurityManagerTest.class);
- suite.addTestSuite(ShortTest.class);
- suite.addTestSuite(StackOverflowErrorTest.class);
- suite.addTestSuite(StackTraceElementTest.class);
- suite.addTestSuite(StrictMathTest.class);
- suite.addTestSuite(String2Test.class);
- suite.addTestSuite(StringBuffer2Test.class);
- suite.addTestSuite(StringBufferTest.class);
- suite.addTestSuite(StringBuilderTest.class);
- suite.addTestSuite(StringIndexOutOfBoundsExceptionTest.class);
- suite.addTestSuite(StringTest.class);
- suite.addTestSuite(SystemTest.class);
- suite.addTestSuite(ThreadDeathTest.class);
- suite.addTestSuite(ThreadGroupTest.class);
- suite.addTestSuite(ThreadLocalTest.class);
- suite.addTestSuite(ThreadTest.class);
- suite.addTestSuite(ThreadStateTest.class);
- suite.addTestSuite(ThrowableTest.class);
- suite.addTestSuite(TypeNotPresentExceptionTest.class);
- suite.addTestSuite(UnknownErrorTest.class);
- suite.addTestSuite(UnsatisfiedLinkErrorTest.class);
- suite.addTestSuite(UnsupportedOperationExceptionTest.class);
- suite.addTestSuite(UnsupportedClassVersionErrorTest.class);
- suite.addTestSuite(VerifyErrorTest.class);
- suite.addTestSuite(VirtualMachineErrorTest.class);
-
- return suite;
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArithmeticExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArithmeticExceptionTest.java
deleted file mode 100644
index bce6f5d..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArithmeticExceptionTest.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(ArithmeticException.class)
-public class ArithmeticExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.ArithmeticException#ArithmeticException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ArithmeticException",
- args = {}
- )
- public void test_Constructor() {
- ArithmeticException e = new ArithmeticException();
- assertNull(e.getMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.ArithmeticException#ArithmeticException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ArithmeticException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- ArithmeticException e = new ArithmeticException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArrayIndexOutOfBoundsExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArrayIndexOutOfBoundsExceptionTest.java
deleted file mode 100644
index 3117e49..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArrayIndexOutOfBoundsExceptionTest.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(ArrayIndexOutOfBoundsException.class)
-public class ArrayIndexOutOfBoundsExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.ArrayIndexOutOfBoundsException#ArrayIndexOutOfBoundsException(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ArrayIndexOutOfBoundsException",
- args = {int.class}
- )
- public void test_ConstructorI() {
- ArrayIndexOutOfBoundsException e = new ArrayIndexOutOfBoundsException(-1);
- assertNotNull(e.getMessage());
- assertTrue("Unable to find index value in 'message' property.", e.getMessage().indexOf(
- "-1", 0) >= 0);
-
- }
-
- /**
- * @tests java.lang.ArrayIndexOutOfBoundsException#ArrayIndexOutOfBoundsException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ArrayIndexOutOfBoundsException",
- args = {}
- )
- public void test_Constructor() {
- ArrayIndexOutOfBoundsException e = new ArrayIndexOutOfBoundsException();
- assertNull(e.getMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.ArrayIndexOutOfBoundsException#ArrayIndexOutOfBoundsException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ArrayIndexOutOfBoundsException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- ArrayIndexOutOfBoundsException e = new ArrayIndexOutOfBoundsException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArrayStoreExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArrayStoreExceptionTest.java
deleted file mode 100644
index d2345cb..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArrayStoreExceptionTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(ArrayStoreException.class)
-public class ArrayStoreExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.ArrayStoreException#ArrayStoreException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ArrayStoreException",
- args = {}
- )
- public void test_Constructor() {
- ArrayStoreException e = new ArrayStoreException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.ArrayStoreException#ArrayStoreException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ArrayStoreException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- ArrayStoreException e = new ArrayStoreException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AssertionErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AssertionErrorTest.java
deleted file mode 100644
index ec0d40f..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AssertionErrorTest.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(AssertionError.class)
-public class AssertionErrorTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AssertionError",
- args = {}
- )
- public void test_Constructor() {
- AssertionError e = new AssertionError();
- assertNull(e.getMessage());
- assertNull(e.getCause());
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AssertionError",
- args = {java.lang.Object.class}
- )
- public void test_ConstructorObject() {
- Object obj = "toString";
- AssertionError e = new AssertionError(obj);
- assertEquals("toString", e.getMessage());
- assertNull(e.getCause());
-
- NullPointerException npe = new NullPointerException("null value");
- e = new AssertionError(npe);
- assertEquals(npe.toString(), e.getMessage());
- assertSame(npe, e.getCause());
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AssertionError",
- args = {boolean.class}
- )
- public void test_ConstructorBoolean() {
- AssertionError e = new AssertionError(true);
- assertEquals("true", e.getMessage());
- assertNull(e.getCause());
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AssertionError",
- args = {char.class}
- )
- public void test_ConstructorChar() {
- AssertionError e = new AssertionError('a');
- assertEquals("a", e.getMessage());
- assertNull(e.getCause());
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AssertionError",
- args = {int.class}
- )
- public void test_ConstructorInt() {
- AssertionError e = new AssertionError(1);
- assertEquals("1", e.getMessage());
- assertNull(e.getCause());
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AssertionError",
- args = {long.class}
- )
- public void test_ConstructorLong() {
- AssertionError e = new AssertionError(1L);
- assertEquals("1", e.getMessage());
- assertNull(e.getCause());
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AssertionError",
- args = {float.class}
- )
- public void test_ConstructorFloat() {
- AssertionError e = new AssertionError(1.0F);
- assertEquals("1.0", e.getMessage());
- assertNull(e.getCause());
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AssertionError",
- args = {double.class}
- )
- public void test_ConstructorDouble() {
- AssertionError e = new AssertionError(1.0D);
- assertEquals("1.0", e.getMessage());
- assertNull(e.getCause());
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/BooleanTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/BooleanTest.java
deleted file mode 100644
index 23f9575..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/BooleanTest.java
+++ /dev/null
@@ -1,235 +0,0 @@
-/* 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(Boolean.class)
-public class BooleanTest extends TestCase {
-
- /**
- * @tests java.lang.Boolean#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- assertEquals(1231, Boolean.TRUE.hashCode());
- assertEquals(1237, Boolean.FALSE.hashCode());
- }
-
- /**
- * @tests java.lang.Boolean#Boolean(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Boolean",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- assertEquals(Boolean.TRUE, new Boolean("TRUE"));
- assertEquals(Boolean.TRUE, new Boolean("true"));
- assertEquals(Boolean.TRUE, new Boolean("True"));
-
- assertEquals(Boolean.FALSE, new Boolean("yes"));
- assertEquals(Boolean.FALSE, new Boolean("false"));
- }
-
- /**
- * @tests java.lang.Boolean#Boolean(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Boolean",
- args = {boolean.class}
- )
- public void test_ConstructorZ() {
- assertEquals(Boolean.TRUE, new Boolean(true));
- assertEquals(Boolean.FALSE, new Boolean(false));
- }
-
- /**
- * @tests java.lang.Boolean#booleanValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "booleanValue",
- args = {}
- )
- public void test_booleanValue() {
- assertTrue(Boolean.TRUE.booleanValue());
- assertFalse(Boolean.FALSE.booleanValue());
- }
-
- /**
- * @tests java.lang.Boolean#equals(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- assertTrue(Boolean.TRUE.equals(Boolean.TRUE));
- assertTrue(Boolean.TRUE.equals(new Boolean(true)));
- assertFalse(Boolean.TRUE.equals("true"));
- assertFalse(Boolean.TRUE.equals(null));
- assertFalse(Boolean.FALSE.equals(Boolean.TRUE));
- assertTrue(Boolean.FALSE.equals(Boolean.FALSE));
- assertTrue(Boolean.FALSE.equals(new Boolean(false)));
- }
-
- /**
- * @tests java.lang.Boolean#getBoolean(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBoolean",
- args = {java.lang.String.class}
- )
- public void test_getBooleanLjava_lang_String() {
- System.setProperty(getClass().getName(), "true");
- assertTrue(Boolean.getBoolean(getClass().getName()));
-
- System.setProperty(getClass().getName(), "TRUE");
- assertTrue(Boolean.getBoolean(getClass().getName()));
-
- System.setProperty(getClass().getName(), "false");
- assertFalse(Boolean.getBoolean(getClass().getName()));
- }
-
- /**
- * @tests java.lang.Boolean#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- assertEquals("true", Boolean.TRUE.toString());
- assertEquals("false", Boolean.FALSE.toString());
- }
-
- /**
- * @tests java.lang.Boolean#toString(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {boolean.class}
- )
- public void test_toStringZ() {
- assertEquals("true", Boolean.toString(true));
- assertEquals("false", Boolean.toString(false));
- }
-
- /**
- * @tests java.lang.Boolean#valueOf(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {java.lang.String.class}
- )
- public void test_valueOfLjava_lang_String() {
- assertEquals(Boolean.TRUE, Boolean.valueOf("true"));
- assertEquals(Boolean.FALSE, Boolean.valueOf("false"));
-
- assertEquals(Boolean.TRUE, Boolean.valueOf("TRUE"));
- assertEquals(Boolean.FALSE, Boolean.valueOf("false"));
-
- assertEquals(Boolean.FALSE, Boolean.valueOf(null));
- assertEquals(Boolean.FALSE, Boolean.valueOf(""));
- assertEquals(Boolean.FALSE, Boolean.valueOf("invalid"));
-
- assertTrue("Failed to parse true to true", Boolean.valueOf("true").booleanValue());
- assertTrue("Failed to parse mixed case true to true", Boolean.valueOf("TrUe")
- .booleanValue());
- assertTrue("parsed non-true to true", !Boolean.valueOf("ddddd").booleanValue());
- }
-
- /**
- * @tests java.lang.Boolean#valueOf(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {boolean.class}
- )
- public void test_valueOfZ() {
- assertEquals(Boolean.TRUE, Boolean.valueOf(true));
- assertEquals(Boolean.FALSE, Boolean.valueOf(false));
- }
-
- /**
- * @tests java.lang.Boolean#parseBoolean(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "parseBoolean",
- args = {java.lang.String.class}
- )
- public void test_parseBooleanLjava_lang_String() {
- assertTrue(Boolean.parseBoolean("true"));
- assertTrue(Boolean.parseBoolean("TRUE"));
- assertFalse(Boolean.parseBoolean("false"));
- assertFalse(Boolean.parseBoolean(null));
- assertFalse(Boolean.parseBoolean(""));
- assertFalse(Boolean.parseBoolean("invalid"));
- }
-
- /**
- * @tests java.lang.Boolean#compareTo(Boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.lang.Boolean.class}
- )
- public void test_compareToLjava_lang_Boolean() {
- assertTrue(Boolean.TRUE.compareTo(Boolean.TRUE) == 0);
- assertTrue(Boolean.FALSE.compareTo(Boolean.FALSE) == 0);
- assertTrue(Boolean.TRUE.compareTo(Boolean.FALSE) > 0);
- assertTrue(Boolean.FALSE.compareTo(Boolean.TRUE) < 0);
-
- try {
- Boolean.TRUE.compareTo(null);
- fail("No NPE");
- } catch (NullPointerException e) {
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ByteTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ByteTest.java
deleted file mode 100644
index d99223a..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ByteTest.java
+++ /dev/null
@@ -1,900 +0,0 @@
-/* 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(Byte.class)
-public class ByteTest extends TestCase {
-
- /**
- * @tests java.lang.Byte#valueOf(byte)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {byte.class}
- )
- public void test_valueOfB() {
- assertEquals(new Byte(Byte.MIN_VALUE), Byte.valueOf(Byte.MIN_VALUE));
- assertEquals(new Byte(Byte.MAX_VALUE), Byte.valueOf(Byte.MAX_VALUE));
- assertEquals(new Byte((byte) 0), Byte.valueOf((byte) 0));
-
- byte b = Byte.MIN_VALUE + 1;
- while (b < Byte.MAX_VALUE) {
- assertEquals(new Byte(b), Byte.valueOf(b));
- assertSame(Byte.valueOf(b), Byte.valueOf(b));
- b++;
- }
- }
-
- /**
- * @tests java.lang.Byte#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- assertEquals(1, new Byte((byte) 1).hashCode());
- assertEquals(2, new Byte((byte) 2).hashCode());
- assertEquals(0, new Byte((byte) 0).hashCode());
- assertEquals(-1, new Byte((byte) -1).hashCode());
- }
-
- /**
- * @tests java.lang.Byte#Byte(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Byte",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- assertEquals(new Byte((byte) 0), new Byte("0"));
- assertEquals(new Byte((byte) 1), new Byte("1"));
- assertEquals(new Byte((byte) -1), new Byte("-1"));
-
- try {
- new Byte("0x1");
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {
- }
-
- try {
- new Byte("9.2");
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {
- }
-
- try {
- new Byte("");
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {
- }
-
- try {
- new Byte(null);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {
- }
- }
-
- /**
- * @tests java.lang.Byte#Byte(byte)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Byte",
- args = {byte.class}
- )
- public void test_ConstructorB() {
- assertEquals(1, new Byte((byte) 1).byteValue());
- assertEquals(2, new Byte((byte) 2).byteValue());
- assertEquals(0, new Byte((byte) 0).byteValue());
- assertEquals(-1, new Byte((byte) -1).byteValue());
- }
-
- /**
- * @tests java.lang.Byte#byteValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "byteValue",
- args = {}
- )
- public void test_byteValue1() {
- assertEquals(1, new Byte((byte) 1).byteValue());
- assertEquals(2, new Byte((byte) 2).byteValue());
- assertEquals(0, new Byte((byte) 0).byteValue());
- assertEquals(-1, new Byte((byte) -1).byteValue());
- }
-
- /**
- * @tests java.lang.Byte#equals(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- assertEquals(new Byte((byte) 0), Byte.valueOf((byte) 0));
- assertEquals(new Byte((byte) 1), Byte.valueOf((byte) 1));
- assertEquals(new Byte((byte) -1), Byte.valueOf((byte) -1));
-
- Byte fixture = new Byte((byte) 25);
- assertEquals(fixture, fixture);
- assertFalse(fixture.equals(null));
- assertFalse(fixture.equals("Not a Byte"));
- }
-
- /**
- * @tests java.lang.Byte#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- assertEquals("-1", new Byte((byte) -1).toString());
- assertEquals("0", new Byte((byte) 0).toString());
- assertEquals("1", new Byte((byte) 1).toString());
- assertEquals("-1", new Byte((byte) 0xFF).toString());
- }
-
- /**
- * @tests java.lang.Byte#toString(byte)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {byte.class}
- )
- public void test_toStringB() {
- assertEquals("-1", Byte.toString((byte) -1));
- assertEquals("0", Byte.toString((byte) 0));
- assertEquals("1", Byte.toString((byte) 1));
- assertEquals("-1", Byte.toString((byte) 0xFF));
- }
-
- /**
- * @tests java.lang.Byte#valueOf(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Checks only positive functionality.",
- method = "valueOf",
- args = {java.lang.String.class}
- )
- public void test_valueOfLjava_lang_String() {
- assertEquals(new Byte((byte) 0), Byte.valueOf("0"));
- assertEquals(new Byte((byte) 1), Byte.valueOf("1"));
- assertEquals(new Byte((byte) -1), Byte.valueOf("-1"));
-
- try {
- Byte.valueOf("0x1");
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.valueOf("9.2");
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.valueOf("");
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.valueOf(null);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {
- }
- }
-
- /**
- * @tests java.lang.Byte#valueOf(String,int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't check boundary values.",
- method = "valueOf",
- args = {java.lang.String.class, int.class}
- )
- public void test_valueOfLjava_lang_StringI() {
- assertEquals(new Byte((byte) 0), Byte.valueOf("0", 10));
- assertEquals(new Byte((byte) 1), Byte.valueOf("1", 10));
- assertEquals(new Byte((byte) -1), Byte.valueOf("-1", 10));
-
- //must be consistent with Character.digit()
- assertEquals(Character.digit('1', 2), Byte.valueOf("1", 2).byteValue());
- assertEquals(Character.digit('F', 16), Byte.valueOf("F", 16).byteValue());
-
- try {
- Byte.valueOf("0x1", 10);
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.valueOf("9.2", 10);
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.valueOf("", 10);
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.valueOf(null, 10);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {
- }
- }
-
- /**
- * @tests java.lang.Byte#parseByte(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "parseByte",
- args = {java.lang.String.class}
- )
- public void test_parseByteLjava_lang_String() {
- assertEquals(0, Byte.parseByte("0"));
- assertEquals(1, Byte.parseByte("1"));
- assertEquals(-1, Byte.parseByte("-1"));
-
- try {
- Byte.parseByte("0x1");
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.parseByte("9.2");
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.parseByte("");
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.parseByte(null);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {
- }
- }
-
- /**
- * @tests java.lang.Byte#parseByte(String,int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't check boundary values.",
- method = "parseByte",
- args = {java.lang.String.class, int.class}
- )
- public void test_parseByteLjava_lang_StringI() {
- assertEquals(0, Byte.parseByte("0", 10));
- assertEquals(1, Byte.parseByte("1", 10));
- assertEquals(-1, Byte.parseByte("-1", 10));
-
- //must be consistent with Character.digit()
- assertEquals(Character.digit('1', 2), Byte.parseByte("1", 2));
- assertEquals(Character.digit('F', 16), Byte.parseByte("F", 16));
-
- try {
- Byte.parseByte("0x1", 10);
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.parseByte("9.2", 10);
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.parseByte("", 10);
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.parseByte(null, 10);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {
- }
- }
-
- /**
- * @tests java.lang.Byte#decode(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "decode",
- args = {java.lang.String.class}
- )
- public void test_decodeLjava_lang_String() {
- assertEquals(new Byte((byte) 0), Byte.decode("0"));
- assertEquals(new Byte((byte) 1), Byte.decode("1"));
- assertEquals(new Byte((byte) -1), Byte.decode("-1"));
- assertEquals(new Byte((byte) 0xF), Byte.decode("0xF"));
- assertEquals(new Byte((byte) 0xF), Byte.decode("#F"));
- assertEquals(new Byte((byte) 0xF), Byte.decode("0XF"));
- assertEquals(new Byte((byte) 07), Byte.decode("07"));
-
- try {
- Byte.decode("9.2");
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.decode("");
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.decode(null);
- //undocumented NPE, but seems consistent across JREs
- fail("Expected NullPointerException with null string.");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @tests java.lang.Byte#doubleValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "No boundary verification.",
- method = "doubleValue",
- args = {}
- )
- public void test_doubleValue() {
- assertEquals(-1D, new Byte((byte) -1).doubleValue(), 0D);
- assertEquals(0D, new Byte((byte) 0).doubleValue(), 0D);
- assertEquals(1D, new Byte((byte) 1).doubleValue(), 0D);
- }
-
- /**
- * @tests java.lang.Byte#floatValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify boundary values.",
- method = "floatValue",
- args = {}
- )
- public void test_floatValue() {
- assertEquals(-1F, new Byte((byte) -1).floatValue(), 0F);
- assertEquals(0F, new Byte((byte) 0).floatValue(), 0F);
- assertEquals(1F, new Byte((byte) 1).floatValue(), 0F);
- }
-
- /**
- * @tests java.lang.Byte#intValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "No boundary verification.",
- method = "intValue",
- args = {}
- )
- public void test_intValue() {
- assertEquals(-1, new Byte((byte) -1).intValue());
- assertEquals(0, new Byte((byte) 0).intValue());
- assertEquals(1, new Byte((byte) 1).intValue());
- }
-
- /**
- * @tests java.lang.Byte#longValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "No boundary verification.",
- method = "longValue",
- args = {}
- )
- public void test_longValue() {
- assertEquals(-1L, new Byte((byte) -1).longValue());
- assertEquals(0L, new Byte((byte) 0).longValue());
- assertEquals(1L, new Byte((byte) 1).longValue());
- }
-
- /**
- * @tests java.lang.Byte#shortValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't check boundary values.",
- method = "shortValue",
- args = {}
- )
- public void test_shortValue() {
- assertEquals(-1, new Byte((byte) -1).shortValue());
- assertEquals(0, new Byte((byte) 0).shortValue());
- assertEquals(1, new Byte((byte) 1).shortValue());
- }
-
- /**
- * @tests java.lang.Byte#compareTo(Byte)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.lang.Byte.class}
- )
- public void test_compareToLjava_lang_Byte() {
- final Byte min = new Byte(Byte.MIN_VALUE);
- final Byte zero = new Byte((byte) 0);
- final Byte max = new Byte(Byte.MAX_VALUE);
-
- assertTrue(max.compareTo(max) == 0);
- assertTrue(min.compareTo(min) == 0);
- assertTrue(zero.compareTo(zero) == 0);
-
- assertTrue(max.compareTo(zero) > 0);
- assertTrue(max.compareTo(min) > 0);
-
- assertTrue(zero.compareTo(max) < 0);
- assertTrue(zero.compareTo(min) > 0);
-
- assertTrue(min.compareTo(zero) < 0);
- assertTrue(min.compareTo(max) < 0);
-
- try {
- min.compareTo(null);
- fail("No NPE");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @tests java.lang.Byte#Byte(byte)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Boundary test.",
- method = "Byte",
- args = {byte.class}
- )
- public void test_ConstructorB2() {
- // Test for method java.lang.Byte(byte)
-
- Byte b = new Byte((byte) 127);
- assertTrue("Byte creation failed", b.byteValue() == (byte) 127);
- }
-
- /**
- * @tests java.lang.Byte#Byte(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Doesn't check empty string or null.",
- method = "Byte",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String2() {
- // Test for method java.lang.Byte(java.lang.String)
-
- Byte b = new Byte("127");
- Byte nb = new Byte("-128");
- assertTrue("Incorrect Byte Object created", b.byteValue() == (byte) 127
- && (nb.byteValue() == (byte) -128));
-
- }
-
- /**
- * @tests java.lang.Byte#byteValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Boundary test.",
- method = "byteValue",
- args = {}
- )
- public void test_byteValue() {
- // Test for method byte java.lang.Byte.byteValue()
- assertTrue("Returned incorrect byte value",
- new Byte((byte) 127).byteValue() == (byte) (127));
- }
-
- /**
- * @tests java.lang.Byte#compareTo(java.lang.Byte)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.lang.Byte.class}
- )
- public void test_compareToLjava_lang_Byte2() {
- // Test for method int java.lang.Byte.compareTo(java.lang.Byte)
- assertTrue("Comparison failed", new Byte((byte) 1).compareTo(new Byte((byte) 2)) < 0);
- assertTrue("Comparison failed", new Byte((byte) 1).compareTo(new Byte((byte) -2)) > 0);
- assertEquals("Comparison failed", 0, new Byte((byte) 1).compareTo(new Byte((byte) 1)));
- }
-
- /**
- * @tests java.lang.Byte#decode(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "decode",
- args = {java.lang.String.class}
- )
- public void test_decodeLjava_lang_String2() {
- // Test for method java.lang.Byte
- // java.lang.Byte.decode(java.lang.String)
- assertTrue("String decoded incorrectly, wanted: 1 got: " + Byte.decode("1").toString(),
- Byte.decode("1").equals(new Byte((byte) 1)));
- assertTrue("String decoded incorrectly, wanted: -1 got: "
- + Byte.decode("-1").toString(), Byte.decode("-1").equals(new Byte((byte) -1)));
- assertTrue("String decoded incorrectly, wanted: 127 got: "
- + Byte.decode("127").toString(), Byte.decode("127")
- .equals(new Byte((byte) 127)));
- assertTrue("String decoded incorrectly, wanted: -128 got: "
- + Byte.decode("-128").toString(), Byte.decode("-128").equals(
- new Byte((byte) -128)));
- assertTrue("String decoded incorrectly, wanted: 127 got: "
- + Byte.decode("0x7f").toString(), Byte.decode("0x7f").equals(
- new Byte((byte) 127)));
- assertTrue("String decoded incorrectly, wanted: -128 got: "
- + Byte.decode("-0x80").toString(), Byte.decode("-0x80").equals(
- new Byte((byte) -128)));
-
- boolean exception = false;
- try {
- Byte.decode("128");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
-
- exception = false;
- try {
- Byte.decode("-129");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
-
- exception = false;
- try {
- Byte.decode("0x80");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for hex MAX_VALUE + 1", exception);
-
- exception = false;
- try {
- Byte.decode("-0x81");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for hex MIN_VALUE - 1", exception);
- }
-
- /**
- * @tests java.lang.Byte#doubleValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks boundary value.",
- method = "doubleValue",
- args = {}
- )
- public void test_doubleValue2() {
- assertEquals(127D, new Byte((byte) 127).doubleValue(), 0.0);
- }
-
- /**
- * @tests java.lang.Byte#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Checks that negative value doesn't equal to positive.",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object2() {
- // Test for method boolean java.lang.Byte.equals(java.lang.Object)
- Byte b1 = new Byte((byte) 90);
- Byte b2 = new Byte((byte) 90);
- Byte b3 = new Byte((byte) -90);
- assertTrue("Equality test failed", b1.equals(b2));
- assertTrue("Equality test failed", !b1.equals(b3));
- }
-
- /**
- * @tests java.lang.Byte#floatValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Boundary test.",
- method = "floatValue",
- args = {}
- )
- public void test_floatValue2() {
- assertEquals(127F, new Byte((byte) 127).floatValue(), 0.0);
- }
-
- /**
- * @tests java.lang.Byte#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Boundary test.",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode2() {
- // Test for method int java.lang.Byte.hashCode()
- assertEquals("Incorrect hash returned", 127, new Byte((byte) 127).hashCode());
- }
-
- /**
- * @tests java.lang.Byte#intValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Boundary test.",
- method = "intValue",
- args = {}
- )
- public void test_intValue2() {
- // Test for method int java.lang.Byte.intValue()
- assertEquals("Returned incorrect int value", 127, new Byte((byte) 127).intValue());
- }
-
- /**
- * @tests java.lang.Byte#longValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies boundary values.",
- method = "longValue",
- args = {}
- )
- public void test_longValue2() {
- // Test for method long java.lang.Byte.longValue()
- assertEquals("Returned incorrect long value", 127L, new Byte((byte) 127).longValue());
- }
-
- /**
- * @tests java.lang.Byte#parseByte(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Boundary verification.",
- method = "parseByte",
- args = {java.lang.String.class}
- )
- public void test_parseByteLjava_lang_String2() {
- assertEquals((byte)127, Byte.parseByte("127"));
- assertEquals((byte)-128, Byte.parseByte("-128"));
- assertEquals((byte)0, Byte.parseByte("0"));
- assertEquals((byte)0x80, Byte.parseByte("-128"));
- assertEquals((byte)0x7F, Byte.parseByte("127"));
-
- try {
- Byte.parseByte("-1000");
- fail("No NumberFormatException");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.parseByte("128");
- fail("No NumberFormatException");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.parseByte("-129");
- fail("No NumberFormatException");
- } catch (NumberFormatException e) {
- }
- }
-
- /**
- * @tests java.lang.Byte#parseByte(java.lang.String, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Boundary test.",
- method = "parseByte",
- args = {java.lang.String.class, int.class}
- )
- public void test_parseByteLjava_lang_StringI2() {
- // Test for method byte java.lang.Byte.parseByte(java.lang.String, int)
- byte b = Byte.parseByte("127", 10);
- byte bn = Byte.parseByte("-128", 10);
- assertTrue("Invalid parse of dec byte", b == (byte) 127 && (bn == (byte) -128));
- assertEquals("Failed to parse hex value", 10, Byte.parseByte("A", 16));
- assertEquals("Returned incorrect value for 0 hex", 0, Byte.parseByte("0", 16));
- assertTrue("Returned incorrect value for most negative value hex", Byte.parseByte(
- "-80", 16) == (byte) 0x80);
- assertTrue("Returned incorrect value for most positive value hex", Byte.parseByte("7f",
- 16) == 0x7f);
- assertEquals("Returned incorrect value for 0 decimal", 0, Byte.parseByte("0", 10));
- assertTrue("Returned incorrect value for most negative value decimal", Byte.parseByte(
- "-128", 10) == (byte) 0x80);
- assertTrue("Returned incorrect value for most positive value decimal", Byte.parseByte(
- "127", 10) == 0x7f);
-
- try {
- Byte.parseByte("-1000", 10);
- fail("Failed to throw exception");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.parseByte("128", 10);
- fail("Failed to throw exception for MAX_VALUE + 1");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.parseByte("-129", 10);
- fail("Failed to throw exception for MIN_VALUE - 1");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.parseByte("80", 16);
- fail("Failed to throw exception for hex MAX_VALUE + 1");
- } catch (NumberFormatException e) {
- }
-
- try {
- Byte.parseByte("-81", 16);
- fail("Failed to throw exception for hex MIN_VALUE + 1");
- } catch (NumberFormatException e) {
- }
- }
-
- /**
- * @tests java.lang.Byte#shortValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Boundary test.",
- method = "shortValue",
- args = {}
- )
- public void test_shortValue2() {
- assertEquals((short)127, new Byte((byte)127).shortValue());
- }
-
- /**
- * @tests java.lang.Byte#toString()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Boundary test.",
- method = "toString",
- args = {}
- )
- public void test_toString2() {
- assertEquals("Returned incorrect String", "127", new Byte((byte) 127).toString());
- assertEquals("Returned incorrect String", "-127", new Byte((byte) -127).toString());
- assertEquals("Returned incorrect String", "-128", new Byte((byte) -128).toString());
- }
-
- /**
- * @tests java.lang.Byte#toString(byte)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Boundary test.",
- method = "toString",
- args = {byte.class}
- )
- public void test_toStringB2() {
- assertEquals("Returned incorrect String", "127", Byte.toString((byte) 127));
- assertEquals("Returned incorrect String", "-127", Byte.toString((byte) -127));
- assertEquals("Returned incorrect String", "-128", Byte.toString((byte) -128));
- }
-
- /**
- * @tests java.lang.Byte#valueOf(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Boundary test.",
- method = "valueOf",
- args = {java.lang.String.class}
- )
- public void test_valueOfLjava_lang_String2() {
- assertEquals("Returned incorrect byte", 0, Byte.valueOf("0").byteValue());
- assertEquals("Returned incorrect byte", 127, Byte.valueOf("127").byteValue());
- assertEquals("Returned incorrect byte", -127, Byte.valueOf("-127").byteValue());
- assertEquals("Returned incorrect byte", -128, Byte.valueOf("-128").byteValue());
-
- try {
- Byte.valueOf("128");
- fail("Failed to throw exception when passes value > byte");
- } catch (NumberFormatException e) {
- }
- }
-
- /**
- * @tests java.lang.Byte#valueOf(java.lang.String, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Boundary test.",
- method = "valueOf",
- args = {java.lang.String.class, int.class}
- )
- public void test_valueOfLjava_lang_StringI2() {
- assertEquals("Returned incorrect byte", 10, Byte.valueOf("A", 16).byteValue());
- assertEquals("Returned incorrect byte", 127, Byte.valueOf("127", 10).byteValue());
- assertEquals("Returned incorrect byte", -127, Byte.valueOf("-127", 10).byteValue());
- assertEquals("Returned incorrect byte", -128, Byte.valueOf("-128", 10).byteValue());
- assertEquals("Returned incorrect byte", 127, Byte.valueOf("7f", 16).byteValue());
- assertEquals("Returned incorrect byte", -127, Byte.valueOf("-7f", 16).byteValue());
- assertEquals("Returned incorrect byte", -128, Byte.valueOf("-80", 16).byteValue());
-
- try {
- Byte.valueOf("128", 10);
- fail("Failed to throw exception when passes value > byte");
- } catch (NumberFormatException e) {
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CharacterImplTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CharacterImplTest.java
deleted file mode 100644
index 93e3abb..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CharacterImplTest.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/* 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(Character.class)
-public class CharacterImplTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {char.class}
- )
- @AndroidOnly("valueOf doesn't return the same values on RI.")
- public void test_valueOfC() {
- // test the cache range
- for (char c = '\u0000'; c < 512; c++) {
- Character e = new Character(c);
- Character a = Character.valueOf(c);
- assertEquals(e, a);
-
- // WARN: this assertion may not be valid on other JREs
- assertSame(Character.valueOf(c), Character.valueOf(c));
- }
- // test the rest of the chars
- for (int c = '\u0512'; c <= Character.MAX_VALUE; c++) {
- assertEquals(new Character((char) c), Character.valueOf((char) c));
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CharacterTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CharacterTest.java
deleted file mode 100644
index 67016b9..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CharacterTest.java
+++ /dev/null
@@ -1,2332 +0,0 @@
-/* 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.FileOutputStream;
-import java.io.PrintWriter;
-import java.util.Arrays;
-
-@TestTargetClass(Character.class)
-public class CharacterTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {char.class}
- )
- public void test_valueOfC() {
- // test the cache range
- for (char c = '\u0000'; c < 512; c++) {
- Character e = new Character(c);
- Character a = Character.valueOf(c);
- assertEquals(e, a);
- }
- // test the rest of the chars
- for (int c = 512; c <= Character.MAX_VALUE; c++) {
- assertEquals(new Character((char) c), Character.valueOf((char) c));
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isValidCodePoint",
- args = {int.class}
- )
- public void test_isValidCodePointI() {
- assertFalse(Character.isValidCodePoint(-1));
- assertTrue(Character.isValidCodePoint(0));
- assertTrue(Character.isValidCodePoint(1));
- assertFalse(Character.isValidCodePoint(Integer.MAX_VALUE));
-
- for (int c = '\u0000'; c <= 0x10FFFF; c++) {
- assertTrue(Character.isValidCodePoint(c));
- }
-
- assertFalse(Character.isValidCodePoint(0x10FFFF + 1));
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isSupplementaryCodePoint",
- args = {int.class}
- )
- public void test_isSupplementaryCodePointI() {
- assertFalse(Character.isSupplementaryCodePoint(-1));
-
- for (int c = '\u0000'; c <= '\uFFFF'; c++) {
- assertFalse(Character.isSupplementaryCodePoint(c));
- }
-
- for (int c = 0xFFFF + 1; c <= 0x10FFFF; c++) {
- assertTrue(Character.isSupplementaryCodePoint(c));
- }
-
- assertFalse(Character.isSupplementaryCodePoint(0x10FFFF + 1));
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isHighSurrogate",
- args = {char.class}
- )
- public void test_isHighSurrogateC() {
- // (\uD800-\uDBFF)
- assertFalse(Character.isHighSurrogate((char) ('\uD800' - 1)));
- for (int c = '\uD800'; c <= '\uDBFF'; c++) {
- assertTrue(Character.isHighSurrogate((char) c));
- }
- assertFalse(Character.isHighSurrogate((char) ('\uDBFF' + 1)));
- assertFalse(Character.isHighSurrogate('\uFFFF'));
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isLowSurrogate",
- args = {char.class}
- )
- public void test_isLowSurrogateC() {
- // (\uDC00-\uDFFF)
- assertFalse(Character.isLowSurrogate((char) ('\uDC00' - 1)));
- for (int c = '\uDC00'; c <= '\uDFFF'; c++) {
- assertTrue(Character.isLowSurrogate((char) c));
- }
- assertFalse(Character.isLowSurrogate((char) ('\uDFFF' + 1)));
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isSurrogatePair",
- args = {char.class, char.class}
- )
- public void test_isSurrogatePairCC() {
- assertFalse(Character.isSurrogatePair('\u0000', '\u0000'));
- assertFalse(Character.isSurrogatePair('\u0000', '\uDC00'));
-
- assertTrue(Character.isSurrogatePair('\uD800', '\uDC00'));
- assertTrue(Character.isSurrogatePair('\uD800', '\uDFFF'));
- assertTrue(Character.isSurrogatePair('\uDBFF', '\uDFFF'));
-
- assertFalse(Character.isSurrogatePair('\uDBFF', '\uF000'));
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "charCount",
- args = {int.class}
- )
- public void test_charCountI() {
-
- for (int c = '\u0000'; c <= '\uFFFF'; c++) {
- assertEquals(1, Character.charCount(c));
- }
-
- for (int c = 0xFFFF + 1; c <= 0x10FFFF; c++) {
- assertEquals(2, Character.charCount(c));
- }
-
- // invalid code points work in this method
- assertEquals(2, Character.charCount(Integer.MAX_VALUE));
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toCodePoint",
- args = {char.class, char.class}
- )
- public void test_toCodePointCC() {
- int result = Character.toCodePoint('\uD800', '\uDC00');
- assertEquals(0x00010000, result);
-
- result = Character.toCodePoint('\uD800', '\uDC01');
- assertEquals(0x00010001, result);
-
- result = Character.toCodePoint('\uD801', '\uDC01');
- assertEquals(0x00010401, result);
-
- result = Character.toCodePoint('\uDBFF', '\uDFFF');
- assertEquals(0x00010FFFF, result);
- }
-
- @SuppressWarnings("cast")
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "codePointAt",
- args = {java.lang.CharSequence.class, int.class}
- )
- public void test_codePointAtLjava_lang_CharSequenceI() {
-
- assertEquals('a', Character.codePointAt((CharSequence) "abc", 0));
- assertEquals('b', Character.codePointAt((CharSequence) "abc", 1));
- assertEquals('c', Character.codePointAt((CharSequence) "abc", 2));
- assertEquals(0x10000, Character.codePointAt(
- (CharSequence) "\uD800\uDC00", 0));
- assertEquals('\uDC00', Character.codePointAt(
- (CharSequence) "\uD800\uDC00", 1));
-
- try {
- Character.codePointAt((CharSequence) null, 0);
- fail("No NPE.");
- } catch (NullPointerException e) {
- }
-
- try {
- Character.codePointAt((CharSequence) "abc", -1);
- fail("No IOOBE, negative index.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.codePointAt((CharSequence) "abc", 4);
- fail("No IOOBE, index too large.");
- } catch (IndexOutOfBoundsException e) {
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "codePointAt",
- args = {char[].class, int.class}
- )
- public void test_codePointAt$CI() {
-
- assertEquals('a', Character.codePointAt("abc".toCharArray(), 0));
- assertEquals('b', Character.codePointAt("abc".toCharArray(), 1));
- assertEquals('c', Character.codePointAt("abc".toCharArray(), 2));
- assertEquals(0x10000, Character.codePointAt("\uD800\uDC00"
- .toCharArray(), 0));
- assertEquals('\uDC00', Character.codePointAt("\uD800\uDC00"
- .toCharArray(), 1));
-
- try {
- Character.codePointAt((char[]) null, 0);
- fail("No NPE.");
- } catch (NullPointerException e) {
- }
-
- try {
- Character.codePointAt("abc".toCharArray(), -1);
- fail("No IOOBE, negative index.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.codePointAt("abc".toCharArray(), 4);
- fail("No IOOBE, index too large.");
- } catch (IndexOutOfBoundsException e) {
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "codePointAt",
- args = {char[].class, int.class, int.class}
- )
- public void test_codePointAt$CII() {
-
- assertEquals('a', Character.codePointAt("abc".toCharArray(), 0, 3));
- assertEquals('b', Character.codePointAt("abc".toCharArray(), 1, 3));
- assertEquals('c', Character.codePointAt("abc".toCharArray(), 2, 3));
- assertEquals(0x10000, Character.codePointAt("\uD800\uDC00"
- .toCharArray(), 0, 2));
- assertEquals('\uDC00', Character.codePointAt("\uD800\uDC00"
- .toCharArray(), 1, 2));
- assertEquals('\uD800', Character.codePointAt("\uD800\uDC00"
- .toCharArray(), 0, 1));
-
- try {
- Character.codePointAt((char[]) null, 0, 1);
- fail("No NPE.");
- } catch (NullPointerException e) {
- }
-
- try {
- Character.codePointAt("abc".toCharArray(), -1, 3);
- fail("No IOOBE, negative index.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.codePointAt("abc".toCharArray(), 4, 3);
- fail("No IOOBE, index too large.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.codePointAt("abc".toCharArray(), 2, 1);
- fail("No IOOBE, index larger than limit.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.codePointAt("abc".toCharArray(), 2, -1);
- fail("No IOOBE, limit is negative.");
- } catch (IndexOutOfBoundsException e) {
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "codePointBefore",
- args = {java.lang.CharSequence.class, int.class}
- )
- @SuppressWarnings("cast")
- public void test_codePointBeforeLjava_lang_CharSequenceI() {
-
- assertEquals('a', Character.codePointBefore((CharSequence) "abc", 1));
- assertEquals('b', Character.codePointBefore((CharSequence) "abc", 2));
- assertEquals('c', Character.codePointBefore((CharSequence) "abc", 3));
- assertEquals(0x10000, Character.codePointBefore(
- (CharSequence) "\uD800\uDC00", 2));
- assertEquals('\uD800', Character.codePointBefore(
- (CharSequence) "\uD800\uDC00", 1));
-
- try {
- Character.codePointBefore((CharSequence) null, 0);
- fail("No NPE.");
- } catch (NullPointerException e) {
- }
-
- try {
- Character.codePointBefore((CharSequence) "abc", 0);
- fail("No IOOBE, index below one.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.codePointBefore((CharSequence) "abc", 4);
- fail("No IOOBE, index too large.");
- } catch (IndexOutOfBoundsException e) {
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "codePointBefore",
- args = {char[].class, int.class}
- )
- public void test_codePointBefore$CI() {
-
- assertEquals('a', Character.codePointBefore("abc".toCharArray(), 1));
- assertEquals('b', Character.codePointBefore("abc".toCharArray(), 2));
- assertEquals('c', Character.codePointBefore("abc".toCharArray(), 3));
- assertEquals(0x10000, Character.codePointBefore("\uD800\uDC00"
- .toCharArray(), 2));
- assertEquals('\uD800', Character.codePointBefore("\uD800\uDC00"
- .toCharArray(), 1));
-
- try {
- Character.codePointBefore((char[]) null, 0);
- fail("No NPE.");
- } catch (NullPointerException e) {
- }
-
- try {
- Character.codePointBefore("abc".toCharArray(), -1);
- fail("No IOOBE, negative index.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.codePointBefore("abc".toCharArray(), 4);
- fail("No IOOBE, index too large.");
- } catch (IndexOutOfBoundsException e) {
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "codePointBefore",
- args = {char[].class, int.class, int.class}
- )
- public void test_codePointBefore$CII() {
-
- assertEquals('a', Character.codePointBefore("abc".toCharArray(), 1, 0));
- assertEquals('b', Character.codePointBefore("abc".toCharArray(), 2, 0));
- assertEquals('c', Character.codePointBefore("abc".toCharArray(), 3, 0));
- assertEquals(0x10000, Character.codePointBefore("\uD800\uDC00"
- .toCharArray(), 2, 0));
- assertEquals('\uDC00', Character.codePointBefore("\uD800\uDC00"
- .toCharArray(), 2, 1));
- assertEquals('\uD800', Character.codePointBefore("\uD800\uDC00"
- .toCharArray(), 1, 0));
-
- try {
- Character.codePointBefore((char[]) null, 1, 0);
- fail("No NPE.");
- } catch (NullPointerException e) {
- }
-
- try {
- Character.codePointBefore("abc".toCharArray(), 0, 1);
- fail("No IOOBE, index less than start.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.codePointBefore("abc".toCharArray(), 4, 0);
- fail("No IOOBE, index larger than length.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.codePointBefore("abc".toCharArray(), 2, -1);
- fail("No IOOBE, start is negative.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.codePointBefore("abc".toCharArray(), 2, 4);
- fail("No IOOBE, start larger than length.");
- } catch (IndexOutOfBoundsException e) {
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toChars",
- args = {int.class, char[].class, int.class}
- )
- public void test_toCharsI$CI() {
- char[] dst = new char[2];
- int result = Character.toChars(0x10000, dst, 0);
- assertEquals(2, result);
- assertTrue(Arrays.equals(new char[] { '\uD800', '\uDC00' }, dst));
-
- result = Character.toChars(0x10001, dst, 0);
- assertEquals(2, result);
- assertTrue(Arrays.equals(new char[] { '\uD800', '\uDC01' }, dst));
-
- result = Character.toChars(0x10401, dst, 0);
- assertEquals(2, result);
- assertTrue(Arrays.equals(new char[] { '\uD801', '\uDC01' }, dst));
-
- result = Character.toChars(0x10FFFF, dst, 0);
- assertEquals(2, result);
- assertTrue(Arrays.equals(new char[] { '\uDBFF', '\uDFFF' }, dst));
-
- try {
- Character.toChars(Integer.MAX_VALUE, new char[2], 0);
- fail("No IAE, invalid code point.");
- } catch (IllegalArgumentException e) {
- }
-
- try {
- Character.toChars('a', null, 0);
- fail("No NPE, null char[].");
- } catch (NullPointerException e) {
- }
-
- try {
- Character.toChars('a', new char[1], -1);
- fail("No IOOBE, negative index.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.toChars('a', new char[1], 1);
- fail("No IOOBE, index equal to length.");
- } catch (IndexOutOfBoundsException e) {
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toChars",
- args = {int.class}
- )
- public void test_toCharsI() {
- assertTrue(Arrays.equals(new char[] { '\uD800', '\uDC00' }, Character
- .toChars(0x10000)));
- assertTrue(Arrays.equals(new char[] { '\uD800', '\uDC01' }, Character
- .toChars(0x10001)));
- assertTrue(Arrays.equals(new char[] { '\uD801', '\uDC01' }, Character
- .toChars(0x10401)));
- assertTrue(Arrays.equals(new char[] { '\uDBFF', '\uDFFF' }, Character
- .toChars(0x10FFFF)));
-
- try {
- Character.toChars(Integer.MAX_VALUE);
- fail("No IAE, invalid code point.");
- } catch (IllegalArgumentException e) {
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "codePointCount",
- args = {java.lang.CharSequence.class, int.class, int.class}
- )
- public void test_codePointCountLjava_lang_CharSequenceII() {
- assertEquals(1, Character.codePointCount("\uD800\uDC00", 0, 2));
- assertEquals(1, Character.codePointCount("\uD800\uDC01", 0, 2));
- assertEquals(1, Character.codePointCount("\uD801\uDC01", 0, 2));
- assertEquals(1, Character.codePointCount("\uDBFF\uDFFF", 0, 2));
-
- assertEquals(3, Character.codePointCount("a\uD800\uDC00b", 0, 4));
- assertEquals(4, Character.codePointCount("a\uD800\uDC00b\uD800", 0, 5));
-
- try {
- Character.codePointCount((CharSequence) null, 0, 1);
- fail("No NPE, null char sequence.");
- } catch (NullPointerException e) {
- }
-
- try {
- Character.codePointCount("abc", -1, 1);
- fail("No IOOBE, negative start.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.codePointCount("abc", 0, 4);
- fail("No IOOBE, end greater than length.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.codePointCount("abc", 2, 1);
- fail("No IOOBE, end greater than start.");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "codePointCount",
- args = {char[].class, int.class, int.class}
- )
- public void test_codePointCountLjava_lang_CharArrayII() {
-
- assertEquals(1, Character.codePointCount("\uD800\uDC00".toCharArray(),
- 0, 2));
- assertEquals(3, Character.codePointCount("a\uD800\uDC00b".toCharArray(),
- 0, 4));
- assertEquals(4, Character.codePointCount("a\uD800\uDC00b\uD800".toCharArray(),
- 0, 5));
- assertEquals(4, Character.codePointCount("ab\uD800\uDC00b\uD800".toCharArray(),
- 1, 5));
-
- try {
- Character.codePointCount((char[]) null, 0, 1);
- fail("No NPE, null char sequence.");
- } catch (NullPointerException e) {
- }
-
- try {
- Character.codePointCount("abc".toCharArray(), -1, 1);
- fail("No IOOBE, negative start.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.codePointCount("abc".toCharArray(), 0, 4);
- fail("No IOOBE, end greater than length.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.codePointCount("abc".toCharArray(), 1, 3);
- fail("No IOOBE, end greater than start.");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDirectionality",
- args = {char.class}
- )
- public void test_getDirectionality() throws Exception {
-
- byte[] directionalities = {
- Character.DIRECTIONALITY_UNDEFINED,
- Character.DIRECTIONALITY_LEFT_TO_RIGHT,
- Character.DIRECTIONALITY_RIGHT_TO_LEFT,
- Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC,
- Character.DIRECTIONALITY_EUROPEAN_NUMBER,
- // Character.DIRECTIONALITY_EUROPEAN_NUMBER_SEPARATOR,
- Character.DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR,
- Character.DIRECTIONALITY_ARABIC_NUMBER,
- Character.DIRECTIONALITY_COMMON_NUMBER_SEPARATOR,
- Character.DIRECTIONALITY_NONSPACING_MARK,
- Character.DIRECTIONALITY_BOUNDARY_NEUTRAL,
- Character.DIRECTIONALITY_PARAGRAPH_SEPARATOR,
- Character.DIRECTIONALITY_SEGMENT_SEPARATOR,
- Character.DIRECTIONALITY_WHITESPACE,
- Character.DIRECTIONALITY_OTHER_NEUTRALS,
- Character.DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING,
- Character.DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE,
- Character.DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING,
- Character.DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE,
- Character.DIRECTIONALITY_POP_DIRECTIONAL_FORMAT
- };
-
- char[] characters = {
- '\u0370', // -1
- '\u00B5', // 0
- '\u05BE', // 1
- '\u0600', // 2
- '\u00B2', // 3
- // '', // No common char in this group on android and java.
- '\u00B1', // 5
- '\u0660', // 6
- '\u00A0', // 7
- '\u0300', // 8
- '\u009F', // 9
- '\u0085', // 10
- '\u001F', // 11
- '\u0020', // 12
- '\u00AB', // 13
- '\u202A', // 14
- '\u202D', // 15
- '\u202B', // 16
- '\u202E', // 17
- '\u202C' // 18
- };
-
- for(int i = 0; i < directionalities.length; i++) {
- assertEquals(directionalities[i],
- Character.getDirectionality(characters[i]));
- }
-
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "offsetByCodePoints",
- args = {java.lang.CharSequence.class, int.class, int.class}
- )
- public void test_offsetByCodePointsLjava_lang_CharSequenceII() {
- int result = Character.offsetByCodePoints("a\uD800\uDC00b", 0, 2);
- assertEquals(3, result);
-
- result = Character.offsetByCodePoints("abcd", 3, -1);
- assertEquals(2, result);
-
- result = Character.offsetByCodePoints("a\uD800\uDC00b", 0, 3);
- assertEquals(4, result);
-
- result = Character.offsetByCodePoints("a\uD800\uDC00b", 3, -1);
- assertEquals(1, result);
-
- result = Character.offsetByCodePoints("a\uD800\uDC00b", 3, 0);
- assertEquals(3, result);
-
- result = Character.offsetByCodePoints("\uD800\uDC00bc", 3, 0);
- assertEquals(3, result);
-
- result = Character.offsetByCodePoints("a\uDC00bc", 3, -1);
- assertEquals(2, result);
-
- result = Character.offsetByCodePoints("a\uD800bc", 3, -1);
- assertEquals(2, result);
-
- try {
- Character.offsetByCodePoints((CharSequence) null, 0, 1);
- fail();
- } catch (NullPointerException e) {
- }
-
- try {
- Character.offsetByCodePoints("abc", -1, 1);
- fail();
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.offsetByCodePoints("abc", 4, 1);
- fail();
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.offsetByCodePoints("abc", 1, 3);
- fail();
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.offsetByCodePoints("abc", 1, -2);
- fail();
- } catch (IndexOutOfBoundsException e) {
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "offsetByCodePoints",
- args = {char[].class, int.class, int.class, int.class, int.class}
- )
- public void test_offsetByCodePoints$CIIII() {
- int result = Character.offsetByCodePoints("a\uD800\uDC00b"
- .toCharArray(), 0, 4, 0, 2);
- assertEquals(3, result);
-
- result = Character.offsetByCodePoints("a\uD800\uDC00b".toCharArray(),
- 0, 4, 0, 3);
- assertEquals(4, result);
-
- result = Character.offsetByCodePoints("a\uD800\uDC00b\uD800c"
- .toCharArray(), 0, 5, 0, 3);
- assertEquals(4, result);
-
- result = Character
- .offsetByCodePoints("abcd".toCharArray(), 0, 4, 3, -1);
- assertEquals(2, result);
-
- result = Character
- .offsetByCodePoints("abcd".toCharArray(), 1, 2, 3, -2);
- assertEquals(1, result);
-
- result = Character.offsetByCodePoints("a\uD800\uDC00b".toCharArray(),
- 0, 4, 3, -1);
- assertEquals(1, result);
-
- result = Character.offsetByCodePoints("a\uD800\uDC00b".toCharArray(),
- 0, 2, 2, -1);
- assertEquals(1, result);
-
- result = Character.offsetByCodePoints("a\uD800\uDC00b".toCharArray(),
- 0, 4, 3, 0);
- assertEquals(3, result);
-
- result = Character.offsetByCodePoints("\uD800\uDC00bc".toCharArray(),
- 0, 4, 3, 0);
- assertEquals(3, result);
-
- result = Character.offsetByCodePoints("a\uDC00bc".toCharArray(), 0, 4,
- 3, -1);
- assertEquals(2, result);
-
- result = Character.offsetByCodePoints("a\uD800bc".toCharArray(), 0, 4,
- 3, -1);
- assertEquals(2, result);
-
- try {
- Character.offsetByCodePoints(null, 0, 4, 1, 1);
- fail();
- } catch (NullPointerException e) {
- }
-
- try {
- Character.offsetByCodePoints("abcd".toCharArray(), -1, 4, 1, 1);
- fail();
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.offsetByCodePoints("abcd".toCharArray(), 0, -1, 1, 1);
- fail();
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.offsetByCodePoints("abcd".toCharArray(), 2, 4, 1, 1);
- fail();
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.offsetByCodePoints("abcd".toCharArray(), 1, 3, 0, 1);
- fail();
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.offsetByCodePoints("abcd".toCharArray(), 1, 1, 3, 1);
- fail();
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.offsetByCodePoints("abc".toCharArray(), 0, 3, 1, 3);
- fail();
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.offsetByCodePoints("abc".toCharArray(), 0, 2, 1, 2);
- fail();
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Character.offsetByCodePoints("abc".toCharArray(), 1, 3, 1, -2);
- fail();
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * @tests java.lang.Character#compareTo(Character)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.lang.Character.class}
- )
- public void test_compareToLjava_lang_Byte() {
- final Character min = new Character(Character.MIN_VALUE);
- final Character mid = new Character((char)(Character.MAX_VALUE/2));
- final Character max = new Character(Character.MAX_VALUE);
-
- assertTrue(max.compareTo(max) == 0);
- assertTrue(min.compareTo(min) == 0);
- assertTrue(mid.compareTo(mid) == 0);
-
- assertTrue(max.compareTo(mid) > 0);
- assertTrue(max.compareTo(min) > 0);
-
- assertTrue(mid.compareTo(max) < 0);
- assertTrue(mid.compareTo(min) > 0);
-
- assertTrue(min.compareTo(mid) < 0);
- assertTrue(min.compareTo(max) < 0);
-
- try {
- min.compareTo(null);
- fail("No NPE");
- } catch (NullPointerException e) {
- }
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Checks exceptions.",
- method = "codePointAt",
- args = {char[].class, int.class, int.class}
- )
- public void test_codePointAt_Invalid() {
-
- try {
- Character.codePointAt(null, 6, 4);
- fail("Expected IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- } catch (Exception e) {
- fail("Expected IndexOutOfBoundsException");
- }
-
- try {
- Character.codePointAt(null, 4, 6);
- fail("Expected NullPointerException");
- } catch (NullPointerException e) {
- // expected
- } catch (Exception e) {
- fail("Expected NullPointerException");
- }
-
- try {
- Character.codePointAt(null, 0, 0);
- fail("Expected IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- } catch (Exception e) {
- fail("Expected IndexOutOfBoundsException");
- }
- }
-
- /**
- * @tests java.lang.Character#Character(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Character",
- args = {char.class}
- )
- public void test_ConstructorC() {
- assertEquals("Constructor failed", 'T', new Character('T').charValue());
- }
-
- /**
- * @tests java.lang.Character#charValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "charValue",
- args = {}
- )
- public void test_charValue() {
- assertEquals("Incorrect char value returned", 'T', new Character('T')
- .charValue());
- }
-
- /**
- * @tests java.lang.Character#compareTo(java.lang.Character)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.lang.Character.class}
- )
- public void test_compareToLjava_lang_Character() {
- Character c = new Character('c');
- Character x = new Character('c');
- Character y = new Character('b');
- Character z = new Character('d');
-
- assertEquals("Returned false for same Character", 0, c.compareTo(c));
- assertEquals("Returned false for identical Character",
- 0, c.compareTo(x));
- assertTrue("Returned other than less than for lesser char", c
- .compareTo(y) > 0);
- assertTrue("Returned other than greater than for greater char", c
- .compareTo(z) < 0);
- }
-
- /**
- * @tests java.lang.Character#digit(char, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "digit",
- args = {char.class, int.class}
- )
- public void test_digitCI() {
- assertEquals("Returned incorrect digit", 1, Character.digit('1', 10));
- assertEquals("Returned incorrect digit", 15, Character.digit('F', 16));
- assertEquals(-1, Character.digit('\uFFFF', 1));
- }
-
- /**
- * @tests java.lang.Character#digit(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "digit",
- args = {int.class, int.class}
- )
- public void test_digit_II() {
- assertEquals(1, Character.digit((int)'1', 10));
- assertEquals(15, Character.digit((int)'F', 16));
-
- assertEquals(-1, Character.digit(0x0000, 37));
- assertEquals(-1, Character.digit(0x0045, 10));
-
- assertEquals(10, Character.digit(0x0041, 20));
- assertEquals(10, Character.digit(0x0061, 20));
-
- assertEquals(-1, Character.digit(0x110000, 20));
- }
-
- /**
- * @tests java.lang.Character#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean java.lang.Character.equals(java.lang.Object)
- assertTrue("Equality test failed", new Character('A')
- .equals(new Character('A')));
- assertTrue("Equality test failed", !(new Character('A')
- .equals(new Character('a'))));
- }
-
- /**
- * @tests java.lang.Character#forDigit(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "forDigit",
- args = {int.class, int.class}
- )
- public void test_forDigitII() {
- char hexChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
- 'a', 'b', 'c', 'd', 'e', 'f' };
- for (int i = 0; i < hexChars.length; i++) {
- assertTrue("Returned incorrect char for " + Integer.toString(i),
- Character.forDigit(i, hexChars.length) == hexChars[i]);
- }
-
- char decimalChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
- '9' };
- for (int i = 0; i < decimalChars.length; i++) {
- assertTrue(
- "Returned incorrect char for " + Integer.toString(i),
- Character.forDigit(i, decimalChars.length) == decimalChars[i]);
- }
-
- }
-
- /**
- * @tests java.lang.Character#getNumericValue(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getNumericValue",
- args = {char.class}
- )
- public void test_getNumericValueC() {
- assertEquals("Returned incorrect numeric value 1", 1, Character
- .getNumericValue('1'));
- assertEquals("Returned incorrect numeric value 2", 15, Character
- .getNumericValue('F'));
- assertEquals("Returned incorrect numeric value 3", -1, Character
- .getNumericValue('\u221e'));
- assertEquals("Returned incorrect numeric value 4", -2, Character
- .getNumericValue('\u00be'));
- assertEquals("Returned incorrect numeric value 5", 10000, Character
- .getNumericValue('\u2182'));
- assertEquals("Returned incorrect numeric value 6", 2, Character
- .getNumericValue('\uff12'));
- }
-
- /**
- * @tests java.lang.Character#getNumericValue(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getNumericValue",
- args = {int.class}
- )
- public void test_getNumericValue_I() {
- assertEquals(1, Character.getNumericValue((int)'1'));
- assertEquals(15, Character.getNumericValue((int)'F'));
- assertEquals(-1, Character.getNumericValue((int)'\u221e'));
- assertEquals(-2, Character.getNumericValue((int)'\u00be'));
- assertEquals(10000, Character.getNumericValue((int)'\u2182'));
- assertEquals(2, Character.getNumericValue((int)'\uff12'));
- assertEquals(-1, Character.getNumericValue(0xFFFF));
-
- assertEquals(-1, Character.getNumericValue(0xFFFF));
- assertEquals(0, Character.getNumericValue(0x1D7CE));
- assertEquals(0, Character.getNumericValue(0x1D7D8));
- assertEquals(-1, Character.getNumericValue(0x2F800));
- assertEquals(-1, Character.getNumericValue(0x10FFFD));
- assertEquals(-1, Character.getNumericValue(0x110000));
-
- assertEquals(50, Character.getNumericValue(0x216C));
-
- assertEquals(10, Character.getNumericValue(0x0041));
- assertEquals(35, Character.getNumericValue(0x005A));
- assertEquals(10, Character.getNumericValue(0x0061));
- assertEquals(35, Character.getNumericValue(0x007A));
- assertEquals(10, Character.getNumericValue(0xFF21));
-
- //FIXME depends on ICU4J
- //assertEquals(35, Character.getNumericValue(0xFF3A));
-
- assertEquals(10, Character.getNumericValue(0xFF41));
- assertEquals(35, Character.getNumericValue(0xFF5A));
- }
-
- /**
- * @tests java.lang.Character#getType(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getType",
- args = {char.class}
- )
- public void test_getTypeC() {
- assertTrue("Returned incorrect type for: \n",
- Character.getType('\n') == Character.CONTROL);
- assertTrue("Returned incorrect type for: 1",
- Character.getType('1') == Character.DECIMAL_DIGIT_NUMBER);
- assertTrue("Returned incorrect type for: ' '",
- Character.getType(' ') == Character.SPACE_SEPARATOR);
- assertTrue("Returned incorrect type for: a",
- Character.getType('a') == Character.LOWERCASE_LETTER);
- assertTrue("Returned incorrect type for: A",
- Character.getType('A') == Character.UPPERCASE_LETTER);
- assertTrue("Returned incorrect type for: <",
- Character.getType('<') == Character.MATH_SYMBOL);
- assertTrue("Returned incorrect type for: ;",
- Character.getType(';') == Character.OTHER_PUNCTUATION);
- assertTrue("Returned incorrect type for: _",
- Character.getType('_') == Character.CONNECTOR_PUNCTUATION);
- assertTrue("Returned incorrect type for: $",
- Character.getType('$') == Character.CURRENCY_SYMBOL);
- assertTrue("Returned incorrect type for: \u2029", Character
- .getType('\u2029') == Character.PARAGRAPH_SEPARATOR);
-
- assertEquals("Wrong constant for FORMAT", 16, Character.FORMAT);
- assertEquals("Wrong constant for PRIVATE_USE",
- 18, Character.PRIVATE_USE);
- }
-
- /**
- * @tests java.lang.Character#getType(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getType",
- args = {int.class}
- )
- public void test_getType_I() {
- assertTrue(Character.getType((int) '\n') == Character.CONTROL);
- assertTrue(Character.getType((int) '1') == Character.DECIMAL_DIGIT_NUMBER);
- assertTrue(Character.getType((int) ' ') == Character.SPACE_SEPARATOR);
- assertTrue(Character.getType((int) 'a') == Character.LOWERCASE_LETTER);
- assertTrue(Character.getType((int) 'A') == Character.UPPERCASE_LETTER);
- assertTrue(Character.getType((int) '<') == Character.MATH_SYMBOL);
- assertTrue(Character.getType((int) ';') == Character.OTHER_PUNCTUATION);
- assertTrue(Character.getType((int) '_') == Character.CONNECTOR_PUNCTUATION);
- assertTrue(Character.getType((int) '$') == Character.CURRENCY_SYMBOL);
- assertTrue(Character.getType((int) '\u2029') == Character.PARAGRAPH_SEPARATOR);
-
- assertTrue(Character.getType(0x9FFF) == Character.UNASSIGNED);
- assertTrue(Character.getType(0x30000) == Character.UNASSIGNED);
- assertTrue(Character.getType(0x110000) == Character.UNASSIGNED);
-
- assertTrue(Character.getType(0x0041) == Character.UPPERCASE_LETTER);
- assertTrue(Character.getType(0x10400) == Character.UPPERCASE_LETTER);
-
- assertTrue(Character.getType(0x0061) == Character.LOWERCASE_LETTER);
- assertTrue(Character.getType(0x10428) == Character.LOWERCASE_LETTER);
-
- assertTrue(Character.getType(0x01C5) == Character.TITLECASE_LETTER);
- assertTrue(Character.getType(0x1FFC) == Character.TITLECASE_LETTER);
-
- assertTrue(Character.getType(0x02B0) == Character.MODIFIER_LETTER);
- assertTrue(Character.getType(0xFF9F) == Character.MODIFIER_LETTER);
-
- assertTrue(Character.getType(0x01BB) == Character.OTHER_LETTER);
- assertTrue(Character.getType(0x2F888) == Character.OTHER_LETTER);
-
- assertTrue(Character.getType(0x0F82) == Character.NON_SPACING_MARK);
- assertTrue(Character.getType(0x1D180) == Character.NON_SPACING_MARK);
-
- assertTrue(Character.getType(0x0488) == Character.ENCLOSING_MARK);
- assertTrue(Character.getType(0x20DE) == Character.ENCLOSING_MARK);
-
- assertTrue(Character.getType(0x1938) == Character.COMBINING_SPACING_MARK);
- assertTrue(Character.getType(0x1D165) == Character.COMBINING_SPACING_MARK);
-
- assertTrue(Character.getType(0x194D) == Character.DECIMAL_DIGIT_NUMBER);
- assertTrue(Character.getType(0x1D7CE) == Character.DECIMAL_DIGIT_NUMBER);
-
- assertTrue(Character.getType(0x2160) == Character.LETTER_NUMBER);
- assertTrue(Character.getType(0x1034A) == Character.LETTER_NUMBER);
-
- assertTrue(Character.getType(0x00B2) == Character.OTHER_NUMBER);
- assertTrue(Character.getType(0x10120) == Character.OTHER_NUMBER);
-
- assertTrue(Character.getType(0x0020) == Character.SPACE_SEPARATOR);
- assertTrue(Character.getType(0x3000) == Character.SPACE_SEPARATOR);
-
- assertTrue(Character.getType(0x2028) == Character.LINE_SEPARATOR);
-
- assertTrue(Character.getType(0x2029) == Character.PARAGRAPH_SEPARATOR);
-
- assertTrue(Character.getType(0x0000) == Character.CONTROL);
- assertTrue(Character.getType(0x009F) == Character.CONTROL);
-
- assertTrue(Character.getType(0x00AD) == Character.FORMAT);
- assertTrue(Character.getType(0xE007F) == Character.FORMAT);
-
- assertTrue(Character.getType(0xE000) == Character.PRIVATE_USE);
- assertTrue(Character.getType(0x10FFFD) == Character.PRIVATE_USE);
-
- assertTrue(Character.getType(0xD800) == Character.SURROGATE);
- assertTrue(Character.getType(0xDFFF) == Character.SURROGATE);
-
- assertTrue(Character.getType(0xFE31) == Character.DASH_PUNCTUATION);
- assertTrue(Character.getType(0xFF0D) == Character.DASH_PUNCTUATION);
-
- assertTrue(Character.getType(0x0028) == Character.START_PUNCTUATION);
- assertTrue(Character.getType(0xFF62) == Character.START_PUNCTUATION);
-
- assertTrue(Character.getType(0x0029) == Character.END_PUNCTUATION);
- assertTrue(Character.getType(0xFF63) == Character.END_PUNCTUATION);
-
- assertTrue(Character.getType(0x005F) == Character.CONNECTOR_PUNCTUATION);
- assertTrue(Character.getType(0xFF3F) == Character.CONNECTOR_PUNCTUATION);
-
- assertTrue(Character.getType(0x2034) == Character.OTHER_PUNCTUATION);
- assertTrue(Character.getType(0x1039F) == Character.OTHER_PUNCTUATION);
-
- assertTrue(Character.getType(0x002B) == Character.MATH_SYMBOL);
- assertTrue(Character.getType(0x1D6C1) == Character.MATH_SYMBOL);
-
- assertTrue(Character.getType(0x0024) == Character.CURRENCY_SYMBOL);
- assertTrue(Character.getType(0xFFE6) == Character.CURRENCY_SYMBOL);
-
- assertTrue(Character.getType(0x005E) == Character.MODIFIER_SYMBOL);
- assertTrue(Character.getType(0xFFE3) == Character.MODIFIER_SYMBOL);
-
- assertTrue(Character.getType(0x00A6) == Character.OTHER_SYMBOL);
- assertTrue(Character.getType(0x1D356) == Character.OTHER_SYMBOL);
-
- assertTrue(Character.getType(0x00AB) == Character.INITIAL_QUOTE_PUNCTUATION);
- assertTrue(Character.getType(0x2039) == Character.INITIAL_QUOTE_PUNCTUATION);
-
- assertTrue(Character.getType(0x00BB) == Character.FINAL_QUOTE_PUNCTUATION);
- assertTrue(Character.getType(0x203A) == Character.FINAL_QUOTE_PUNCTUATION);
- }
-
- /**
- * @tests java.lang.Character#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- assertEquals("Incorrect hash returned",
- 89, new Character('Y').hashCode());
- }
-
- /**
- * @tests java.lang.Character#isDefined(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isDefined",
- args = {char.class}
- )
- public void test_isDefinedC() {
- assertTrue("Defined character returned false", Character.isDefined('v'));
- assertTrue("Defined character returned false", Character
- .isDefined('\u6039'));
- }
-
- /**
- * @tests java.lang.Character#isDefined(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isDefined",
- args = {int.class}
- )
- public void test_isDefined_I(){
- assertTrue(Character.isDefined((int)'v'));
- assertTrue(Character.isDefined((int)'\u6039'));
- assertTrue(Character.isDefined(0x10300));
-
- assertFalse(Character.isDefined(0x30000));
- assertFalse(Character.isDefined(0x3FFFF));
- assertFalse(Character.isDefined(0x110000));
- }
-
- /**
- * @tests java.lang.Character#isDigit(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isDigit",
- args = {char.class}
- )
- public void test_isDigitC() {
- assertTrue("Digit returned false", Character.isDigit('1'));
- assertTrue("Non-Digit returned false", !Character.isDigit('A'));
- }
-
- /**
- * @tests java.lang.Character#isDigit(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isDigit",
- args = {int.class}
- )
- public void test_isDigit_I() {
- assertTrue(Character.isDigit((int) '1'));
- assertFalse(Character.isDigit((int) 'A'));
-
- assertTrue(Character.isDigit(0x0030));
- assertTrue(Character.isDigit(0x0035));
- assertTrue(Character.isDigit(0x0039));
-
- assertTrue(Character.isDigit(0x0660));
- assertTrue(Character.isDigit(0x0665));
- assertTrue(Character.isDigit(0x0669));
-
- assertTrue(Character.isDigit(0x06F0));
- assertTrue(Character.isDigit(0x06F5));
- assertTrue(Character.isDigit(0x06F9));
-
- assertTrue(Character.isDigit(0x0966));
- assertTrue(Character.isDigit(0x096A));
- assertTrue(Character.isDigit(0x096F));
-
- assertTrue(Character.isDigit(0xFF10));
- assertTrue(Character.isDigit(0xFF15));
- assertTrue(Character.isDigit(0xFF19));
-
- assertTrue(Character.isDigit(0x1D7CE));
- assertTrue(Character.isDigit(0x1D7D8));
-
- assertFalse(Character.isDigit(0x2F800));
- assertFalse(Character.isDigit(0x10FFFD));
- assertFalse(Character.isDigit(0x110000));
- }
-
- /**
- * @tests java.lang.Character#isIdentifierIgnorable(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isIdentifierIgnorable",
- args = {char.class}
- )
- public void test_isIdentifierIgnorableC() {
- assertTrue("Ignorable whitespace returned false", Character
- .isIdentifierIgnorable('\u0007'));
- assertTrue("Ignorable non - whitespace control returned false",
- Character.isIdentifierIgnorable('\u000f'));
- assertTrue("Ignorable join control returned false", Character
- .isIdentifierIgnorable('\u200e'));
-
- // the spec is wrong, and our implementation is correct
- assertTrue("Ignorable bidi control returned false", Character
- .isIdentifierIgnorable('\u202b'));
-
- assertTrue("Ignorable format control returned false", Character
- .isIdentifierIgnorable('\u206c'));
- assertTrue("Ignorable zero-width no-break returned false", Character
- .isIdentifierIgnorable('\ufeff'));
-
- assertTrue("Non-Ignorable returned true", !Character
- .isIdentifierIgnorable('\u0065'));
- }
-
- /**
- * @tests java.lang.Character#isIdentifierIgnorable(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isIdentifierIgnorable",
- args = {int.class}
- )
- public void test_isIdentifierIgnorable_I() {
- assertTrue(Character.isIdentifierIgnorable(0x0000));
- assertTrue(Character.isIdentifierIgnorable(0x0004));
- assertTrue(Character.isIdentifierIgnorable(0x0008));
-
- assertTrue(Character.isIdentifierIgnorable(0x000E));
- assertTrue(Character.isIdentifierIgnorable(0x0013));
- assertTrue(Character.isIdentifierIgnorable(0x001B));
-
- assertTrue(Character.isIdentifierIgnorable(0x007F));
- assertTrue(Character.isIdentifierIgnorable(0x008F));
- assertTrue(Character.isIdentifierIgnorable(0x009F));
-
- assertTrue(Character.isIdentifierIgnorable(0x202b));
- assertTrue(Character.isIdentifierIgnorable(0x206c));
- assertTrue(Character.isIdentifierIgnorable(0xfeff));
- assertFalse(Character.isIdentifierIgnorable(0x0065));
-
- assertTrue(Character.isIdentifierIgnorable(0x1D173));
-
- assertFalse(Character.isIdentifierIgnorable(0x10FFFD));
- assertFalse(Character.isIdentifierIgnorable(0x110000));
- }
-
- /**
- * @tests java.lang.Character#isMirrored(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMirrored",
- args = {char.class}
- )
- public void test_isMirrored_C() {
- assertTrue(Character.isMirrored('\u0028'));
- assertFalse(Character.isMirrored('\uFFFF'));
- }
-
- /**
- * @tests java.lang.Character#isMirrored(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMirrored",
- args = {int.class}
- )
- public void test_isMirrored_I() {
- assertTrue(Character.isMirrored(0x0028));
- assertFalse(Character.isMirrored(0xFFFF));
- assertFalse(Character.isMirrored(0x110000));
- }
-
- /**
- * @tests java.lang.Character#isISOControl(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isISOControl",
- args = {char.class}
- )
- public void test_isISOControlC() {
- // Test for method boolean java.lang.Character.isISOControl(char)
- for (int i = 0; i < 32; i++)
- assertTrue("ISOConstrol char returned false", Character
- .isISOControl((char) i));
-
- for (int i = 127; i < 160; i++)
- assertTrue("ISOConstrol char returned false", Character
- .isISOControl((char) i));
-
- for (int i = 160; i < 260; i++)
- assertFalse("Not ISOConstrol char returned true", Character
- .isISOControl((char) i));
- }
-
- /**
- * @tests java.lang.Character#isISOControl(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isISOControl",
- args = {int.class}
- )
- public void test_isISOControlI() {
- // Test for method boolean java.lang.Character.isISOControl(char)
- for (int i = 0; i < 32; i++)
- assertTrue("ISOConstrol char returned false", Character
- .isISOControl(i));
-
- for (int i = 127; i < 160; i++)
- assertTrue("ISOConstrol char returned false", Character
- .isISOControl(i));
-
- for (int i = 160; i < 260; i++)
- assertFalse("Not ISOConstrol char returned true", Character
- .isISOControl(i));
-
- }
-
-
- /**
- * @tests java.lang.Character#isJavaIdentifierPart(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isJavaIdentifierPart",
- args = {char.class}
- )
- public void test_isJavaIdentifierPartC() {
- assertTrue("letter returned false", Character.isJavaIdentifierPart('l'));
- assertTrue("currency returned false", Character
- .isJavaIdentifierPart('$'));
- assertTrue("digit returned false", Character.isJavaIdentifierPart('9'));
- assertTrue("connecting char returned false", Character
- .isJavaIdentifierPart('_'));
- assertTrue("ignorable control returned false", Character
- .isJavaIdentifierPart('\u200c'));
- assertTrue("semi returned true", !Character.isJavaIdentifierPart(';'));
- }
-
- /**
- * @tests java.lang.Character#isJavaIdentifierPart(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isJavaIdentifierPart",
- args = {int.class}
- )
- public void test_isJavaIdentifierPart_I() {
- assertTrue(Character.isJavaIdentifierPart((int)'l'));
- assertTrue(Character.isJavaIdentifierPart((int)'$'));
- assertTrue(Character.isJavaIdentifierPart((int)'9'));
- assertTrue(Character.isJavaIdentifierPart((int)'_'));
- assertFalse(Character.isJavaIdentifierPart((int)';'));
-
- assertTrue(Character.isJavaIdentifierPart(0x0041));
- assertTrue(Character.isJavaIdentifierPart(0x10400));
- assertTrue(Character.isJavaIdentifierPart(0x0061));
- assertTrue(Character.isJavaIdentifierPart(0x10428));
- assertTrue(Character.isJavaIdentifierPart(0x01C5));
- assertTrue(Character.isJavaIdentifierPart(0x1FFC));
- assertTrue(Character.isJavaIdentifierPart(0x02B0));
- assertTrue(Character.isJavaIdentifierPart(0xFF9F));
- assertTrue(Character.isJavaIdentifierPart(0x01BB));
- assertTrue(Character.isJavaIdentifierPart(0x2F888));
-
- assertTrue(Character.isJavaIdentifierPart(0x0024));
- assertTrue(Character.isJavaIdentifierPart(0xFFE6));
-
- assertTrue(Character.isJavaIdentifierPart(0x005F));
- assertTrue(Character.isJavaIdentifierPart(0xFF3F));
-
- assertTrue(Character.isJavaIdentifierPart(0x194D));
- assertTrue(Character.isJavaIdentifierPart(0x1D7CE));
- assertTrue(Character.isJavaIdentifierPart(0x2160));
- assertTrue(Character.isJavaIdentifierPart(0x1034A));
-
- assertTrue(Character.isJavaIdentifierPart(0x0F82));
- assertTrue(Character.isJavaIdentifierPart(0x1D180));
-
- assertTrue(Character.isJavaIdentifierPart(0x0000));
- assertTrue(Character.isJavaIdentifierPart(0x0008));
- assertTrue(Character.isJavaIdentifierPart(0x000E));
- assertTrue(Character.isJavaIdentifierPart(0x001B));
- assertTrue(Character.isJavaIdentifierPart(0x007F));
- assertTrue(Character.isJavaIdentifierPart(0x009F));
- assertTrue(Character.isJavaIdentifierPart(0x00AD));
- assertTrue(Character.isJavaIdentifierPart(0xE007F));
-
- assertTrue(Character.isJavaIdentifierPart(0x200C));
- }
-
- /**
- * @tests java.lang.Character#isJavaIdentifierStart(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isJavaIdentifierStart",
- args = {char.class}
- )
- public void test_isJavaIdentifierStartC() {
- assertTrue("letter returned false", Character
- .isJavaIdentifierStart('l'));
- assertTrue("currency returned false", Character
- .isJavaIdentifierStart('$'));
- assertTrue("connecting char returned false", Character
- .isJavaIdentifierStart('_'));
- assertTrue("digit returned true", !Character.isJavaIdentifierStart('9'));
- assertTrue("ignorable control returned true", !Character
- .isJavaIdentifierStart('\u200b'));
- assertTrue("semi returned true", !Character.isJavaIdentifierStart(';'));
- }
-
- /**
- * @tests java.lang.Character#isJavaIdentifierStart(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isJavaIdentifierStart",
- args = {int.class}
- )
- public void test_isJavaIdentifierStart_I() {
- assertTrue(Character.isJavaIdentifierStart((int)'l'));
- assertTrue(Character.isJavaIdentifierStart((int)'$'));
- assertTrue(Character.isJavaIdentifierStart((int)'_'));
- assertFalse(Character.isJavaIdentifierStart((int)'9'));
- assertFalse(Character.isJavaIdentifierStart((int)'\u200b'));
- assertFalse(Character.isJavaIdentifierStart((int)';'));
-
- assertTrue(Character.isJavaIdentifierStart(0x0041));
- assertTrue(Character.isJavaIdentifierStart(0x10400));
- assertTrue(Character.isJavaIdentifierStart(0x0061));
- assertTrue(Character.isJavaIdentifierStart(0x10428));
- assertTrue(Character.isJavaIdentifierStart(0x01C5));
- assertTrue(Character.isJavaIdentifierStart(0x1FFC));
- assertTrue(Character.isJavaIdentifierStart(0x02B0));
- assertTrue(Character.isJavaIdentifierStart(0xFF9F));
- assertTrue(Character.isJavaIdentifierStart(0x01BB));
- assertTrue(Character.isJavaIdentifierStart(0x2F888));
-
- assertTrue(Character.isJavaIdentifierPart(0x0024));
- assertTrue(Character.isJavaIdentifierPart(0xFFE6));
-
- assertTrue(Character.isJavaIdentifierPart(0x005F));
- assertTrue(Character.isJavaIdentifierPart(0xFF3F));
-
- assertTrue(Character.isJavaIdentifierPart(0x2160));
- assertTrue(Character.isJavaIdentifierPart(0x1034A));
-
- assertFalse(Character.isJavaIdentifierPart(0x110000));
- }
-
- /**
- * @tests java.lang.Character#isJavaLetter(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isJavaLetter",
- args = {char.class}
- )
- @SuppressWarnings("deprecation")
- public void test_isJavaLetterC() {
- assertTrue("letter returned false", Character.isJavaLetter('l'));
- assertTrue("currency returned false", Character.isJavaLetter('$'));
- assertTrue("connecting char returned false", Character
- .isJavaLetter('_'));
-
- assertTrue("digit returned true", !Character.isJavaLetter('9'));
- assertTrue("ignored control returned true", !Character
- .isJavaLetter('\u200b'));
- assertTrue("semi returned true", !Character.isJavaLetter(';'));
- }
-
- /**
- * @tests java.lang.Character#isJavaLetterOrDigit(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isJavaLetterOrDigit",
- args = {char.class}
- )
- @SuppressWarnings("deprecation")
- public void test_isJavaLetterOrDigitC() {
- assertTrue("letter returned false", Character.isJavaLetterOrDigit('l'));
- assertTrue("currency returned false", Character
- .isJavaLetterOrDigit('$'));
- assertTrue("digit returned false", Character.isJavaLetterOrDigit('9'));
- assertTrue("connecting char returned false", Character
- .isJavaLetterOrDigit('_'));
- assertTrue("semi returned true", !Character.isJavaLetterOrDigit(';'));
- }
-
- /**
- * @tests java.lang.Character#isLetter(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isLetter",
- args = {char.class}
- )
- public void test_isLetterC() {
- assertTrue("Letter returned false", Character.isLetter('L'));
- assertTrue("Non-Letter returned true", !Character.isLetter('9'));
- }
-
- /**
- * @tests java.lang.Character#isLetter(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isLetter",
- args = {int.class}
- )
- public void test_isLetter_I() {
- assertTrue(Character.isLetter((int)'L'));
- assertFalse(Character.isLetter((int)'9'));
-
- assertTrue(Character.isLetter(0x1FA9));
- assertTrue(Character.isLetter(0x1D400));
- assertTrue(Character.isLetter(0x1D622));
- assertTrue(Character.isLetter(0x10000));
-
- assertFalse(Character.isLetter(0x1012C));
- assertFalse(Character.isLetter(0x110000));
- }
-
- /**
- * @tests java.lang.Character#isLetterOrDigit(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isLetterOrDigit",
- args = {char.class}
- )
- public void test_isLetterOrDigitC() {
- assertTrue("Digit returned false", Character.isLetterOrDigit('9'));
- assertTrue("Letter returned false", Character.isLetterOrDigit('K'));
- assertTrue("Control returned true", !Character.isLetterOrDigit('\n'));
- assertTrue("Punctuation returned true", !Character.isLetterOrDigit('?'));
- }
-
- /**
- * @tests java.lang.Character#isLetterOrDigit(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isLetterOrDigit",
- args = {int.class}
- )
- public void test_isLetterOrDigit_I() {
- assertTrue(Character.isLetterOrDigit((int)'9'));
- assertTrue(Character.isLetterOrDigit((int)'K'));
- assertFalse(Character.isLetterOrDigit((int)'\n'));
- assertFalse(Character.isLetterOrDigit((int)'?'));
-
- assertTrue(Character.isLetterOrDigit(0x1FA9));
- assertTrue(Character.isLetterOrDigit(0x1D400));
- assertTrue(Character.isLetterOrDigit(0x1D622));
- assertTrue(Character.isLetterOrDigit(0x10000));
-
- assertTrue(Character.isLetterOrDigit(0x1D7CE));
- assertTrue(Character.isLetterOrDigit(0x1D7D8));
-
- assertFalse(Character.isLetterOrDigit(0x10FFFD));
- assertFalse(Character.isLetterOrDigit(0x1012C));
- assertFalse(Character.isLetterOrDigit(0x110000));
- }
-
- /**
- * @tests java.lang.Character#isLowerCase(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isLowerCase",
- args = {char.class}
- )
- public void test_isLowerCaseC() {
- assertTrue("lower returned false", Character.isLowerCase('a'));
- assertTrue("upper returned true", !Character.isLowerCase('T'));
- }
-
- /**
- * @tests java.lang.Character#isLowerCase(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isLowerCase",
- args = {int.class}
- )
- public void test_isLowerCase_I() {
- assertTrue(Character.isLowerCase((int)'a'));
- assertFalse(Character.isLowerCase((int)'T'));
-
- assertTrue(Character.isLowerCase(0x10428));
- assertTrue(Character.isLowerCase(0x1D4EA));
-
- assertFalse(Character.isLowerCase(0x1D504));
- assertFalse(Character.isLowerCase(0x30000));
- assertFalse(Character.isLowerCase(0x110000));
- }
-
- /**
- * @tests java.lang.Character#isSpace(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isSpace",
- args = {char.class}
- )
- @SuppressWarnings("deprecation")
- public void test_isSpaceC() {
- // Test for method boolean java.lang.Character.isSpace(char)
- assertTrue("space returned false", Character.isSpace('\n'));
- assertTrue("non-space returned true", !Character.isSpace('T'));
- }
-
- /**
- * @tests java.lang.Character#isSpaceChar(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isSpaceChar",
- args = {char.class}
- )
- public void test_isSpaceCharC() {
- assertTrue("space returned false", Character.isSpaceChar('\u0020'));
- assertTrue("non-space returned true", !Character.isSpaceChar('\n'));
- }
-
- /**
- * @tests java.lang.Character#isSpaceChar(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isSpaceChar",
- args = {int.class}
- )
- public void test_isSpaceChar_I() {
- assertTrue(Character.isSpaceChar((int)'\u0020'));
- assertFalse(Character.isSpaceChar((int)'\n'));
-
- assertTrue(Character.isSpaceChar(0x2000));
- assertTrue(Character.isSpaceChar(0x200A));
-
- assertTrue(Character.isSpaceChar(0x2028));
- assertTrue(Character.isSpaceChar(0x2029));
-
- assertFalse(Character.isSpaceChar(0x110000));
- }
-
- /**
- * @tests java.lang.Character#isTitleCase(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isTitleCase",
- args = {char.class}
- )
- public void test_isTitleCaseC() {
- char[] tChars = { (char) 0x01c5, (char) 0x01c8, (char) 0x01cb,
- (char) 0x01f2, (char) 0x1f88, (char) 0x1f89, (char) 0x1f8a,
- (char) 0x1f8b, (char) 0x1f8c, (char) 0x1f8d, (char) 0x1f8e,
- (char) 0x1f8f, (char) 0x1f98, (char) 0x1f99, (char) 0x1f9a,
- (char) 0x1f9b, (char) 0x1f9c, (char) 0x1f9d, (char) 0x1f9e,
- (char) 0x1f9f, (char) 0x1fa8, (char) 0x1fa9, (char) 0x1faa,
- (char) 0x1fab, (char) 0x1fac, (char) 0x1fad, (char) 0x1fae,
- (char) 0x1faf, (char) 0x1fbc, (char) 0x1fcc, (char) 0x1ffc };
- byte tnum = 0;
- for (char c = 0; c < 65535; c++) {
- if (Character.isTitleCase(c)) {
- tnum++;
- int i;
- for (i = 0; i < tChars.length; i++)
- if (tChars[i] == c)
- i = tChars.length + 1;
- if (i < tChars.length) {
- fail("Non Title Case char returned true");
- }
- }
- }
- assertTrue("Failed to find all Title Case chars", tnum == tChars.length);
- }
-
- /**
- * @tests java.lang.Character#isTitleCase(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isTitleCase",
- args = {int.class}
- )
- public void test_isTitleCase_I() {
- //all the titlecase characters
- int[] titleCaseCharacters = { 0x01c5, 0x01c8, 0x01cb, 0x01f2, 0x1f88,
- 0x1f89, 0x1f8a, 0x1f8b, 0x1f8c, 0x1f8d, 0x1f8e, 0x1f8f, 0x1f98,
- 0x1f99, 0x1f9a, 0x1f9b, 0x1f9c, 0x1f9d, 0x1f9e, 0x1f9f, 0x1fa8,
- 0x1fa9, 0x1faa, 0x1fab, 0x1fac, 0x1fad, 0x1fae, 0x1faf, 0x1fbc,
- 0x1fcc, 0x1ffc };
-
- for (int i = 0; i < titleCaseCharacters.length; i++) {
- assertTrue(Character.isTitleCase(titleCaseCharacters[i]));
- }
-
- assertFalse(Character.isTitleCase(0x110000));
- }
-
- /**
- * @tests java.lang.Character#isUnicodeIdentifierPart(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isUnicodeIdentifierPart",
- args = {char.class}
- )
- public void test_isUnicodeIdentifierPartC() {
- assertTrue("'a' returned false", Character.isUnicodeIdentifierPart('a'));
- assertTrue("'2' returned false", Character.isUnicodeIdentifierPart('2'));
- assertTrue("'+' returned true", !Character.isUnicodeIdentifierPart('+'));
- }
-
- /**
- * @tests java.lang.Character#isUnicodeIdentifierPart(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isUnicodeIdentifierPart",
- args = {int.class}
- )
- public void test_isUnicodeIdentifierPart_I() {
- assertTrue(Character.isUnicodeIdentifierPart((int)'a'));
- assertTrue(Character.isUnicodeIdentifierPart((int)'2'));
- assertFalse(Character.isUnicodeIdentifierPart((int)'+'));
-
- assertTrue(Character.isUnicodeIdentifierPart(0x1FA9));
- assertTrue(Character.isUnicodeIdentifierPart(0x1D400));
- assertTrue(Character.isUnicodeIdentifierPart(0x1D622));
- assertTrue(Character.isUnicodeIdentifierPart(0x10000));
-
- assertTrue(Character.isUnicodeIdentifierPart(0x0030));
- assertTrue(Character.isUnicodeIdentifierPart(0x0035));
- assertTrue(Character.isUnicodeIdentifierPart(0x0039));
-
- assertTrue(Character.isUnicodeIdentifierPart(0x0660));
- assertTrue(Character.isUnicodeIdentifierPart(0x0665));
- assertTrue(Character.isUnicodeIdentifierPart(0x0669));
-
- assertTrue(Character.isUnicodeIdentifierPart(0x06F0));
- assertTrue(Character.isUnicodeIdentifierPart(0x06F5));
- assertTrue(Character.isUnicodeIdentifierPart(0x06F9));
-
- assertTrue(Character.isUnicodeIdentifierPart(0x0966));
- assertTrue(Character.isUnicodeIdentifierPart(0x096A));
- assertTrue(Character.isUnicodeIdentifierPart(0x096F));
-
- assertTrue(Character.isUnicodeIdentifierPart(0xFF10));
- assertTrue(Character.isUnicodeIdentifierPart(0xFF15));
- assertTrue(Character.isUnicodeIdentifierPart(0xFF19));
-
- assertTrue(Character.isUnicodeIdentifierPart(0x1D7CE));
- assertTrue(Character.isUnicodeIdentifierPart(0x1D7D8));
-
- assertTrue(Character.isUnicodeIdentifierPart(0x16EE));
- assertTrue(Character.isUnicodeIdentifierPart(0xFE33));
- assertTrue(Character.isUnicodeIdentifierPart(0xFF10));
- assertTrue(Character.isUnicodeIdentifierPart(0x1D165));
- assertTrue(Character.isUnicodeIdentifierPart(0x1D167));
- assertTrue(Character.isUnicodeIdentifierPart(0x1D173));
-
- assertFalse(Character.isUnicodeIdentifierPart(0x10FFFF));
- assertFalse(Character.isUnicodeIdentifierPart(0x110000));
- }
-
- /**
- * @tests java.lang.Character#isUnicodeIdentifierStart(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isUnicodeIdentifierStart",
- args = {char.class}
- )
- public void test_isUnicodeIdentifierStartC() {
- assertTrue("'a' returned false", Character
- .isUnicodeIdentifierStart('a'));
- assertTrue("'2' returned true", !Character
- .isUnicodeIdentifierStart('2'));
- assertTrue("'+' returned true", !Character
- .isUnicodeIdentifierStart('+'));
- }
-
- /**
- * @tests java.lang.Character#isUnicodeIdentifierStart(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isUnicodeIdentifierStart",
- args = {int.class}
- )
- public void test_isUnicodeIdentifierStart_I() {
-
- assertTrue(Character.isUnicodeIdentifierStart((int) 'a'));
- assertFalse(Character.isUnicodeIdentifierStart((int) '2'));
- assertFalse(Character.isUnicodeIdentifierStart((int) '+'));
-
- assertTrue(Character.isUnicodeIdentifierStart(0x1FA9));
- assertTrue(Character.isUnicodeIdentifierStart(0x1D400));
- assertTrue(Character.isUnicodeIdentifierStart(0x1D622));
- assertTrue(Character.isUnicodeIdentifierStart(0x10000));
-
- assertTrue(Character.isUnicodeIdentifierStart(0x16EE));
-
- // number is not a valid start of a Unicode identifier
- assertFalse(Character.isUnicodeIdentifierStart(0x0030));
- assertFalse(Character.isUnicodeIdentifierStart(0x0039));
- assertFalse(Character.isUnicodeIdentifierStart(0x0660));
- assertFalse(Character.isUnicodeIdentifierStart(0x0669));
- assertFalse(Character.isUnicodeIdentifierStart(0x06F0));
- assertFalse(Character.isUnicodeIdentifierStart(0x06F9));
-
- assertFalse(Character.isUnicodeIdentifierPart(0x10FFFF));
- assertFalse(Character.isUnicodeIdentifierPart(0x110000));
- }
-
- /**
- * @tests java.lang.Character#isUpperCase(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isUpperCase",
- args = {char.class}
- )
- public void test_isUpperCaseC() {
- assertTrue("Incorrect case value", !Character.isUpperCase('t'));
- assertTrue("Incorrect case value", Character.isUpperCase('T'));
- assertFalse("Incorrect case value", Character.isUpperCase('1'));
- assertFalse("Incorrect case value", Character.isUpperCase('?'));
- }
-
- /**
- * @tests java.lang.Character#isUpperCase(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isUpperCase",
- args = {int.class}
- )
- public void test_isUpperCase_I() {
- assertFalse(Character.isUpperCase((int)'t'));
- assertTrue(Character.isUpperCase((int)'T'));
-
- assertTrue(Character.isUpperCase(0x1D504));
- assertTrue(Character.isUpperCase(0x1D608));
-
- assertFalse(Character.isUpperCase(0x1D656));
- assertFalse(Character.isUpperCase(0x10FFFD));
- assertFalse(Character.isUpperCase(0x110000));
- }
-
- /**
- * @tests java.lang.Character#isWhitespace(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isWhitespace",
- args = {char.class}
- )
- public void test_isWhitespaceC() {
- assertTrue("space returned false", Character.isWhitespace('\n'));
- assertTrue("non-space returned true", !Character.isWhitespace('T'));
- }
-
- /**
- * @tests java.lang.Character#isWhitespace(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isWhitespace",
- args = {int.class}
- )
- public void test_isWhitespace_I() {
- assertTrue(Character.isWhitespace((int)'\n'));
- assertFalse(Character.isWhitespace((int)'T'));
-
- assertTrue(Character.isWhitespace(0x0009));
- assertTrue(Character.isWhitespace(0x000A));
- assertTrue(Character.isWhitespace(0x000B));
- assertTrue(Character.isWhitespace(0x000C));
- assertTrue(Character.isWhitespace(0x000D));
- assertTrue(Character.isWhitespace(0x001C));
- assertTrue(Character.isWhitespace(0x001D));
- assertTrue(Character.isWhitespace(0x001F));
- assertTrue(Character.isWhitespace(0x001E));
-
- assertTrue(Character.isWhitespace(0x2000));
- assertTrue(Character.isWhitespace(0x200A));
-
- assertTrue(Character.isWhitespace(0x2028));
- assertTrue(Character.isWhitespace(0x2029));
-
- assertFalse(Character.isWhitespace(0x00A0));
- assertFalse(Character.isWhitespace(0x202F));
- assertFalse(Character.isWhitespace(0x110000));
-
- assertFalse(Character.isWhitespace(0xFEFF));
-
- //FIXME depend on ICU4J
- //assertFalse(Character.isWhitespace(0x2007));
-
- }
-
- /**
- * @tests java.lang.Character#reverseBytes(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reverseBytes",
- args = {char.class}
- )
- public void test_reverseBytesC() {
- char original[] = new char[]{0x0000, 0x0010, 0x00AA, 0xB000, 0xCC00, 0xABCD, 0xFFAA};
- char reversed[] = new char[]{0x0000, 0x1000, 0xAA00, 0x00B0, 0x00CC, 0xCDAB, 0xAAFF};
- assertTrue("Test self check", original.length==reversed.length);
-
- for (int i=0; i<original.length; i++) {
- char origChar = original[i];
- char reversedChar = reversed[i];
- char origReversed= Character.reverseBytes(origChar);
-
- assertTrue("java.lang.Character.reverseBytes failed: orig char="
- +Integer.toHexString(origChar)+", reversed char="
- +Integer.toHexString(origReversed), reversedChar==origReversed);
- }
- }
-
- /**
- * @tests java.lang.Character#toLowerCase(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toLowerCase",
- args = {char.class}
- )
- public void test_toLowerCaseC() {
- assertEquals("Failed to change case", 't', Character.toLowerCase('T'));
- assertEquals("Failed to change case", 't', Character.toLowerCase('t'));
- assertEquals("Failed to change case", '1', Character.toLowerCase('1'));
- }
-
- /**
- * @tests java.lang.Character#toLowerCase(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toLowerCase",
- args = {int.class}
- )
- public void test_toLowerCase_I() {
- assertEquals('t', Character.toLowerCase((int)'T'));
-
- assertEquals(0x10428, Character.toLowerCase(0x10400));
- assertEquals(0x10428, Character.toLowerCase(0x10428));
-
- assertEquals(0x1D504, Character.toLowerCase(0x1D504));
- assertEquals(0x10FFFD, Character.toLowerCase(0x10FFFD));
- assertEquals(0x110000, Character.toLowerCase(0x110000));
- }
-
- /**
- * @tests java.lang.Character#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- assertEquals("Incorrect String returned", "T", new Character('T').toString());
- assertEquals("Incorrect String returned", "1", new Character('1').toString());
- assertEquals("Incorrect String returned", "$", new Character('$').toString());
- }
-
- /**
- * @tests java.lang.Character#toString(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {char.class}
- )
- public void test_toString_char() {
- assertEquals("Incorrect String returned", "T", Character.toString('T'));
- }
-
- /**
- * @tests java.lang.Character#toTitleCase(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toTitleCase",
- args = {char.class}
- )
- public void test_toTitleCaseC() {
- assertEquals("Incorrect title case for a",
- 'A', Character.toTitleCase('a'));
- assertEquals("Incorrect title case for A",
- 'A', Character.toTitleCase('A'));
- assertEquals("Incorrect title case for 1",
- '1', Character.toTitleCase('1'));
- }
-
- /**
- * @tests java.lang.Character#toTitleCase(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toTitleCase",
- args = {int.class}
- )
- public void test_toTitleCase_I() {
- assertEquals('A', Character.toTitleCase((int)'a'));
- assertEquals('A', Character.toTitleCase((int)'A'));
- assertEquals('1', Character.toTitleCase((int)'1'));
-
- assertEquals(0x10400, Character.toTitleCase(0x10428));
- assertEquals(0x10400, Character.toTitleCase(0x10400));
-
- assertEquals(0x10FFFF, Character.toTitleCase(0x10FFFF));
- assertEquals(0x110000, Character.toTitleCase(0x110000));
- }
-
- /**
- * @tests java.lang.Character#toUpperCase(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toUpperCase",
- args = {char.class}
- )
- public void test_toUpperCaseC() {
- // Test for method char java.lang.Character.toUpperCase(char)
- assertEquals("Incorrect upper case for a",
- 'A', Character.toUpperCase('a'));
- assertEquals("Incorrect upper case for A",
- 'A', Character.toUpperCase('A'));
- assertEquals("Incorrect upper case for 1",
- '1', Character.toUpperCase('1'));
- }
-
- /**
- * @tests java.lang.Character#toUpperCase(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toUpperCase",
- args = {int.class}
- )
- public void test_toUpperCase_I() {
- assertEquals('A', Character.toUpperCase((int)'a'));
- assertEquals('A', Character.toUpperCase((int)'A'));
- assertEquals('1', Character.toUpperCase((int)'1'));
-
- assertEquals(0x10400, Character.toUpperCase(0x10428));
- assertEquals(0x10400, Character.toUpperCase(0x10400));
-
- assertEquals(0x10FFFF, Character.toUpperCase(0x10FFFF));
- assertEquals(0x110000, Character.toUpperCase(0x110000));
- }
-
- /**
- * @tests java.lang.Character#getDirectionality(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDirectionality",
- args = {int.class}
- )
- public void test_isDirectionaliy_I(){
- assertEquals(Character.DIRECTIONALITY_UNDEFINED, Character
- .getDirectionality(0xFFFE));
- assertEquals(Character.DIRECTIONALITY_UNDEFINED, Character
- .getDirectionality(0x30000));
- assertEquals(Character.DIRECTIONALITY_UNDEFINED, Character
- .getDirectionality(0x110000));
- assertEquals(Character.DIRECTIONALITY_UNDEFINED, Character
- .getDirectionality(-1));
-
- assertEquals(Character.DIRECTIONALITY_LEFT_TO_RIGHT, Character
- .getDirectionality(0x0041));
- assertEquals(Character.DIRECTIONALITY_LEFT_TO_RIGHT, Character
- .getDirectionality(0x10000));
- assertEquals(Character.DIRECTIONALITY_LEFT_TO_RIGHT, Character
- .getDirectionality(0x104A9));
-
- assertEquals(Character.DIRECTIONALITY_RIGHT_TO_LEFT, Character
- .getDirectionality(0xFB4F));
- assertEquals(Character.DIRECTIONALITY_RIGHT_TO_LEFT, Character
- .getDirectionality(0x10838));
-
- assertEquals(Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC, Character
- .getDirectionality(0x0600));
- assertEquals(Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC, Character
- .getDirectionality(0xFEFC));
-
- assertEquals(Character.DIRECTIONALITY_EUROPEAN_NUMBER, Character
- .getDirectionality(0x2070));
- assertEquals(Character.DIRECTIONALITY_EUROPEAN_NUMBER, Character
- .getDirectionality(0x1D7FF));
-
- // No common char in this group on android and java.
- // assertEquals(Character.DIRECTIONALITY_EUROPEAN_NUMBER_SEPARATOR, Character
- // .getDirectionality(0x002B));
- // assertEquals(Character.DIRECTIONALITY_EUROPEAN_NUMBER_SEPARATOR, Character
- // .getDirectionality(0xFF0B));
-
- assertEquals(Character.DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR, Character
- .getDirectionality(0x0023));
- assertEquals(Character.DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR, Character
- .getDirectionality(0x17DB));
-
- assertEquals(Character.DIRECTIONALITY_ARABIC_NUMBER, Character
- .getDirectionality(0x0660));
- assertEquals(Character.DIRECTIONALITY_ARABIC_NUMBER, Character
- .getDirectionality(0x066C));
-
- assertEquals(Character.DIRECTIONALITY_COMMON_NUMBER_SEPARATOR, Character
- .getDirectionality(0x002C));
- assertEquals(Character.DIRECTIONALITY_COMMON_NUMBER_SEPARATOR, Character
- .getDirectionality(0xFF1A));
-
- assertEquals(Character.DIRECTIONALITY_NONSPACING_MARK, Character
- .getDirectionality(0x17CE));
- assertEquals(Character.DIRECTIONALITY_NONSPACING_MARK, Character
- .getDirectionality(0xE01DB));
-
- assertEquals(Character.DIRECTIONALITY_BOUNDARY_NEUTRAL, Character
- .getDirectionality(0x0000));
- assertEquals(Character.DIRECTIONALITY_BOUNDARY_NEUTRAL, Character
- .getDirectionality(0xE007F));
-
- assertEquals(Character.DIRECTIONALITY_PARAGRAPH_SEPARATOR, Character
- .getDirectionality(0x000A));
- assertEquals(Character.DIRECTIONALITY_PARAGRAPH_SEPARATOR, Character
- .getDirectionality(0x2029));
-
- assertEquals(Character.DIRECTIONALITY_SEGMENT_SEPARATOR, Character
- .getDirectionality(0x0009));
- assertEquals(Character.DIRECTIONALITY_SEGMENT_SEPARATOR, Character
- .getDirectionality(0x001F));
-
- assertEquals(Character.DIRECTIONALITY_WHITESPACE, Character
- .getDirectionality(0x0020));
- assertEquals(Character.DIRECTIONALITY_WHITESPACE, Character
- .getDirectionality(0x3000));
-
- assertEquals(Character.DIRECTIONALITY_OTHER_NEUTRALS, Character
- .getDirectionality(0x2FF0));
- assertEquals(Character.DIRECTIONALITY_OTHER_NEUTRALS, Character
- .getDirectionality(0x1D356));
-
- assertEquals(Character.DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING, Character
- .getDirectionality(0x202A));
-
- assertEquals(Character.DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE, Character
- .getDirectionality(0x202D));
-
- assertEquals(Character.DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING, Character
- .getDirectionality(0x202B));
-
- assertEquals(Character.DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE, Character
- .getDirectionality(0x202E));
-
- assertEquals(Character.DIRECTIONALITY_POP_DIRECTIONAL_FORMAT, Character
- .getDirectionality(0x202C));
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/Character_SubsetTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/Character_SubsetTest.java
deleted file mode 100644
index f99fb86..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/Character_SubsetTest.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(Character.Subset.class)
-public class Character_SubsetTest extends TestCase {
-
- /**
- * @tests java.lang.Character.Subset#Character.Subset(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Subset",
- args = {java.lang.String.class}
- )
- public void test_Ctor() {
-
- try {
- // Regression for HARMONY-888
- new Character.Subset(null) {
- };
- fail("No expected NullPointerException");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @tests java.lang.Character.Subset#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
-
- String name = "name";
- Character.Subset subset = new Character.Subset(name) {
- };
- assertSame(name, subset.toString());
- }
-
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equals() {
- Character.Subset subset1 = new Character.Subset("name") { };
- assertTrue(subset1.equals(subset1));
- assertFalse(subset1.equals(new Character.Subset("name") {}));
- assertFalse(subset1.equals(new Character.Subset("name1") {}));
- assertFalse(subset1.equals(new Integer(0)));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- Character.Subset subset1 = new Character.Subset("name") {};
- Character.Subset subset2 = new Character.Subset("name") {};
- Character.Subset subset3 = new Character.Subset("name1") {};
- assertFalse(subset1.hashCode() == subset2.hashCode());
- assertFalse(subset1.hashCode() == subset3.hashCode());
- }
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(Character_SubsetTest.class);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/Character_UnicodeBlockTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/Character_UnicodeBlockTest.java
deleted file mode 100644
index 0766f28..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/Character_UnicodeBlockTest.java
+++ /dev/null
@@ -1,913 +0,0 @@
-/* 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(Character.UnicodeBlock.class)
-public class Character_UnicodeBlockTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "of",
- args = {char.class}
- )
- public void test_ofC() {
- assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.of((char)0x0));
- assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.of((char)0x7f));
- assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.of((char)0x80));
- assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.of((char)0xff));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.of((char)0x100));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.of((char)0x17f));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.of((char)0x180));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.of((char)0x24f));
- assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.of((char)0x250));
- assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.of((char)0x2af));
- assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.of((char)0x2b0));
- assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.of((char)0x2ff));
- assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.of((char)0x300));
- assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.of((char)0x36f));
- assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.of((char)0x370));
- assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.of((char)0x3ff));
- assertEquals(Character.UnicodeBlock.CYRILLIC, Character.UnicodeBlock.of((char)0x400));
- assertEquals(Character.UnicodeBlock.CYRILLIC, Character.UnicodeBlock.of((char)0x4ff));
- assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.of((char)0x500));
- assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.of((char)0x52f));
- assertEquals(Character.UnicodeBlock.ARMENIAN, Character.UnicodeBlock.of((char)0x530));
- assertEquals(Character.UnicodeBlock.ARMENIAN, Character.UnicodeBlock.of((char)0x58f));
- assertEquals(Character.UnicodeBlock.HEBREW, Character.UnicodeBlock.of((char)0x590));
- assertEquals(Character.UnicodeBlock.HEBREW, Character.UnicodeBlock.of((char)0x5ff));
- assertEquals(Character.UnicodeBlock.ARABIC, Character.UnicodeBlock.of((char)0x600));
- assertEquals(Character.UnicodeBlock.ARABIC, Character.UnicodeBlock.of((char)0x6ff));
- assertEquals(Character.UnicodeBlock.SYRIAC, Character.UnicodeBlock.of((char)0x700));
- assertEquals(Character.UnicodeBlock.SYRIAC, Character.UnicodeBlock.of((char)0x74f));
- assertNull(Character.UnicodeBlock.of((char)0x750));
- assertNull(Character.UnicodeBlock.of((char)0x77f));
- assertEquals(Character.UnicodeBlock.THAANA, Character.UnicodeBlock.of((char)0x780));
- assertEquals(Character.UnicodeBlock.THAANA, Character.UnicodeBlock.of((char)0x7bf));
- assertNull(Character.UnicodeBlock.of((char)0x7c0));
- assertNull(Character.UnicodeBlock.of((char)0x8ff));
- assertEquals(Character.UnicodeBlock.DEVANAGARI, Character.UnicodeBlock.of((char)0x900));
- assertEquals(Character.UnicodeBlock.DEVANAGARI, Character.UnicodeBlock.of((char)0x97f));
- assertEquals(Character.UnicodeBlock.BENGALI, Character.UnicodeBlock.of((char)0x980));
- assertEquals(Character.UnicodeBlock.BENGALI, Character.UnicodeBlock.of((char)0x9ff));
- assertEquals(Character.UnicodeBlock.GURMUKHI, Character.UnicodeBlock.of((char)0xa00));
- assertEquals(Character.UnicodeBlock.GURMUKHI, Character.UnicodeBlock.of((char)0xa7f));
- assertEquals(Character.UnicodeBlock.GUJARATI, Character.UnicodeBlock.of((char)0xa80));
- assertEquals(Character.UnicodeBlock.GUJARATI, Character.UnicodeBlock.of((char)0xaff));
- assertEquals(Character.UnicodeBlock.ORIYA, Character.UnicodeBlock.of((char)0xb00));
- assertEquals(Character.UnicodeBlock.ORIYA, Character.UnicodeBlock.of((char)0xb7f));
- assertEquals(Character.UnicodeBlock.TAMIL, Character.UnicodeBlock.of((char)0xb80));
- assertEquals(Character.UnicodeBlock.TAMIL, Character.UnicodeBlock.of((char)0xbff));
- assertEquals(Character.UnicodeBlock.TELUGU, Character.UnicodeBlock.of((char)0xc00));
- assertEquals(Character.UnicodeBlock.TELUGU, Character.UnicodeBlock.of((char)0xc7f));
- assertEquals(Character.UnicodeBlock.KANNADA, Character.UnicodeBlock.of((char)0xc80));
- assertEquals(Character.UnicodeBlock.KANNADA, Character.UnicodeBlock.of((char)0xcff));
- assertEquals(Character.UnicodeBlock.MALAYALAM, Character.UnicodeBlock.of((char)0xd00));
- assertEquals(Character.UnicodeBlock.MALAYALAM, Character.UnicodeBlock.of((char)0xd7f));
- assertEquals(Character.UnicodeBlock.SINHALA, Character.UnicodeBlock.of((char)0xd80));
- assertEquals(Character.UnicodeBlock.SINHALA, Character.UnicodeBlock.of((char)0xdff));
- assertEquals(Character.UnicodeBlock.THAI, Character.UnicodeBlock.of((char)0xe00));
- assertEquals(Character.UnicodeBlock.THAI, Character.UnicodeBlock.of((char)0xe7f));
- assertEquals(Character.UnicodeBlock.LAO, Character.UnicodeBlock.of((char)0xe80));
- assertEquals(Character.UnicodeBlock.LAO, Character.UnicodeBlock.of((char)0xeff));
- assertEquals(Character.UnicodeBlock.TIBETAN, Character.UnicodeBlock.of((char)0xf00));
- assertEquals(Character.UnicodeBlock.TIBETAN, Character.UnicodeBlock.of((char)0xfff));
- assertEquals(Character.UnicodeBlock.MYANMAR, Character.UnicodeBlock.of((char)0x1000));
- assertEquals(Character.UnicodeBlock.MYANMAR, Character.UnicodeBlock.of((char)0x109f));
- assertEquals(Character.UnicodeBlock.GEORGIAN, Character.UnicodeBlock.of((char)0x10a0));
- assertEquals(Character.UnicodeBlock.GEORGIAN, Character.UnicodeBlock.of((char)0x10ff));
- assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.of((char)0x1100));
- assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.of((char)0x11ff));
- assertEquals(Character.UnicodeBlock.ETHIOPIC, Character.UnicodeBlock.of((char)0x1200));
- assertEquals(Character.UnicodeBlock.ETHIOPIC, Character.UnicodeBlock.of((char)0x137f));
- assertNull(Character.UnicodeBlock.of((char)0x1380));
- assertNull(Character.UnicodeBlock.of((char)0x139f));
- assertEquals(Character.UnicodeBlock.CHEROKEE, Character.UnicodeBlock.of((char)0x13a0));
- assertEquals(Character.UnicodeBlock.CHEROKEE, Character.UnicodeBlock.of((char)0x13ff));
- assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.of((char)0x1400));
- assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.of((char)0x167f));
- assertEquals(Character.UnicodeBlock.OGHAM, Character.UnicodeBlock.of((char)0x1680));
- assertEquals(Character.UnicodeBlock.OGHAM, Character.UnicodeBlock.of((char)0x169f));
- assertEquals(Character.UnicodeBlock.RUNIC, Character.UnicodeBlock.of((char)0x16a0));
- assertEquals(Character.UnicodeBlock.RUNIC, Character.UnicodeBlock.of((char)0x16ff));
- assertEquals(Character.UnicodeBlock.TAGALOG, Character.UnicodeBlock.of((char)0x1700));
- assertEquals(Character.UnicodeBlock.TAGALOG, Character.UnicodeBlock.of((char)0x171f));
- assertEquals(Character.UnicodeBlock.HANUNOO, Character.UnicodeBlock.of((char)0x1720));
- assertEquals(Character.UnicodeBlock.HANUNOO, Character.UnicodeBlock.of((char)0x173f));
- assertEquals(Character.UnicodeBlock.BUHID, Character.UnicodeBlock.of((char)0x1740));
- assertEquals(Character.UnicodeBlock.BUHID, Character.UnicodeBlock.of((char)0x175f));
- assertEquals(Character.UnicodeBlock.TAGBANWA, Character.UnicodeBlock.of((char)0x1760));
- assertEquals(Character.UnicodeBlock.TAGBANWA, Character.UnicodeBlock.of((char)0x177f));
- assertEquals(Character.UnicodeBlock.KHMER, Character.UnicodeBlock.of((char)0x1780));
- assertEquals(Character.UnicodeBlock.KHMER, Character.UnicodeBlock.of((char)0x17ff));
- assertEquals(Character.UnicodeBlock.MONGOLIAN, Character.UnicodeBlock.of((char)0x1800));
- assertEquals(Character.UnicodeBlock.MONGOLIAN, Character.UnicodeBlock.of((char)0x18af));
- assertNull(Character.UnicodeBlock.of((char)0x18b0));
- assertNull(Character.UnicodeBlock.of((char)0x18ff));
- assertEquals(Character.UnicodeBlock.LIMBU, Character.UnicodeBlock.of((char)0x1900));
- assertEquals(Character.UnicodeBlock.LIMBU, Character.UnicodeBlock.of((char)0x194f));
- assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.of((char)0x1950));
- assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.of((char)0x197f));
- assertNull(Character.UnicodeBlock.of((char)0x1980));
- assertNull(Character.UnicodeBlock.of((char)0x19df));
- assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.of((char)0x19e0));
- assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.of((char)0x19ff));
- assertNull(Character.UnicodeBlock.of((char)0x1a00));
- assertNull(Character.UnicodeBlock.of((char)0x1cff));
- assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.of((char)0x1d00));
- assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.of((char)0x1d7f));
- assertNull(Character.UnicodeBlock.of((char)0x1d80));
- assertNull(Character.UnicodeBlock.of((char)0x1dff));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.of((char)0x1e00));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.of((char)0x1eff));
- assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.of((char)0x1f00));
- assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.of((char)0x1fff));
- assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.of((char)0x2000));
- assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.of((char)0x206f));
- assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.of((char)0x2070));
- assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.of((char)0x209f));
- assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.of((char)0x20a0));
- assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.of((char)0x20cf));
- assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.of((char)0x20d0));
- assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.of((char)0x20ff));
- assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.of((char)0x2100));
- assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.of((char)0x214f));
- assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.of((char)0x2150));
- assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.of((char)0x218f));
- assertEquals(Character.UnicodeBlock.ARROWS, Character.UnicodeBlock.of((char)0x2190));
- assertEquals(Character.UnicodeBlock.ARROWS, Character.UnicodeBlock.of((char)0x21ff));
- assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of((char)0x2200));
- assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of((char)0x22ff));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.of((char)0x2300));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.of((char)0x23ff));
- assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.of((char)0x2400));
- assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.of((char)0x243f));
- assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.of((char)0x2440));
- assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.of((char)0x245f));
- assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.of((char)0x2460));
- assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.of((char)0x24ff));
- assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.of((char)0x2500));
- assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.of((char)0x257f));
- assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.of((char)0x2580));
- assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.of((char)0x259f));
- assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.of((char)0x25a0));
- assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.of((char)0x25ff));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.of((char)0x2600));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.of((char)0x26ff));
- assertEquals(Character.UnicodeBlock.DINGBATS, Character.UnicodeBlock.of((char)0x2700));
- assertEquals(Character.UnicodeBlock.DINGBATS, Character.UnicodeBlock.of((char)0x27bf));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.of((char)0x27c0));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.of((char)0x27ef));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.of((char)0x27f0));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.of((char)0x27ff));
- assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.of((char)0x2800));
- assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.of((char)0x28ff));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.of((char)0x2900));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.of((char)0x297f));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.of((char)0x2980));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.of((char)0x29ff));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of((char)0x2a00));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of((char)0x2aff));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.of((char)0x2b00));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.of((char)0x2bff));
- assertNull(Character.UnicodeBlock.of((char)0x2c00));
- assertNull(Character.UnicodeBlock.of((char)0x2e7f));
- assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.of((char)0x2e80));
- assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.of((char)0x2eff));
- assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.of((char)0x2f00));
- assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.of((char)0x2fdf));
- assertNull(Character.UnicodeBlock.of((char)0x2fe0));
- assertNull(Character.UnicodeBlock.of((char)0x2fef));
- assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.of((char)0x2ff0));
- assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.of((char)0x2fff));
- assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.of((char)0x3000));
- assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.of((char)0x303f));
- assertEquals(Character.UnicodeBlock.HIRAGANA, Character.UnicodeBlock.of((char)0x3040));
- assertEquals(Character.UnicodeBlock.HIRAGANA, Character.UnicodeBlock.of((char)0x309f));
- assertEquals(Character.UnicodeBlock.KATAKANA, Character.UnicodeBlock.of((char)0x30a0));
- assertEquals(Character.UnicodeBlock.KATAKANA, Character.UnicodeBlock.of((char)0x30ff));
- assertEquals(Character.UnicodeBlock.BOPOMOFO, Character.UnicodeBlock.of((char)0x3100));
- assertEquals(Character.UnicodeBlock.BOPOMOFO, Character.UnicodeBlock.of((char)0x312f));
- assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.of((char)0x3130));
- assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.of((char)0x318f));
- assertEquals(Character.UnicodeBlock.KANBUN, Character.UnicodeBlock.of((char)0x3190));
- assertEquals(Character.UnicodeBlock.KANBUN, Character.UnicodeBlock.of((char)0x319f));
- assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.of((char)0x31a0));
- assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.of((char)0x31bf));
- assertNull(Character.UnicodeBlock.of((char)0x31c0));
- assertNull(Character.UnicodeBlock.of((char)0x31ef));
- assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.of((char)0x31f0));
- assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.of((char)0x31ff));
- assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.of((char)0x3200));
- assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.of((char)0x32ff));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.of((char)0x3300));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.of((char)0x33ff));
- assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.of((char)0x3400));
- assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.of((char)0x4dbf));
- assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.of((char)0x4dc0));
- assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.of((char)0x4dff));
- assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.of((char)0x4e00));
- assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.of((char)0x9fff));
- assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.of((char)0xa000));
- assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.of((char)0xa48f));
- assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.of((char)0xa490));
- assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.of((char)0xa4cf));
- assertNull(Character.UnicodeBlock.of((char)0xa4d0));
- assertNull(Character.UnicodeBlock.of((char)0xabff));
- assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.of((char)0xac00));
- assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.of((char)0xd7af));
- assertNull(Character.UnicodeBlock.of((char)0xd7b0));
- assertNull(Character.UnicodeBlock.of((char)0xd7ff));
- assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.of((char)0xd800));
- assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.of((char)0xdb7f));
- assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.of((char)0xdb80));
- assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.of((char)0xdbff));
- assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.of((char)0xdc00));
- assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.of((char)0xdfff));
- assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.of((char)0xe000));
- assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.of((char)0xf8ff));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.of((char)0xf900));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.of((char)0xfaff));
- assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.of((char)0xfb00));
- assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.of((char)0xfb4f));
- assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.of((char)0xfb50));
- assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.of((char)0xfdff));
- assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.of((char)0xfe00));
- assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.of((char)0xfe0f));
- assertNull(Character.UnicodeBlock.of((char)0xfe10));
- assertNull(Character.UnicodeBlock.of((char)0xfe1f));
- assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.of((char)0xfe20));
- assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.of((char)0xfe2f));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.of((char)0xfe30));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.of((char)0xfe4f));
- assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.of((char)0xfe50));
- assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.of((char)0xfe6f));
- assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.of((char)0xfe70));
- assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.of((char)0xfeff));
- assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.of((char)0xff00));
- assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.of((char)0xffef));
- assertEquals(Character.UnicodeBlock.SPECIALS, Character.UnicodeBlock.of((char)0xfff0));
- assertEquals(Character.UnicodeBlock.SPECIALS, Character.UnicodeBlock.of((char)0xffff));
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't check exception.",
- method = "of",
- args = {int.class}
- )
- public void test_ofI() {
- assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.of(0x0));
- assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.of(0x7f));
- assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.of(0x80));
- assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.of(0xff));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.of(0x100));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.of(0x17f));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.of(0x180));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.of(0x24f));
- assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.of(0x250));
- assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.of(0x2af));
- assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.of(0x2b0));
- assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.of(0x2ff));
- assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.of(0x300));
- assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.of(0x36f));
- assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.of(0x370));
- assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.of(0x3ff));
- assertEquals(Character.UnicodeBlock.CYRILLIC, Character.UnicodeBlock.of(0x400));
- assertEquals(Character.UnicodeBlock.CYRILLIC, Character.UnicodeBlock.of(0x4ff));
- assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.of(0x500));
- assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.of(0x52f));
- assertEquals(Character.UnicodeBlock.ARMENIAN, Character.UnicodeBlock.of(0x530));
- assertEquals(Character.UnicodeBlock.ARMENIAN, Character.UnicodeBlock.of(0x58f));
- assertEquals(Character.UnicodeBlock.HEBREW, Character.UnicodeBlock.of(0x590));
- assertEquals(Character.UnicodeBlock.HEBREW, Character.UnicodeBlock.of(0x5ff));
- assertEquals(Character.UnicodeBlock.ARABIC, Character.UnicodeBlock.of(0x600));
- assertEquals(Character.UnicodeBlock.ARABIC, Character.UnicodeBlock.of(0x6ff));
- assertEquals(Character.UnicodeBlock.SYRIAC, Character.UnicodeBlock.of(0x700));
- assertEquals(Character.UnicodeBlock.SYRIAC, Character.UnicodeBlock.of(0x74f));
- assertNull(Character.UnicodeBlock.of(0x750));
- assertNull(Character.UnicodeBlock.of(0x77f));
- assertEquals(Character.UnicodeBlock.THAANA, Character.UnicodeBlock.of(0x780));
- assertEquals(Character.UnicodeBlock.THAANA, Character.UnicodeBlock.of(0x7bf));
- assertNull(Character.UnicodeBlock.of(0x7c0));
- assertNull(Character.UnicodeBlock.of(0x8ff));
- assertEquals(Character.UnicodeBlock.DEVANAGARI, Character.UnicodeBlock.of(0x900));
- assertEquals(Character.UnicodeBlock.DEVANAGARI, Character.UnicodeBlock.of(0x97f));
- assertEquals(Character.UnicodeBlock.BENGALI, Character.UnicodeBlock.of(0x980));
- assertEquals(Character.UnicodeBlock.BENGALI, Character.UnicodeBlock.of(0x9ff));
- assertEquals(Character.UnicodeBlock.GURMUKHI, Character.UnicodeBlock.of(0xa00));
- assertEquals(Character.UnicodeBlock.GURMUKHI, Character.UnicodeBlock.of(0xa7f));
- assertEquals(Character.UnicodeBlock.GUJARATI, Character.UnicodeBlock.of(0xa80));
- assertEquals(Character.UnicodeBlock.GUJARATI, Character.UnicodeBlock.of(0xaff));
- assertEquals(Character.UnicodeBlock.ORIYA, Character.UnicodeBlock.of(0xb00));
- assertEquals(Character.UnicodeBlock.ORIYA, Character.UnicodeBlock.of(0xb7f));
- assertEquals(Character.UnicodeBlock.TAMIL, Character.UnicodeBlock.of(0xb80));
- assertEquals(Character.UnicodeBlock.TAMIL, Character.UnicodeBlock.of(0xbff));
- assertEquals(Character.UnicodeBlock.TELUGU, Character.UnicodeBlock.of(0xc00));
- assertEquals(Character.UnicodeBlock.TELUGU, Character.UnicodeBlock.of(0xc7f));
- assertEquals(Character.UnicodeBlock.KANNADA, Character.UnicodeBlock.of(0xc80));
- assertEquals(Character.UnicodeBlock.KANNADA, Character.UnicodeBlock.of(0xcff));
- assertEquals(Character.UnicodeBlock.MALAYALAM, Character.UnicodeBlock.of(0xd00));
- assertEquals(Character.UnicodeBlock.MALAYALAM, Character.UnicodeBlock.of(0xd7f));
- assertEquals(Character.UnicodeBlock.SINHALA, Character.UnicodeBlock.of(0xd80));
- assertEquals(Character.UnicodeBlock.SINHALA, Character.UnicodeBlock.of(0xdff));
- assertEquals(Character.UnicodeBlock.THAI, Character.UnicodeBlock.of(0xe00));
- assertEquals(Character.UnicodeBlock.THAI, Character.UnicodeBlock.of(0xe7f));
- assertEquals(Character.UnicodeBlock.LAO, Character.UnicodeBlock.of(0xe80));
- assertEquals(Character.UnicodeBlock.LAO, Character.UnicodeBlock.of(0xeff));
- assertEquals(Character.UnicodeBlock.TIBETAN, Character.UnicodeBlock.of(0xf00));
- assertEquals(Character.UnicodeBlock.TIBETAN, Character.UnicodeBlock.of(0xfff));
- assertEquals(Character.UnicodeBlock.MYANMAR, Character.UnicodeBlock.of(0x1000));
- assertEquals(Character.UnicodeBlock.MYANMAR, Character.UnicodeBlock.of(0x109f));
- assertEquals(Character.UnicodeBlock.GEORGIAN, Character.UnicodeBlock.of(0x10a0));
- assertEquals(Character.UnicodeBlock.GEORGIAN, Character.UnicodeBlock.of(0x10ff));
- assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.of(0x1100));
- assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.of(0x11ff));
- assertEquals(Character.UnicodeBlock.ETHIOPIC, Character.UnicodeBlock.of(0x1200));
- assertEquals(Character.UnicodeBlock.ETHIOPIC, Character.UnicodeBlock.of(0x137f));
- assertNull(Character.UnicodeBlock.of(0x1380));
- assertNull(Character.UnicodeBlock.of(0x139f));
- assertEquals(Character.UnicodeBlock.CHEROKEE, Character.UnicodeBlock.of(0x13a0));
- assertEquals(Character.UnicodeBlock.CHEROKEE, Character.UnicodeBlock.of(0x13ff));
- assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.of(0x1400));
- assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.of(0x167f));
- assertEquals(Character.UnicodeBlock.OGHAM, Character.UnicodeBlock.of(0x1680));
- assertEquals(Character.UnicodeBlock.OGHAM, Character.UnicodeBlock.of(0x169f));
- assertEquals(Character.UnicodeBlock.RUNIC, Character.UnicodeBlock.of(0x16a0));
- assertEquals(Character.UnicodeBlock.RUNIC, Character.UnicodeBlock.of(0x16ff));
- assertEquals(Character.UnicodeBlock.TAGALOG, Character.UnicodeBlock.of(0x1700));
- assertEquals(Character.UnicodeBlock.TAGALOG, Character.UnicodeBlock.of(0x171f));
- assertEquals(Character.UnicodeBlock.HANUNOO, Character.UnicodeBlock.of(0x1720));
- assertEquals(Character.UnicodeBlock.HANUNOO, Character.UnicodeBlock.of(0x173f));
- assertEquals(Character.UnicodeBlock.BUHID, Character.UnicodeBlock.of(0x1740));
- assertEquals(Character.UnicodeBlock.BUHID, Character.UnicodeBlock.of(0x175f));
- assertEquals(Character.UnicodeBlock.TAGBANWA, Character.UnicodeBlock.of(0x1760));
- assertEquals(Character.UnicodeBlock.TAGBANWA, Character.UnicodeBlock.of(0x177f));
- assertEquals(Character.UnicodeBlock.KHMER, Character.UnicodeBlock.of(0x1780));
- assertEquals(Character.UnicodeBlock.KHMER, Character.UnicodeBlock.of(0x17ff));
- assertEquals(Character.UnicodeBlock.MONGOLIAN, Character.UnicodeBlock.of(0x1800));
- assertEquals(Character.UnicodeBlock.MONGOLIAN, Character.UnicodeBlock.of(0x18af));
- assertNull(Character.UnicodeBlock.of(0x18b0));
- assertNull(Character.UnicodeBlock.of(0x18ff));
- assertEquals(Character.UnicodeBlock.LIMBU, Character.UnicodeBlock.of(0x1900));
- assertEquals(Character.UnicodeBlock.LIMBU, Character.UnicodeBlock.of(0x194f));
- assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.of(0x1950));
- assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.of(0x197f));
- assertNull(Character.UnicodeBlock.of(0x1980));
- assertNull(Character.UnicodeBlock.of(0x19df));
- assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.of(0x19e0));
- assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.of(0x19ff));
- assertNull(Character.UnicodeBlock.of(0x1a00));
- assertNull(Character.UnicodeBlock.of(0x1cff));
- assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.of(0x1d00));
- assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.of(0x1d7f));
- assertNull(Character.UnicodeBlock.of(0x1d80));
- assertNull(Character.UnicodeBlock.of(0x1dff));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.of(0x1e00));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.of(0x1eff));
- assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.of(0x1f00));
- assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.of(0x1fff));
- assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.of(0x2000));
- assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.of(0x206f));
- assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.of(0x2070));
- assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.of(0x209f));
- assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.of(0x20a0));
- assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.of(0x20cf));
- assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.of(0x20d0));
- assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.of(0x20ff));
- assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.of(0x2100));
- assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.of(0x214f));
- assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.of(0x2150));
- assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.of(0x218f));
- assertEquals(Character.UnicodeBlock.ARROWS, Character.UnicodeBlock.of(0x2190));
- assertEquals(Character.UnicodeBlock.ARROWS, Character.UnicodeBlock.of(0x21ff));
- assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of(0x2200));
- assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of(0x22ff));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.of(0x2300));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.of(0x23ff));
- assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.of(0x2400));
- assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.of(0x243f));
- assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.of(0x2440));
- assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.of(0x245f));
- assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.of(0x2460));
- assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.of(0x24ff));
- assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.of(0x2500));
- assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.of(0x257f));
- assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.of(0x2580));
- assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.of(0x259f));
- assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.of(0x25a0));
- assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.of(0x25ff));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.of(0x2600));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.of(0x26ff));
- assertEquals(Character.UnicodeBlock.DINGBATS, Character.UnicodeBlock.of(0x2700));
- assertEquals(Character.UnicodeBlock.DINGBATS, Character.UnicodeBlock.of(0x27bf));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.of(0x27c0));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.of(0x27ef));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.of(0x27f0));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.of(0x27ff));
- assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.of(0x2800));
- assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.of(0x28ff));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.of(0x2900));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.of(0x297f));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.of(0x2980));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.of(0x29ff));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of(0x2a00));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.of(0x2aff));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.of(0x2b00));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.of(0x2bff));
- assertNull(Character.UnicodeBlock.of(0x2c00));
- assertNull(Character.UnicodeBlock.of(0x2e7f));
- assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.of(0x2e80));
- assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.of(0x2eff));
- assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.of(0x2f00));
- assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.of(0x2fdf));
- assertNull(Character.UnicodeBlock.of(0x2fe0));
- assertNull(Character.UnicodeBlock.of(0x2fef));
- assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.of(0x2ff0));
- assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.of(0x2fff));
- assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.of(0x3000));
- assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.of(0x303f));
- assertEquals(Character.UnicodeBlock.HIRAGANA, Character.UnicodeBlock.of(0x3040));
- assertEquals(Character.UnicodeBlock.HIRAGANA, Character.UnicodeBlock.of(0x309f));
- assertEquals(Character.UnicodeBlock.KATAKANA, Character.UnicodeBlock.of(0x30a0));
- assertEquals(Character.UnicodeBlock.KATAKANA, Character.UnicodeBlock.of(0x30ff));
- assertEquals(Character.UnicodeBlock.BOPOMOFO, Character.UnicodeBlock.of(0x3100));
- assertEquals(Character.UnicodeBlock.BOPOMOFO, Character.UnicodeBlock.of(0x312f));
- assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.of(0x3130));
- assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.of(0x318f));
- assertEquals(Character.UnicodeBlock.KANBUN, Character.UnicodeBlock.of(0x3190));
- assertEquals(Character.UnicodeBlock.KANBUN, Character.UnicodeBlock.of(0x319f));
- assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.of(0x31a0));
- assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.of(0x31bf));
- assertNull(Character.UnicodeBlock.of(0x31c0));
- assertNull(Character.UnicodeBlock.of(0x31ef));
- assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.of(0x31f0));
- assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.of(0x31ff));
- assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.of(0x3200));
- assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.of(0x32ff));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.of(0x3300));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.of(0x33ff));
- assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.of(0x3400));
- assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.of(0x4dbf));
- assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.of(0x4dc0));
- assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.of(0x4dff));
- assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.of(0x4e00));
- assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.of(0x9fff));
- assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.of(0xa000));
- assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.of(0xa48f));
- assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.of(0xa490));
- assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.of(0xa4cf));
- assertNull(Character.UnicodeBlock.of(0xa4d0));
- assertNull(Character.UnicodeBlock.of(0xabff));
- assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.of(0xac00));
- assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.of(0xd7af));
- assertNull(Character.UnicodeBlock.of(0xd7b0));
- assertNull(Character.UnicodeBlock.of(0xd7ff));
- assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.of(0xd800));
- assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.of(0xdb7f));
- assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.of(0xdb80));
- assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.of(0xdbff));
- assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.of(0xdc00));
- assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.of(0xdfff));
- assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.of(0xe000));
- assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.of(0xf8ff));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.of(0xf900));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.of(0xfaff));
- assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.of(0xfb00));
- assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.of(0xfb4f));
- assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.of(0xfb50));
- assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.of(0xfdff));
- assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.of(0xfe00));
- assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.of(0xfe0f));
- assertNull(Character.UnicodeBlock.of(0xfe10));
- assertNull(Character.UnicodeBlock.of(0xfe1f));
- assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.of(0xfe20));
- assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.of(0xfe2f));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.of(0xfe30));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.of(0xfe4f));
- assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.of(0xfe50));
- assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.of(0xfe6f));
- assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.of(0xfe70));
- assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.of(0xfeff));
- assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.of(0xff00));
- assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.of(0xffef));
- assertEquals(Character.UnicodeBlock.SPECIALS, Character.UnicodeBlock.of(0xfff0));
- assertEquals(Character.UnicodeBlock.SPECIALS, Character.UnicodeBlock.of(0xffff));
- assertEquals(Character.UnicodeBlock.LINEAR_B_SYLLABARY, Character.UnicodeBlock.of(0x10000));
- assertEquals(Character.UnicodeBlock.LINEAR_B_SYLLABARY, Character.UnicodeBlock.of(0x1007f));
- assertEquals(Character.UnicodeBlock.LINEAR_B_IDEOGRAMS, Character.UnicodeBlock.of(0x10080));
- assertEquals(Character.UnicodeBlock.LINEAR_B_IDEOGRAMS, Character.UnicodeBlock.of(0x100ff));
- assertEquals(Character.UnicodeBlock.AEGEAN_NUMBERS, Character.UnicodeBlock.of(0x10100));
- assertEquals(Character.UnicodeBlock.AEGEAN_NUMBERS, Character.UnicodeBlock.of(0x1013f));
- assertNull(Character.UnicodeBlock.of(0x10140));
- assertNull(Character.UnicodeBlock.of(0x102ff));
- assertEquals(Character.UnicodeBlock.OLD_ITALIC, Character.UnicodeBlock.of(0x10300));
- assertEquals(Character.UnicodeBlock.OLD_ITALIC, Character.UnicodeBlock.of(0x1032f));
- assertEquals(Character.UnicodeBlock.GOTHIC, Character.UnicodeBlock.of(0x10330));
- assertEquals(Character.UnicodeBlock.GOTHIC, Character.UnicodeBlock.of(0x1034f));
- assertNull(Character.UnicodeBlock.of(0x10350));
- assertNull(Character.UnicodeBlock.of(0x1037f));
- assertEquals(Character.UnicodeBlock.UGARITIC, Character.UnicodeBlock.of(0x10380));
- assertEquals(Character.UnicodeBlock.UGARITIC, Character.UnicodeBlock.of(0x1039f));
- assertNull(Character.UnicodeBlock.of(0x103a0));
- assertNull(Character.UnicodeBlock.of(0x103ff));
- assertEquals(Character.UnicodeBlock.DESERET, Character.UnicodeBlock.of(0x10400));
- assertEquals(Character.UnicodeBlock.DESERET, Character.UnicodeBlock.of(0x1044f));
- assertEquals(Character.UnicodeBlock.SHAVIAN, Character.UnicodeBlock.of(0x10450));
- assertEquals(Character.UnicodeBlock.SHAVIAN, Character.UnicodeBlock.of(0x1047f));
- assertEquals(Character.UnicodeBlock.OSMANYA, Character.UnicodeBlock.of(0x10480));
- assertEquals(Character.UnicodeBlock.OSMANYA, Character.UnicodeBlock.of(0x104af));
- assertNull(Character.UnicodeBlock.of(0x104b0));
- assertNull(Character.UnicodeBlock.of(0x107ff));
- assertEquals(Character.UnicodeBlock.CYPRIOT_SYLLABARY, Character.UnicodeBlock.of(0x10800));
- assertEquals(Character.UnicodeBlock.CYPRIOT_SYLLABARY, Character.UnicodeBlock.of(0x1083f));
- assertNull(Character.UnicodeBlock.of(0x10840));
- assertNull(Character.UnicodeBlock.of(0x1cfff));
- assertEquals(Character.UnicodeBlock.BYZANTINE_MUSICAL_SYMBOLS, Character.UnicodeBlock.of(0x1d000));
- assertEquals(Character.UnicodeBlock.BYZANTINE_MUSICAL_SYMBOLS, Character.UnicodeBlock.of(0x1d0ff));
- assertEquals(Character.UnicodeBlock.MUSICAL_SYMBOLS, Character.UnicodeBlock.of(0x1d100));
- assertEquals(Character.UnicodeBlock.MUSICAL_SYMBOLS, Character.UnicodeBlock.of(0x1d1ff));
- assertNull(Character.UnicodeBlock.of(0x1d200));
- assertNull(Character.UnicodeBlock.of(0x1d2ff));
- assertEquals(Character.UnicodeBlock.TAI_XUAN_JING_SYMBOLS, Character.UnicodeBlock.of(0x1d300));
- assertEquals(Character.UnicodeBlock.TAI_XUAN_JING_SYMBOLS, Character.UnicodeBlock.of(0x1d35f));
- assertNull(Character.UnicodeBlock.of(0x1d360));
- assertNull(Character.UnicodeBlock.of(0x1d3ff));
- assertEquals(Character.UnicodeBlock.MATHEMATICAL_ALPHANUMERIC_SYMBOLS, Character.UnicodeBlock.of(0x1d400));
- assertEquals(Character.UnicodeBlock.MATHEMATICAL_ALPHANUMERIC_SYMBOLS, Character.UnicodeBlock.of(0x1d7ff));
- assertNull(Character.UnicodeBlock.of(0x1d800));
- assertNull(Character.UnicodeBlock.of(0x1ffff));
- assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B, Character.UnicodeBlock.of(0x20000));
- assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B, Character.UnicodeBlock.of(0x2a6df));
- assertNull(Character.UnicodeBlock.of(0x2a6e0));
- assertNull(Character.UnicodeBlock.of(0x2f7ff));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT, Character.UnicodeBlock.of(0x2f800));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT, Character.UnicodeBlock.of(0x2fa1f));
- assertNull(Character.UnicodeBlock.of(0x2fa20));
- assertNull(Character.UnicodeBlock.of(0xdffff));
- assertEquals(Character.UnicodeBlock.TAGS, Character.UnicodeBlock.of(0xe0000));
- assertEquals(Character.UnicodeBlock.TAGS, Character.UnicodeBlock.of(0xe007f));
- assertNull(Character.UnicodeBlock.of(0xe0080));
- assertNull(Character.UnicodeBlock.of(0xe00ff));
- assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS_SUPPLEMENT, Character.UnicodeBlock.of(0xe0100));
- assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS_SUPPLEMENT, Character.UnicodeBlock.of(0xe01ef));
- assertNull(Character.UnicodeBlock.of(0xe01f0));
- assertNull(Character.UnicodeBlock.of(0xeffff));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_A, Character.UnicodeBlock.of(0xf0000));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_A, Character.UnicodeBlock.of(0xfffff));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_B, Character.UnicodeBlock.of(0x100000));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_B, Character.UnicodeBlock.of(0x10ffff));
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks IllegalArgumentException.",
- method = "of",
- args = {int.class}
- )
- public void test_ofIExceptions() {
- try {
- Character.UnicodeBlock.of(Character.MAX_CODE_POINT + 1);
- fail("No illegal argument exception");
- } catch(IllegalArgumentException e) {
- }
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't check null.",
- method = "forName",
- args = {java.lang.String.class}
- )
- @SuppressWarnings("deprecation")
- public void test_forNameLjava_lang_String() {
- assertEquals(Character.UnicodeBlock.SURROGATES_AREA, Character.UnicodeBlock.forName("SURROGATES_AREA"));
- assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.forName("BASIC_LATIN"));
- assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.forName("Basic Latin"));
- assertEquals(Character.UnicodeBlock.BASIC_LATIN, Character.UnicodeBlock.forName("BasicLatin"));
- assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.forName("LATIN_1_SUPPLEMENT"));
- assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.forName("Latin-1 Supplement"));
- assertEquals(Character.UnicodeBlock.LATIN_1_SUPPLEMENT, Character.UnicodeBlock.forName("Latin-1Supplement"));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.forName("LATIN_EXTENDED_A"));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.forName("Latin Extended-A"));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_A, Character.UnicodeBlock.forName("LatinExtended-A"));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.forName("LATIN_EXTENDED_B"));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.forName("Latin Extended-B"));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_B, Character.UnicodeBlock.forName("LatinExtended-B"));
- assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.forName("IPA_EXTENSIONS"));
- assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.forName("IPA Extensions"));
- assertEquals(Character.UnicodeBlock.IPA_EXTENSIONS, Character.UnicodeBlock.forName("IPAExtensions"));
- assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.forName("SPACING_MODIFIER_LETTERS"));
- assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.forName("Spacing Modifier Letters"));
- assertEquals(Character.UnicodeBlock.SPACING_MODIFIER_LETTERS, Character.UnicodeBlock.forName("SpacingModifierLetters"));
- assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.forName("COMBINING_DIACRITICAL_MARKS"));
- assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.forName("Combining Diacritical Marks"));
- assertEquals(Character.UnicodeBlock.COMBINING_DIACRITICAL_MARKS, Character.UnicodeBlock.forName("CombiningDiacriticalMarks"));
- assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.forName("GREEK"));
- assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.forName("Greek and Coptic"));
- assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.forName("GreekandCoptic"));
- assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.forName("Greek"));
- assertEquals(Character.UnicodeBlock.GREEK, Character.UnicodeBlock.forName("Greek"));
- assertEquals(Character.UnicodeBlock.CYRILLIC, Character.UnicodeBlock.forName("CYRILLIC"));
- assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.forName("CYRILLIC_SUPPLEMENTARY"));
- assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.forName("Cyrillic Supplementary"));
- assertEquals(Character.UnicodeBlock.CYRILLIC_SUPPLEMENTARY, Character.UnicodeBlock.forName("CyrillicSupplementary"));
- assertEquals(Character.UnicodeBlock.ARMENIAN, Character.UnicodeBlock.forName("ARMENIAN"));
- assertEquals(Character.UnicodeBlock.HEBREW, Character.UnicodeBlock.forName("HEBREW"));
- assertEquals(Character.UnicodeBlock.ARABIC, Character.UnicodeBlock.forName("ARABIC"));
- assertEquals(Character.UnicodeBlock.SYRIAC, Character.UnicodeBlock.forName("SYRIAC"));
- assertEquals(Character.UnicodeBlock.THAANA, Character.UnicodeBlock.forName("THAANA"));
- assertEquals(Character.UnicodeBlock.DEVANAGARI, Character.UnicodeBlock.forName("DEVANAGARI"));
- assertEquals(Character.UnicodeBlock.BENGALI, Character.UnicodeBlock.forName("BENGALI"));
- assertEquals(Character.UnicodeBlock.GURMUKHI, Character.UnicodeBlock.forName("GURMUKHI"));
- assertEquals(Character.UnicodeBlock.GUJARATI, Character.UnicodeBlock.forName("GUJARATI"));
- assertEquals(Character.UnicodeBlock.ORIYA, Character.UnicodeBlock.forName("ORIYA"));
- assertEquals(Character.UnicodeBlock.TAMIL, Character.UnicodeBlock.forName("TAMIL"));
- assertEquals(Character.UnicodeBlock.TELUGU, Character.UnicodeBlock.forName("TELUGU"));
- assertEquals(Character.UnicodeBlock.KANNADA, Character.UnicodeBlock.forName("KANNADA"));
- assertEquals(Character.UnicodeBlock.MALAYALAM, Character.UnicodeBlock.forName("MALAYALAM"));
- assertEquals(Character.UnicodeBlock.SINHALA, Character.UnicodeBlock.forName("SINHALA"));
- assertEquals(Character.UnicodeBlock.THAI, Character.UnicodeBlock.forName("THAI"));
- assertEquals(Character.UnicodeBlock.LAO, Character.UnicodeBlock.forName("LAO"));
- assertEquals(Character.UnicodeBlock.TIBETAN, Character.UnicodeBlock.forName("TIBETAN"));
- assertEquals(Character.UnicodeBlock.MYANMAR, Character.UnicodeBlock.forName("MYANMAR"));
- assertEquals(Character.UnicodeBlock.GEORGIAN, Character.UnicodeBlock.forName("GEORGIAN"));
- assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.forName("HANGUL_JAMO"));
- assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.forName("Hangul Jamo"));
- assertEquals(Character.UnicodeBlock.HANGUL_JAMO, Character.UnicodeBlock.forName("HangulJamo"));
- assertEquals(Character.UnicodeBlock.ETHIOPIC, Character.UnicodeBlock.forName("ETHIOPIC"));
- assertEquals(Character.UnicodeBlock.CHEROKEE, Character.UnicodeBlock.forName("CHEROKEE"));
- assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.forName("UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS"));
- assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.forName("Unified Canadian Aboriginal Syllabics"));
- assertEquals(Character.UnicodeBlock.UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS, Character.UnicodeBlock.forName("UnifiedCanadianAboriginalSyllabics"));
- assertEquals(Character.UnicodeBlock.OGHAM, Character.UnicodeBlock.forName("OGHAM"));
- assertEquals(Character.UnicodeBlock.RUNIC, Character.UnicodeBlock.forName("RUNIC"));
- assertEquals(Character.UnicodeBlock.TAGALOG, Character.UnicodeBlock.forName("TAGALOG"));
- assertEquals(Character.UnicodeBlock.HANUNOO, Character.UnicodeBlock.forName("HANUNOO"));
- assertEquals(Character.UnicodeBlock.BUHID, Character.UnicodeBlock.forName("BUHID"));
- assertEquals(Character.UnicodeBlock.TAGBANWA, Character.UnicodeBlock.forName("TAGBANWA"));
- assertEquals(Character.UnicodeBlock.KHMER, Character.UnicodeBlock.forName("KHMER"));
- assertEquals(Character.UnicodeBlock.MONGOLIAN, Character.UnicodeBlock.forName("MONGOLIAN"));
- assertEquals(Character.UnicodeBlock.LIMBU, Character.UnicodeBlock.forName("LIMBU"));
- assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.forName("TAI_LE"));
- assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.forName("Tai Le"));
- assertEquals(Character.UnicodeBlock.TAI_LE, Character.UnicodeBlock.forName("TaiLe"));
- assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.forName("KHMER_SYMBOLS"));
- assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.forName("Khmer Symbols"));
- assertEquals(Character.UnicodeBlock.KHMER_SYMBOLS, Character.UnicodeBlock.forName("KhmerSymbols"));
- assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.forName("PHONETIC_EXTENSIONS"));
- assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.forName("Phonetic Extensions"));
- assertEquals(Character.UnicodeBlock.PHONETIC_EXTENSIONS, Character.UnicodeBlock.forName("PhoneticExtensions"));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.forName("LATIN_EXTENDED_ADDITIONAL"));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.forName("Latin Extended Additional"));
- assertEquals(Character.UnicodeBlock.LATIN_EXTENDED_ADDITIONAL, Character.UnicodeBlock.forName("LatinExtendedAdditional"));
- assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.forName("GREEK_EXTENDED"));
- assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.forName("Greek Extended"));
- assertEquals(Character.UnicodeBlock.GREEK_EXTENDED, Character.UnicodeBlock.forName("GreekExtended"));
- assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.forName("GENERAL_PUNCTUATION"));
- assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.forName("General Punctuation"));
- assertEquals(Character.UnicodeBlock.GENERAL_PUNCTUATION, Character.UnicodeBlock.forName("GeneralPunctuation"));
- assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.forName("SUPERSCRIPTS_AND_SUBSCRIPTS"));
- assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.forName("Superscripts and Subscripts"));
- assertEquals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS, Character.UnicodeBlock.forName("SuperscriptsandSubscripts"));
- assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.forName("CURRENCY_SYMBOLS"));
- assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.forName("Currency Symbols"));
- assertEquals(Character.UnicodeBlock.CURRENCY_SYMBOLS, Character.UnicodeBlock.forName("CurrencySymbols"));
- assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.forName("COMBINING_MARKS_FOR_SYMBOLS"));
- assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.forName("Combining Diacritical Marks for Symbols"));
- assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.forName("CombiningDiacriticalMarksforSymbols"));
- assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.forName("Combining Marks for Symbols"));
- assertEquals(Character.UnicodeBlock.COMBINING_MARKS_FOR_SYMBOLS, Character.UnicodeBlock.forName("CombiningMarksforSymbols"));
- assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.forName("LETTERLIKE_SYMBOLS"));
- assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.forName("Letterlike Symbols"));
- assertEquals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS, Character.UnicodeBlock.forName("LetterlikeSymbols"));
- assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.forName("NUMBER_FORMS"));
- assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.forName("Number Forms"));
- assertEquals(Character.UnicodeBlock.NUMBER_FORMS, Character.UnicodeBlock.forName("NumberForms"));
- assertEquals(Character.UnicodeBlock.ARROWS, Character.UnicodeBlock.forName("ARROWS"));
- assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.forName("MATHEMATICAL_OPERATORS"));
- assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.forName("Mathematical Operators"));
- assertEquals(Character.UnicodeBlock.MATHEMATICAL_OPERATORS, Character.UnicodeBlock.forName("MathematicalOperators"));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.forName("MISCELLANEOUS_TECHNICAL"));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.forName("Miscellaneous Technical"));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_TECHNICAL, Character.UnicodeBlock.forName("MiscellaneousTechnical"));
- assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.forName("CONTROL_PICTURES"));
- assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.forName("Control Pictures"));
- assertEquals(Character.UnicodeBlock.CONTROL_PICTURES, Character.UnicodeBlock.forName("ControlPictures"));
- assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.forName("OPTICAL_CHARACTER_RECOGNITION"));
- assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.forName("Optical Character Recognition"));
- assertEquals(Character.UnicodeBlock.OPTICAL_CHARACTER_RECOGNITION, Character.UnicodeBlock.forName("OpticalCharacterRecognition"));
- assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.forName("ENCLOSED_ALPHANUMERICS"));
- assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.forName("Enclosed Alphanumerics"));
- assertEquals(Character.UnicodeBlock.ENCLOSED_ALPHANUMERICS, Character.UnicodeBlock.forName("EnclosedAlphanumerics"));
- assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.forName("BOX_DRAWING"));
- assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.forName("Box Drawing"));
- assertEquals(Character.UnicodeBlock.BOX_DRAWING, Character.UnicodeBlock.forName("BoxDrawing"));
- assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.forName("BLOCK_ELEMENTS"));
- assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.forName("Block Elements"));
- assertEquals(Character.UnicodeBlock.BLOCK_ELEMENTS, Character.UnicodeBlock.forName("BlockElements"));
- assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.forName("GEOMETRIC_SHAPES"));
- assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.forName("Geometric Shapes"));
- assertEquals(Character.UnicodeBlock.GEOMETRIC_SHAPES, Character.UnicodeBlock.forName("GeometricShapes"));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.forName("MISCELLANEOUS_SYMBOLS"));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.forName("Miscellaneous Symbols"));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS, Character.UnicodeBlock.forName("MiscellaneousSymbols"));
- assertEquals(Character.UnicodeBlock.DINGBATS, Character.UnicodeBlock.forName("DINGBATS"));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.forName("MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A"));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.forName("Miscellaneous Mathematical Symbols-A"));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A, Character.UnicodeBlock.forName("MiscellaneousMathematicalSymbols-A"));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.forName("SUPPLEMENTAL_ARROWS_A"));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.forName("Supplemental Arrows-A"));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_A, Character.UnicodeBlock.forName("SupplementalArrows-A"));
- assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.forName("BRAILLE_PATTERNS"));
- assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.forName("Braille Patterns"));
- assertEquals(Character.UnicodeBlock.BRAILLE_PATTERNS, Character.UnicodeBlock.forName("BraillePatterns"));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.forName("SUPPLEMENTAL_ARROWS_B"));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.forName("Supplemental Arrows-B"));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_ARROWS_B, Character.UnicodeBlock.forName("SupplementalArrows-B"));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.forName("MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B"));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.forName("Miscellaneous Mathematical Symbols-B"));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B, Character.UnicodeBlock.forName("MiscellaneousMathematicalSymbols-B"));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.forName("SUPPLEMENTAL_MATHEMATICAL_OPERATORS"));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.forName("Supplemental Mathematical Operators"));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTAL_MATHEMATICAL_OPERATORS, Character.UnicodeBlock.forName("SupplementalMathematicalOperators"));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.forName("MISCELLANEOUS_SYMBOLS_AND_ARROWS"));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.forName("Miscellaneous Symbols and Arrows"));
- assertEquals(Character.UnicodeBlock.MISCELLANEOUS_SYMBOLS_AND_ARROWS, Character.UnicodeBlock.forName("MiscellaneousSymbolsandArrows"));
- assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.forName("CJK_RADICALS_SUPPLEMENT"));
- assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.forName("CJK Radicals Supplement"));
- assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT, Character.UnicodeBlock.forName("CJKRadicalsSupplement"));
- assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.forName("KANGXI_RADICALS"));
- assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.forName("Kangxi Radicals"));
- assertEquals(Character.UnicodeBlock.KANGXI_RADICALS, Character.UnicodeBlock.forName("KangxiRadicals"));
- assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.forName("IDEOGRAPHIC_DESCRIPTION_CHARACTERS"));
- assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.forName("Ideographic Description Characters"));
- assertEquals(Character.UnicodeBlock.IDEOGRAPHIC_DESCRIPTION_CHARACTERS, Character.UnicodeBlock.forName("IdeographicDescriptionCharacters"));
- assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.forName("CJK_SYMBOLS_AND_PUNCTUATION"));
- assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.forName("CJK Symbols and Punctuation"));
- assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION, Character.UnicodeBlock.forName("CJKSymbolsandPunctuation"));
- assertEquals(Character.UnicodeBlock.HIRAGANA, Character.UnicodeBlock.forName("HIRAGANA"));
- assertEquals(Character.UnicodeBlock.KATAKANA, Character.UnicodeBlock.forName("KATAKANA"));
- assertEquals(Character.UnicodeBlock.BOPOMOFO, Character.UnicodeBlock.forName("BOPOMOFO"));
- assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.forName("HANGUL_COMPATIBILITY_JAMO"));
- assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.forName("Hangul Compatibility Jamo"));
- assertEquals(Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO, Character.UnicodeBlock.forName("HangulCompatibilityJamo"));
- assertEquals(Character.UnicodeBlock.KANBUN, Character.UnicodeBlock.forName("KANBUN"));
- assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.forName("BOPOMOFO_EXTENDED"));
- assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.forName("Bopomofo Extended"));
- assertEquals(Character.UnicodeBlock.BOPOMOFO_EXTENDED, Character.UnicodeBlock.forName("BopomofoExtended"));
- assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.forName("KATAKANA_PHONETIC_EXTENSIONS"));
- assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.forName("Katakana Phonetic Extensions"));
- assertEquals(Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS, Character.UnicodeBlock.forName("KatakanaPhoneticExtensions"));
- assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.forName("ENCLOSED_CJK_LETTERS_AND_MONTHS"));
- assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.forName("Enclosed CJK Letters and Months"));
- assertEquals(Character.UnicodeBlock.ENCLOSED_CJK_LETTERS_AND_MONTHS, Character.UnicodeBlock.forName("EnclosedCJKLettersandMonths"));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.forName("CJK_COMPATIBILITY"));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.forName("CJK Compatibility"));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY, Character.UnicodeBlock.forName("CJKCompatibility"));
- assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.forName("CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A"));
- assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.forName("CJK Unified Ideographs Extension A"));
- assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A, Character.UnicodeBlock.forName("CJKUnifiedIdeographsExtensionA"));
- assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.forName("YIJING_HEXAGRAM_SYMBOLS"));
- assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.forName("Yijing Hexagram Symbols"));
- assertEquals(Character.UnicodeBlock.YIJING_HEXAGRAM_SYMBOLS, Character.UnicodeBlock.forName("YijingHexagramSymbols"));
- assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.forName("CJK_UNIFIED_IDEOGRAPHS"));
- assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.forName("CJK Unified Ideographs"));
- assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS, Character.UnicodeBlock.forName("CJKUnifiedIdeographs"));
- assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.forName("YI_SYLLABLES"));
- assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.forName("Yi Syllables"));
- assertEquals(Character.UnicodeBlock.YI_SYLLABLES, Character.UnicodeBlock.forName("YiSyllables"));
- assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.forName("YI_RADICALS"));
- assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.forName("Yi Radicals"));
- assertEquals(Character.UnicodeBlock.YI_RADICALS, Character.UnicodeBlock.forName("YiRadicals"));
- assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.forName("HANGUL_SYLLABLES"));
- assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.forName("Hangul Syllables"));
- assertEquals(Character.UnicodeBlock.HANGUL_SYLLABLES, Character.UnicodeBlock.forName("HangulSyllables"));
- assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.forName("HIGH_SURROGATES"));
- assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.forName("High Surrogates"));
- assertEquals(Character.UnicodeBlock.HIGH_SURROGATES, Character.UnicodeBlock.forName("HighSurrogates"));
- assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.forName("HIGH_PRIVATE_USE_SURROGATES"));
- assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.forName("High Private Use Surrogates"));
- assertEquals(Character.UnicodeBlock.HIGH_PRIVATE_USE_SURROGATES, Character.UnicodeBlock.forName("HighPrivateUseSurrogates"));
- assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.forName("LOW_SURROGATES"));
- assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.forName("Low Surrogates"));
- assertEquals(Character.UnicodeBlock.LOW_SURROGATES, Character.UnicodeBlock.forName("LowSurrogates"));
- assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.forName("PRIVATE_USE_AREA"));
- assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.forName("Private Use Area"));
- assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA, Character.UnicodeBlock.forName("PrivateUseArea"));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.forName("CJK_COMPATIBILITY_IDEOGRAPHS"));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.forName("CJK Compatibility Ideographs"));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS, Character.UnicodeBlock.forName("CJKCompatibilityIdeographs"));
- assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.forName("ALPHABETIC_PRESENTATION_FORMS"));
- assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.forName("Alphabetic Presentation Forms"));
- assertEquals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS, Character.UnicodeBlock.forName("AlphabeticPresentationForms"));
- assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.forName("ARABIC_PRESENTATION_FORMS_A"));
- assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.forName("Arabic Presentation Forms-A"));
- assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_A, Character.UnicodeBlock.forName("ArabicPresentationForms-A"));
- assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.forName("VARIATION_SELECTORS"));
- assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.forName("Variation Selectors"));
- assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS, Character.UnicodeBlock.forName("VariationSelectors"));
- assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.forName("COMBINING_HALF_MARKS"));
- assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.forName("Combining Half Marks"));
- assertEquals(Character.UnicodeBlock.COMBINING_HALF_MARKS, Character.UnicodeBlock.forName("CombiningHalfMarks"));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.forName("CJK_COMPATIBILITY_FORMS"));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.forName("CJK Compatibility Forms"));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS, Character.UnicodeBlock.forName("CJKCompatibilityForms"));
- assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.forName("SMALL_FORM_VARIANTS"));
- assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.forName("Small Form Variants"));
- assertEquals(Character.UnicodeBlock.SMALL_FORM_VARIANTS, Character.UnicodeBlock.forName("SmallFormVariants"));
- assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.forName("ARABIC_PRESENTATION_FORMS_B"));
- assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.forName("Arabic Presentation Forms-B"));
- assertEquals(Character.UnicodeBlock.ARABIC_PRESENTATION_FORMS_B, Character.UnicodeBlock.forName("ArabicPresentationForms-B"));
- assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.forName("HALFWIDTH_AND_FULLWIDTH_FORMS"));
- assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.forName("Halfwidth and Fullwidth Forms"));
- assertEquals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS, Character.UnicodeBlock.forName("HalfwidthandFullwidthForms"));
- assertEquals(Character.UnicodeBlock.SPECIALS, Character.UnicodeBlock.forName("SPECIALS"));
- assertEquals(Character.UnicodeBlock.LINEAR_B_SYLLABARY, Character.UnicodeBlock.forName("LINEAR_B_SYLLABARY"));
- assertEquals(Character.UnicodeBlock.LINEAR_B_SYLLABARY, Character.UnicodeBlock.forName("Linear B Syllabary"));
- assertEquals(Character.UnicodeBlock.LINEAR_B_SYLLABARY, Character.UnicodeBlock.forName("LinearBSyllabary"));
- assertEquals(Character.UnicodeBlock.LINEAR_B_IDEOGRAMS, Character.UnicodeBlock.forName("LINEAR_B_IDEOGRAMS"));
- assertEquals(Character.UnicodeBlock.LINEAR_B_IDEOGRAMS, Character.UnicodeBlock.forName("Linear B Ideograms"));
- assertEquals(Character.UnicodeBlock.LINEAR_B_IDEOGRAMS, Character.UnicodeBlock.forName("LinearBIdeograms"));
- assertEquals(Character.UnicodeBlock.AEGEAN_NUMBERS, Character.UnicodeBlock.forName("AEGEAN_NUMBERS"));
- assertEquals(Character.UnicodeBlock.AEGEAN_NUMBERS, Character.UnicodeBlock.forName("Aegean Numbers"));
- assertEquals(Character.UnicodeBlock.AEGEAN_NUMBERS, Character.UnicodeBlock.forName("AegeanNumbers"));
- assertEquals(Character.UnicodeBlock.OLD_ITALIC, Character.UnicodeBlock.forName("OLD_ITALIC"));
- assertEquals(Character.UnicodeBlock.OLD_ITALIC, Character.UnicodeBlock.forName("Old Italic"));
- assertEquals(Character.UnicodeBlock.OLD_ITALIC, Character.UnicodeBlock.forName("OldItalic"));
- assertEquals(Character.UnicodeBlock.GOTHIC, Character.UnicodeBlock.forName("GOTHIC"));
- assertEquals(Character.UnicodeBlock.UGARITIC, Character.UnicodeBlock.forName("UGARITIC"));
- assertEquals(Character.UnicodeBlock.DESERET, Character.UnicodeBlock.forName("DESERET"));
- assertEquals(Character.UnicodeBlock.SHAVIAN, Character.UnicodeBlock.forName("SHAVIAN"));
- assertEquals(Character.UnicodeBlock.OSMANYA, Character.UnicodeBlock.forName("OSMANYA"));
- assertEquals(Character.UnicodeBlock.CYPRIOT_SYLLABARY, Character.UnicodeBlock.forName("CYPRIOT_SYLLABARY"));
- assertEquals(Character.UnicodeBlock.CYPRIOT_SYLLABARY, Character.UnicodeBlock.forName("Cypriot Syllabary"));
- assertEquals(Character.UnicodeBlock.CYPRIOT_SYLLABARY, Character.UnicodeBlock.forName("CypriotSyllabary"));
- assertEquals(Character.UnicodeBlock.BYZANTINE_MUSICAL_SYMBOLS, Character.UnicodeBlock.forName("BYZANTINE_MUSICAL_SYMBOLS"));
- assertEquals(Character.UnicodeBlock.BYZANTINE_MUSICAL_SYMBOLS, Character.UnicodeBlock.forName("Byzantine Musical Symbols"));
- assertEquals(Character.UnicodeBlock.BYZANTINE_MUSICAL_SYMBOLS, Character.UnicodeBlock.forName("ByzantineMusicalSymbols"));
- assertEquals(Character.UnicodeBlock.MUSICAL_SYMBOLS, Character.UnicodeBlock.forName("MUSICAL_SYMBOLS"));
- assertEquals(Character.UnicodeBlock.MUSICAL_SYMBOLS, Character.UnicodeBlock.forName("Musical Symbols"));
- assertEquals(Character.UnicodeBlock.MUSICAL_SYMBOLS, Character.UnicodeBlock.forName("MusicalSymbols"));
- assertEquals(Character.UnicodeBlock.TAI_XUAN_JING_SYMBOLS, Character.UnicodeBlock.forName("TAI_XUAN_JING_SYMBOLS"));
- assertEquals(Character.UnicodeBlock.TAI_XUAN_JING_SYMBOLS, Character.UnicodeBlock.forName("Tai Xuan Jing Symbols"));
- assertEquals(Character.UnicodeBlock.TAI_XUAN_JING_SYMBOLS, Character.UnicodeBlock.forName("TaiXuanJingSymbols"));
- assertEquals(Character.UnicodeBlock.MATHEMATICAL_ALPHANUMERIC_SYMBOLS, Character.UnicodeBlock.forName("MATHEMATICAL_ALPHANUMERIC_SYMBOLS"));
- assertEquals(Character.UnicodeBlock.MATHEMATICAL_ALPHANUMERIC_SYMBOLS, Character.UnicodeBlock.forName("Mathematical Alphanumeric Symbols"));
- assertEquals(Character.UnicodeBlock.MATHEMATICAL_ALPHANUMERIC_SYMBOLS, Character.UnicodeBlock.forName("MathematicalAlphanumericSymbols"));
- assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B, Character.UnicodeBlock.forName("CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B"));
- assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B, Character.UnicodeBlock.forName("CJK Unified Ideographs Extension B"));
- assertEquals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B, Character.UnicodeBlock.forName("CJKUnifiedIdeographsExtensionB"));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT, Character.UnicodeBlock.forName("CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT"));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT, Character.UnicodeBlock.forName("CJK Compatibility Ideographs Supplement"));
- assertEquals(Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT, Character.UnicodeBlock.forName("CJKCompatibilityIdeographsSupplement"));
- assertEquals(Character.UnicodeBlock.TAGS, Character.UnicodeBlock.forName("TAGS"));
- assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS_SUPPLEMENT, Character.UnicodeBlock.forName("VARIATION_SELECTORS_SUPPLEMENT"));
- assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS_SUPPLEMENT, Character.UnicodeBlock.forName("Variation Selectors Supplement"));
- assertEquals(Character.UnicodeBlock.VARIATION_SELECTORS_SUPPLEMENT, Character.UnicodeBlock.forName("VariationSelectorsSupplement"));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_A, Character.UnicodeBlock.forName("SUPPLEMENTARY_PRIVATE_USE_AREA_A"));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_A, Character.UnicodeBlock.forName("Supplementary Private Use Area-A"));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_A, Character.UnicodeBlock.forName("SupplementaryPrivateUseArea-A"));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_B, Character.UnicodeBlock.forName("SUPPLEMENTARY_PRIVATE_USE_AREA_B"));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_B, Character.UnicodeBlock.forName("Supplementary Private Use Area-B"));
- assertEquals(Character.UnicodeBlock.SUPPLEMENTARY_PRIVATE_USE_AREA_B, Character.UnicodeBlock.forName("SupplementaryPrivateUseArea-B"));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks null as a parameter.",
- method = "forName",
- args = {java.lang.String.class}
- )
- public void test_forNameLjava_lang_StringExceptions() {
- try {
- Character.UnicodeBlock.forName(null);
- fail("No NPE");
- } catch(NullPointerException e) {
- }
-
- try {
- Character.UnicodeBlock.forName("INVALID_NAME");
- fail("No illegal argument exception");
- } catch(IllegalArgumentException e) {
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassCastExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassCastExceptionTest.java
deleted file mode 100644
index 1e61f87..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassCastExceptionTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(ClassCastException.class)
-public class ClassCastExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.ClassCastException#ClassCastException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ClassCastException",
- args = {}
- )
- public void test_Constructor() {
- ClassCastException e = new ClassCastException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.ClassCastException#ClassCastException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ClassCastException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- ClassCastException e = new ClassCastException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassCircularityErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassCircularityErrorTest.java
deleted file mode 100644
index 7acf714..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassCircularityErrorTest.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(ClassCircularityError.class)
-public class ClassCircularityErrorTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ClassCircularityError",
- args = {}
- )
- public void test_ClassCircularityError() {
- ClassCircularityError cce = new ClassCircularityError();
- assertNull(cce.getMessage());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ClassCircularityError",
- args = {java.lang.String.class}
- )
- public void test_ClassCircularityError_String() {
- String message = "Test message";
- ClassCircularityError cce = new ClassCircularityError(message);
- assertEquals(message, cce.getMessage());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassFormatErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassFormatErrorTest.java
deleted file mode 100644
index 0aeef9b..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassFormatErrorTest.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(ClassFormatError.class)
-public class ClassFormatErrorTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ClassFormatError",
- args = {}
- )
- public void test_ClassFormatError() {
- ClassFormatError cfe = new ClassFormatError();
- assertNull(cfe.getMessage());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ClassFormatError",
- args = {java.lang.String.class}
- )
- public void test_ClassFormatError_String() {
- String message = "Test message";
- ClassFormatError cfe = new ClassFormatError(message);
- assertEquals(message, cfe.getMessage());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassLoaderTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassLoaderTest.java
deleted file mode 100644
index fd68f66..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassLoaderTest.java
+++ /dev/null
@@ -1,1251 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.BrokenTest;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.nio.ByteBuffer;
-import java.security.CodeSource;
-import java.security.Permission;
-import java.security.PermissionCollection;
-import java.security.Policy;
-import java.security.ProtectionDomain;
-import java.util.Enumeration;
-import java.util.NoSuchElementException;
-
-@TestTargetClass(ClassLoader.class)
-public class ClassLoaderTest extends TestCase {
-
- public static volatile int flag;
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ClassLoader",
- args = {}
- )
- public void test_ClassLoader() {
- PublicClassLoader pcl = new PublicClassLoader();
- SecurityManager sm = new SecurityManager() {
- RuntimePermission rp = new RuntimePermission("getProtectionDomain");
-
- public void checkCreateClassLoader() {
- throw new SecurityException();
- }
-
- public void checkPermission(Permission perm) {
- if (perm.equals(rp)) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new PublicClassLoader();
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ClassLoader",
- args = {java.lang.ClassLoader.class}
- )
- public void test_ClassLoaderLClassLoader() {
- PublicClassLoader pcl = new PublicClassLoader(
- ClassLoader.getSystemClassLoader());
- assertEquals(ClassLoader.getSystemClassLoader(), pcl.getParent());
-
- SecurityManager sm = new SecurityManager() {
- RuntimePermission rp = new RuntimePermission("getProtectionDomain");
-
- public void checkCreateClassLoader() {
- throw new SecurityException();
- }
-
- public void checkPermission(Permission perm) {
- if (perm.equals(rp)) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new PublicClassLoader(ClassLoader.getSystemClassLoader());
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "",
- method = "clearAssertionStatus",
- args = {}
- )
- @AndroidOnly("clearAssertionStatus method is not supported.")
- @BrokenTest("Android doesn't support assertions to be activated through " +
- "the api")
- public void test_clearAssertionStatus() {
- String className = getClass().getPackage().getName() + ".TestAssertions";
- String className1 = getClass().getPackage().getName() + ".TestAssertions1";
- ClassLoader cl = ClassLoader.getSystemClassLoader();
- cl.setClassAssertionStatus("TestAssertions", true);
- cl.setDefaultAssertionStatus(true);
- try {
-
- Class clazz = cl.loadClass(className);
-
- TestAssertions ta = (TestAssertions) clazz.newInstance();
- try {
- ta.test();
- fail("AssertionError should be thrown.");
- } catch(AssertionError ae) {
- //expected
- }
- cl.clearAssertionStatus();
- clazz = cl.loadClass(className1);
-
- TestAssertions1 ta1 = (TestAssertions1) clazz.newInstance();
- try {
- ta1.test();
- } catch(AssertionError ae) {
- fail("AssertionError should not be thrown.");
- }
-
- } catch(Exception cnfe) {
- fail("Unexpected exception: " + cnfe.toString());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "This method is not supported. " +
- "UnsupportedOperationException should be thrown.",
- method = "defineClass",
- args = {byte[].class, int.class, int.class}
- )
- @AndroidOnly("define methods re not supported on Android. " +
- "UnsupportedOperationException should be thrown.")
- public void test_defineClassLbyteArrayLintLint() throws Exception {
-
- try {
- Class<?> a = new Ldr().define(Ldr.TEST_CASE_DEFINE_1);
- //assertEquals("org.apache.harmony.luni.tests.java.lang.A", a.getName());
- fail("UnsupportedOperationException was not thrown.");
- } catch(UnsupportedOperationException uoe) {
- //expected
- }
-
- try {
- new Ldr().define(1000, Ldr.TEST_CASE_DEFINE_1);
- fail("IndexOutOfBoundsException is not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- fail("UnsupportedOperationException should be thrown.");
- } catch(UnsupportedOperationException uoe) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "This method is not supported. UnsupportedOperationException should be thrown.",
- method = "defineClass",
- args = {java.lang.String.class, byte[].class, int.class, int.class, java.security.ProtectionDomain.class}
- )
- @AndroidOnly("define methods re not supported on Android. " +
- "UnsupportedOperationException should be thrown.")
- public void test_defineClassLjava_lang_StringLbyteArrayLintLintLProtectionDomain()
- throws Exception {
-
- try {
- Class<?> a = new Ldr().define(Ldr.TEST_CASE_DEFINE_2);
- //assertEquals("org.apache.harmony.luni.tests.java.lang.A", a.getName());
- //assertEquals(getClass().getProtectionDomain(), a.getProtectionDomain());
- fail("UnsupportedOperationException was not thrown.");
- } catch(UnsupportedOperationException uoe) {
- //expected
- }
-
- try {
- new Ldr().define(1000, Ldr.TEST_CASE_DEFINE_2);
- fail("IndexOutOfBoundsException is not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- fail("UnsupportedOperationException should be thrown.");
- } catch(UnsupportedOperationException uoe) {
- //expected
- }
-
- /*try {
- ErrorLdr loader = new ErrorLdr();
-
- try {
- loader.define("WrongFormatClass", Ldr.TEST_CASE_DEFINE_2);
- fail("ClassFormatError should be thrown.");
- } catch (ClassFormatError le) {
- //expected
- } catch(UnsupportedOperationException uoe) {
- //expected
- }
-
- try {
- loader.defineWrongName("TestClass", 0);
- fail("NoClassDefFoundError should be thrown.");
- } catch (NoClassDefFoundError ncdfe) {
- //expected
- } catch(UnsupportedOperationException uoe) {
- //expected
- }
-
- try {
- Class<?> clazz = loader.defineNullDomain("TestClass", 0);
- assertEquals(getClass().getProtectionDomain(),
- clazz.getProtectionDomain());
- } catch(UnsupportedOperationException uoe) {
- //expected
- }
-
- } catch(Exception e) {
- fail("Unexpected exception was thrown: " + e.toString());
- }
- */
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "This method is not supported. UnsupportedOperationException should be thrown.",
- method = "defineClass",
- args = {java.lang.String.class, java.nio.ByteBuffer.class, java.security.ProtectionDomain.class}
- )
- @AndroidOnly("define methods re not supported on Android. " +
- "UnsupportedOperationException should be thrown.")
- public void test_defineClassLjava_lang_StringLByteBufferLProtectionDomain() {
-
- try {
- try {
- Class<?> a = new Ldr().define(Ldr.TEST_CASE_DEFINE_3);
- //assertEquals("org.apache.harmony.luni.tests.java.lang.A", a.getName());
- //assertEquals(getClass().getProtectionDomain(), a.getProtectionDomain());
- fail("UnsupportedOperationException was not thrown.");
- } catch(UnsupportedOperationException uoe) {
- //expected
- }
-
- try {
- new Ldr().define(1000, Ldr.TEST_CASE_DEFINE_3);
- fail("IndexOutOfBoundsException is not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- fail("UnsupportedOperationException should be thrown.");
- } catch(UnsupportedOperationException uoe) {
- //expected
- }
-
- } catch(Exception e) {
- fail("Unexpected exception was thrown: " + e.toString());
- }
- }
-
- /**
- * Tests that Classloader.defineClass() assigns appropriate
- * default domains to the defined classes.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "This method is not supported. " +
- "UnsupportedOperationException should be thrown.",
- method = "defineClass",
- args = {java.lang.String.class, byte[].class, int.class, int.class}
- )
- @AndroidOnly("define methods re not supported on Android. " +
- "UnsupportedOperationException should be thrown.")
- public void test_defineClass_defaultDomain() throws Exception {
- try {
- Class<?> a = new Ldr().define(Ldr.TEST_CASE_DEFINE_0);
- fail("UnsupportedOperationException was not thrown.");
- } catch(UnsupportedOperationException uoe) {
- //expected
- }
-
- try {
- new Ldr().define(1000, Ldr.TEST_CASE_DEFINE_0);
- fail("IndexOutOfBoundsException is not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- fail("UnsupportedOperationException should be thrown.");
- } catch(UnsupportedOperationException uoe) {
- //expected
- }
- }
-
- static class SyncTestClassLoader extends ClassLoader {
- Object lock;
- volatile int numFindClassCalled;
-
- SyncTestClassLoader(Object o) {
- this.lock = o;
- numFindClassCalled = 0;
- }
-
- /*
- * Byte array of bytecode equivalent to the following source code:
- * public class TestClass {
- * }
- */
- private byte[] classData = new byte[] {
- -54, -2, -70, -66, 0, 0, 0, 49, 0, 13,
- 10, 0, 3, 0, 10, 7, 0, 11, 7, 0,
- 12, 1, 0, 6, 60, 105, 110, 105, 116, 62,
- 1, 0, 3, 40, 41, 86, 1, 0, 4, 67,
- 111, 100, 101, 1, 0, 15, 76, 105, 110, 101,
- 78, 117, 109, 98, 101, 114, 84, 97, 98, 108,
- 101, 1, 0, 10, 83, 111, 117, 114, 99, 101,
- 70, 105, 108, 101, 1, 0, 14, 84, 101, 115,
- 116, 67, 108, 97, 115, 115, 46, 106, 97, 118,
- 97, 12, 0, 4, 0, 5, 1, 0, 9, 84,
- 101, 115, 116, 67, 108, 97, 115, 115, 1, 0,
- 16, 106, 97, 118, 97, 47, 108, 97, 110, 103,
- 47, 79, 98, 106, 101, 99, 116, 0, 33, 0,
- 2, 0, 3, 0, 0, 0, 0, 0, 1, 0,
- 1, 0, 4, 0, 5, 0, 1, 0, 6, 0,
- 0, 0, 29, 0, 1, 0, 1, 0, 0, 0,
- 5, 42, -73, 0, 1, -79, 0, 0, 0, 1,
- 0, 7, 0, 0, 0, 6, 0, 1, 0, 0,
- 0, 1, 0, 1, 0, 8, 0, 0, 0, 2,
- 0, 9 };
-
- protected Class findClass(String name) throws ClassNotFoundException {
- try {
- while (flag != 2) {
- synchronized (lock) {
- lock.wait();
- }
- }
- } catch (InterruptedException ie) {}
-
- if (name.equals("TestClass")) {
- numFindClassCalled++;
- return defineClass(null, classData, 0, classData.length);
- } else {
- throw new ClassNotFoundException("Class " + name + " not found.");
- }
- }
- }
-
- static class SyncLoadTestThread extends Thread {
- volatile boolean started;
- ClassLoader cl;
- Class cls;
-
- SyncLoadTestThread(ClassLoader cl) {
- this.cl = cl;
- }
-
- public void run() {
- try {
- started = true;
- cls = Class.forName("TestClass", false, cl);
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- }
-
- /**
- * Regression test for HARMONY-1939:
- * 2 threads simultaneously run Class.forName() method for the same classname
- * and the same classloader. It is expected that both threads succeed but
- * class must be defined just once.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Regression test.",
- method = "loadClass",
- args = {java.lang.String.class}
- )
- @BrokenTest("Both threads try to define class. But defineClass is not " +
- "supported on Adnroid. so both seem to succeed defining the class.")
- public void test_loadClass_concurrentLoad() throws Exception
- {
- Object lock = new Object();
- SyncTestClassLoader cl = new SyncTestClassLoader(lock);
- SyncLoadTestThread tt1 = new SyncLoadTestThread(cl);
- SyncLoadTestThread tt2 = new SyncLoadTestThread(cl);
- flag = 1;
- tt1.start();
- tt2.start();
-
- while (!tt1.started && !tt2.started) {
- Thread.sleep(100);
- }
-
- flag = 2;
- synchronized (lock) {
- lock.notifyAll();
- }
- tt1.join();
- tt2.join();
-
- assertSame("Bad or redefined class", tt1.cls, tt2.cls);
- assertEquals("Both threads tried to define class", 1, cl.numFindClassCalled);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "loadClass",
- args = {java.lang.String.class}
- )
- public void test_loadClassLjava_lang_String() {
-
- String [] classNames = {"org.apache.harmony.luni.tests.java.lang.TestClass1",
- "org.apache.harmony.luni.tests.java.lang.TestClass3",
- "org.apache.harmony.luni.tests.java.lang.A"};
-
- ClassLoader cl = getClass().getClassLoader();
- for(String str:classNames) {
- try {
- Class<?> clazz = cl.loadClass(str);
- assertNotNull(clazz);
- assertEquals(str, clazz.getName());
- if(str.endsWith("A"))
- clazz.newInstance();
- if(str.endsWith("TestClass1")) {
- try {
- clazz.newInstance();
- fail("ExceptionInInitializerError was not thrown.");
- } catch(ExceptionInInitializerError eiine) {
- //expected
- }
- }
- if(str.endsWith("TestClass3")) {
- try {
- clazz.newInstance();
- fail("IllegalAccessException was not thrown.");
- } catch(IllegalAccessException ie) {
- //expected
- }
- }
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException was thrown." + e.getMessage());
- } catch (InstantiationException e) {
- fail("InstantiationException was thrown.");
- } catch (IllegalAccessException e) {
- fail("IllegalAccessException was thrown.");
- }
- }
-
- try {
- Class<?> clazz = cl.loadClass("org.apache.harmony.luni.tests.java.lang.TestClass4");
- fail("ClassNotFoundException was not thrown.");
- } catch (ClassNotFoundException e) {
- //expected
- }
-
- try {
- Class<?> clazz = cl.loadClass("org.apache.harmony.luni.tests.java.lang.TestClass5");
- fail("ClassNotFoundException was not thrown.");
- } catch (ClassNotFoundException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "loadClass",
- args = {java.lang.String.class, boolean.class}
- )
- public void test_loadClassLjava_lang_StringLZ() {
- PackageClassLoader pcl = new PackageClassLoader();
- String className = getClass().getPackage().getName() + ".A";
- try {
- Class<?> clazz = pcl.loadClass(className, false);
- assertEquals(className, clazz.getName());
- assertNotNull(clazz.newInstance());
-
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException was thrown.");
- } catch (InstantiationException e) {
- fail("InstantiationException was thrown.");
- } catch (IllegalAccessException e) {
- fail("IllegalAccessException was thrown.");
- }
-
- try {
- Class<?> clazz = pcl.loadClass(className, true);
- assertEquals(className, clazz.getName());
- assertNotNull(clazz.newInstance());
-
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException was thrown.");
- } catch (InstantiationException e) {
- fail("InstantiationException was thrown.");
- } catch (IllegalAccessException e) {
- fail("IllegalAccessException was thrown.");
- }
- try {
- Class<?> clazz = pcl.loadClass("UnknownClass", false);
- assertEquals("TestClass", clazz.getName());
- fail("ClassNotFoundException was not thrown.");
- } catch (ClassNotFoundException e) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.ClassLoader#getResource(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getResource",
- args = {java.lang.String.class}
- )
- public void test_getResourceLjava_lang_String() {
- // Test for method java.net.URL
- // java.lang.ClassLoader.getResource(java.lang.String)
- java.net.URL u = ClassLoader.getSystemClassLoader().getResource("hyts_Foo.c");
- assertNotNull("Unable to find resource", u);
- java.io.InputStream is = null;
- try {
- is = u.openStream();
- assertNotNull("Resource returned is invalid", is);
- is.close();
- } catch (java.io.IOException e) {
- fail("IOException getting stream for resource : " + e.getMessage());
- }
-
-
-
- assertNull(ClassLoader.getSystemClassLoader().
- getResource("not.found.resource"));
- }
-
- /**
- * @tests java.lang.ClassLoader#getResourceAsStream(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getResourceAsStream",
- args = {java.lang.String.class}
- )
- public void test_getResourceAsStreamLjava_lang_String() {
- // Test for method java.io.InputStream
- // java.lang.ClassLoader.getResourceAsStream(java.lang.String)
- // Need better test...
-
- java.io.InputStream is = null;
- assertNotNull("Failed to find resource: HelloWorld.txt", (is = ClassLoader
- .getSystemClassLoader().getResourceAsStream("HelloWorld.txt")));
-
- byte [] array = new byte[13];
- try {
- is.read(array);
- } catch(IOException ioe) {
- fail("IOException was not thrown.");
- } finally {
- try {
- is.close();
- } catch(IOException ioe) {}
- }
-
- assertEquals("Hello, World.", new String(array));
-
-
- try {
- is.close();
- } catch (java.io.IOException e) {
- fail("Exception during getResourceAsStream: " + e.toString());
- }
-
- assertNull(getClass().getClassLoader().
- getResourceAsStream("unknownResource.txt"));
- }
-
- /**
- * @tests java.lang.ClassLoader#getSystemClassLoader()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "",
- method = "getSystemClassLoader",
- args = {}
- )
- public void test_getSystemClassLoader() {
- // Test for method java.lang.ClassLoader
- // java.lang.ClassLoader.getSystemClassLoader()
- ClassLoader cl = ClassLoader.getSystemClassLoader();
-
- java.io.InputStream is = cl.getResourceAsStream("hyts_Foo.c");
- assertNotNull("Failed to find resource from system classpath", is);
- try {
- is.close();
- } catch (java.io.IOException e) {
- }
-
- SecurityManager sm = new SecurityManager() {
- public void checkPermission(Permission perm) {
- if(perm.getName().equals("getClassLoader")) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldManager = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- ClassLoader.getSystemClassLoader();
- } catch(SecurityException se) {
- //expected
- } finally {
- System.setSecurityManager(oldManager);
- }
-/*
- * // java.lang.Error is not thrown on RI, but it's specified.
- *
- * String keyProp = "java.system.class.loader";
- * String oldProp = System.getProperty(keyProp);
- * System.setProperty(keyProp, "java.test.UnknownClassLoader");
- * boolean isFailed = false;
- * try {
- * ClassLoader.getSystemClassLoader();
- * isFailed = true;
- * } catch(java.lang.Error e) {
- * //expected
- * } finally {
- * if(oldProp == null) {
- * System.clearProperty(keyProp);
- * } else {
- * System.setProperty(keyProp, oldProp);
- * }
- * }
- * assertFalse("java.lang.Error was not thrown.", isFailed);
- */
- }
-
- /**
- * @tests java.lang.ClassLoader#getSystemResource(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSystemResource",
- args = {java.lang.String.class}
- )
- public void test_getSystemResourceLjava_lang_String() {
- // java.lang.ClassLoader.getSystemResource(java.lang.String)
- // Need better test...
-
-
- //String classResource = getClass().getPackage().getName().replace(".", "/") + "/" +
- // getClass().getSimpleName() + ".class";
- //assertNotNull("Failed to find resource: " + classResource,
- // ClassLoader.getSystemResource(classResource));
-
- URL url = null;
- assertNotNull("Failed to find resource: HelloWorld.txt", (url = ClassLoader
- .getSystemClassLoader().getSystemResource("HelloWorld.txt")));
-
- byte [] array = new byte[13];
- InputStream is = null;
- try {
- is = url.openStream();
- is.read(array);
- } catch(IOException ioe) {
- fail("IOException was not thrown.");
- } finally {
- try {
- is.close();
- } catch(IOException ioe) {}
- }
-
- assertEquals("Hello, World.", new String(array));
- assertNull("Doesn't return null for unknown resource.",
- ClassLoader.getSystemClassLoader().getSystemResource("NotFound"));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSystemResourceAsStream",
- args = {java.lang.String.class}
- )
- public void test_getSystemResourceAsStreamLjava_lang_String() {
-
- //String classResource = getClass().getPackage().getName().replace(".", "/") + "/" +
- // getClass().getSimpleName() + ".class";
- //assertNotNull("Failed to find resource: " + classResource,
- // ClassLoader.getSystemResourceAsStream(classResource));
-
- java.io.InputStream is = null;
- assertNotNull("Failed to find resource: HelloWorld.txt", (is = ClassLoader
- .getSystemClassLoader().getSystemResourceAsStream("HelloWorld.txt")));
-
- byte [] array = new byte[13];
- try {
- is.read(array);
- } catch(IOException ioe) {
- fail("IOException was not thrown.");
- } finally {
- try {
- is.close();
- } catch(IOException ioe) {}
- }
-
- assertEquals("Hello, World.", new String(array));
-
- assertNull(ClassLoader.getSystemResourceAsStream("NotFoundResource"));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSystemResources",
- args = {java.lang.String.class}
- )
- public void test_getSystemResources() {
-
- String textResource = "HelloWorld.txt";
-
- try {
- Enumeration<URL> urls = ClassLoader.getSystemResources(textResource);
- assertNotNull(urls);
- assertTrue(urls.nextElement().getPath().endsWith(textResource));
- try {
- urls.nextElement();
- fail("NoSuchElementException was not thrown.");
- } catch(NoSuchElementException nse) {
- //expected
- }
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPackage",
- args = {java.lang.String.class}
- )
- @KnownFailure("PackageClassLoader.getPackage returns null.")
- public void test_getPackageLjava_lang_String() {
- PackageClassLoader pcl = new PackageClassLoader();
-
- String [] packageProperties = { "test.package", "title", "1.0",
- "Vendor", "Title", "1.1", "implementation vendor"};
-
- URL url = null;
- try {
- url = new URL("file:");
- } catch (MalformedURLException e) {
- fail("MalformedURLException was thrown.");
- }
- pcl.definePackage(packageProperties[0],
- packageProperties[1],
- packageProperties[2],
- packageProperties[3],
- packageProperties[4],
- packageProperties[5],
- packageProperties[6],
- url);
-
- assertNotNull(pcl.getPackage(packageProperties[0]));
-
- assertEquals("should define current package", getClass().getPackage(),
- pcl.getPackage(getClass().getPackage().getName()));
-
- assertNull(pcl.getPackage("not.found.package"));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPackages",
- args = {}
- )
- @KnownFailure("The package canot be found. Seems like the cache is not"
- + "shared between the class loaders. But this test seems to"
- + "expect exactly that. this tests works on the RI.")
- public void test_getPackages() {
-
- PackageClassLoader pcl = new PackageClassLoader();
-
- String [] packageProperties = { "test.package", "title", "1.0",
- "Vendor", "Title", "1.1", "implementation vendor"};
-
- URL url = null;
- try {
- url = new URL("file:");
- } catch (MalformedURLException e) {
- fail("MalformedURLException was thrown.");
- }
- pcl.definePackage(packageProperties[0],
- packageProperties[1],
- packageProperties[2],
- packageProperties[3],
- packageProperties[4],
- packageProperties[5],
- packageProperties[6],
- url);
-
- Package [] packages = pcl.getPackages();
- assertTrue(packages.length != 0);
-
- pcl = new PackageClassLoader();
- packages = pcl.getPackages();
- assertNotNull(packages);
-
- boolean isThisFound = false;
- for(Package p:packages) {
- if(p.equals(getClass().getPackage())) {
- isThisFound = true;
- }
- }
- assertTrue(isThisFound);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getParent",
- args = {}
- )
- public void test_getParent() {
- PublicClassLoader pcl = new PublicClassLoader();
- assertNotNull(pcl.getParent());
- ClassLoader cl = getClass().getClassLoader().getParent();
- assertNotNull(cl);
-
- SecurityManager sm = new SecurityManager() {
-
- final String perName = "getClassLoader";
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals(perName)) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- getClass().getClassLoader().getParent();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getResources",
- args = {java.lang.String.class}
- )
- public void test_getResourcesLjava_lang_String() {
- Enumeration<java.net.URL> urls = null;
- FileInputStream fis = null;
- try {
- urls = ClassLoader.getSystemClassLoader().getResources("HelloWorld.txt");
- URL url = urls.nextElement();
- fis = new FileInputStream(url.getFile());
- byte [] array = new byte[13];
- fis.read(array);
- assertEquals("Hello, World.", new String(array));
- } catch (IOException e) {
-
- } finally {
- try {
- fis.close();
- } catch(Exception e) {}
- }
-
- assertNull(ClassLoader.getSystemClassLoader().
- getResource("not.found.resource"));
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "definePackage",
- args = {java.lang.String.class, java.lang.String.class,
- java.lang.String.class, java.lang.String.class,
- java.lang.String.class, java.lang.String.class,
- java.lang.String.class, java.net.URL.class }
- )
- public void test_definePackage() {
-
- PackageClassLoader pcl = new PackageClassLoader();
-
- String [] packageProperties = { "test.package", "title", "1.0",
- "Vendor", "Title", "1.1", "implementation vendor"};
-
- URL url = null;
- try {
- url = new URL("file:");
- } catch (MalformedURLException e) {
- fail("MalformedURLException was thrown.");
- }
- pcl.definePackage(packageProperties[0],
- packageProperties[1],
- packageProperties[2],
- packageProperties[3],
- packageProperties[4],
- packageProperties[5],
- packageProperties[6],
- url);
-
- Package pack = pcl.getPackage(packageProperties[0]);
- assertEquals(packageProperties[1], pack.getSpecificationTitle());
- assertEquals(packageProperties[2], pack.getSpecificationVersion());
- assertEquals(packageProperties[3], pack.getSpecificationVendor());
- assertEquals(packageProperties[4], pack.getImplementationTitle());
- assertEquals(packageProperties[5], pack.getImplementationVersion());
- assertEquals(packageProperties[6], pack.getImplementationVendor());
- assertTrue(pack.isSealed(url));
- assertTrue(pack.isSealed());
-
- try {
- pcl.definePackage(packageProperties[0],
- packageProperties[1],
- packageProperties[2],
- packageProperties[3],
- packageProperties[4],
- packageProperties[5],
- packageProperties[6],
- null);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- pcl.definePackage("test.package.test", null, null, null, null,
- null, null, null);
- pack = pcl.getPackage("test.package.test");
- assertNull(pack.getSpecificationTitle());
- assertNull(pack.getSpecificationVersion());
- assertNull(pack.getSpecificationVendor());
- assertNull(pack.getImplementationTitle());
- assertNull(pack.getImplementationVersion());
- assertNull(pack.getImplementationVendor());
- assertFalse(pack.isSealed());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "findClass",
- args = {java.lang.String.class}
- )
- @AndroidOnly("findClass method throws ClassNotFoundException exception.")
- public void test_findClass(){
-
- try {
- PackageClassLoader pcl = new PackageClassLoader();
- pcl.findClass(getClass().getPackage().getName() + ".A");
- fail("ClassNotFoundException was not thrown.");
- } catch(ClassNotFoundException cnfe) {
- //expected
- }
-
- try {
- PackageClassLoader pcl = new PackageClassLoader();
- pcl.findClass("TestClass");
- fail("ClassNotFoundException was not thrown.");
- } catch(ClassNotFoundException cnfe) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "findLibrary",
- args = {java.lang.String.class}
- )
- @AndroidOnly("findLibrary method is not supported, it returns null.")
- public void test_findLibrary() {
- PackageClassLoader pcl = new PackageClassLoader();
- assertNull(pcl.findLibrary("libjvm.so"));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "findResource",
- args = {java.lang.String.class}
- )
- @AndroidOnly("findResource method is not supported, it returns null.")
- public void test_findResourceLjava_lang_String() {
- assertNull(new PackageClassLoader().findResource("hyts_Foo.c"));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "findResources",
- args = {java.lang.String.class}
- )
- @AndroidOnly("findResources method is not supported, it returns " +
- "empty Enumeration.")
- public void test_findResourcesLjava_lang_String() throws IOException {
- assertFalse(new PackageClassLoader().findResources("hyts_Foo.c").
- hasMoreElements());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "findSystemClass",
- args = {java.lang.String.class}
- )
- public void test_findSystemClass() {
- PackageClassLoader pcl = new PackageClassLoader();
-
- Class [] classes = { String.class, A.class, PublicTestClass.class,
- TestAnnotation.class, TestClass1.class };
-
- for(Class clazz:classes) {
- try {
- String className = clazz.getName();
- assertEquals(clazz, pcl.findSystemClazz(className));
- } catch(ClassNotFoundException cnfe) {
- fail("ClassNotFoundException was thrown: " + cnfe.getMessage());
- }
- }
- try {
- pcl.findSystemClazz("unknownClass");
- fail("ClassNotFoundException was not thrown.");
- } catch(ClassNotFoundException cnfe) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "findLoadedClass",
- args = {java.lang.String.class }
- )
- public void test_findLoadedClass() {
- PackageClassLoader pcl = new PackageClassLoader();
-
- Class [] classes = { A.class, PublicTestClass.class,
- TestAnnotation.class, TestClass1.class };
-
- for(Class clazz:classes) {
- String className = clazz.getName();
- assertNull(pcl.findLoadedClazz(className));
- }
-
- assertNull(pcl.findLoadedClazz("unknownClass"));
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "setClassAssertionStatus is not supported.",
- method = "setClassAssertionStatus",
- args = {java.lang.String.class, boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "setDefaultAssertionStatus is not supported.",
- method = "setDefaultAssertionStatus",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "setPackageAssertionStatus is not supported.",
- method = "setPackageAssertionStatus",
- args = {java.lang.String.class, boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "resolveClass is not supported.",
- method = "resolveClass",
- args = {java.lang.Class.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "setSigners is not supported.",
- method = "setSigners",
- args = {java.lang.Class.class, java.lang.Object[].class}
- )
- })
- public void test_notSupported() {
- getClass().getClassLoader().setClassAssertionStatus(getName(), true);
- getClass().getClassLoader().setDefaultAssertionStatus(true);
- getClass().getClassLoader().setPackageAssertionStatus(
- getClass().getPackage().getName(), true);
- }
-}
-
-class DynamicPolicy extends Policy {
-
- public PermissionCollection pc;
-
- @Override
- public PermissionCollection getPermissions(ProtectionDomain pd) {
- return pc;
- }
-
- @Override
- public PermissionCollection getPermissions(CodeSource codesource) {
- return pc;
- }
-
- @Override
- public void refresh() {
- }
-}
-
-class A {
-}
-
-class Ldr extends ClassLoader {
-
- public static final int TEST_CASE_DEFINE_0 = 0;
- public static final int TEST_CASE_DEFINE_1 = 1;
- public static final int TEST_CASE_DEFINE_2 = 2;
- public static final int TEST_CASE_DEFINE_3 = 3;
-
- @SuppressWarnings("deprecation")
- public Class<?> define(int len, int testCase) throws Exception {
- Package p = getClass().getPackage();
- String path = p == null ? "" : p.getName().replace('.', File.separatorChar)
- + File.separator;
- InputStream is = getResourceAsStream(path + "A.class");
- byte[] buf = new byte[512];
- if(len < 0) len = is.read(buf);
- Class<?> clazz = null;
- String className = "org.apache.harmony.luni.tests.java.lang.A";
- switch(testCase) {
- case TEST_CASE_DEFINE_0:
- clazz = defineClass(className, buf, 0, len);
- break;
- case TEST_CASE_DEFINE_1:
- clazz = defineClass(buf, 0, len);
- break;
- case TEST_CASE_DEFINE_2:
- clazz = defineClass(className, buf, 0, len,
- getClass().getProtectionDomain());
- break;
- case TEST_CASE_DEFINE_3:
- ByteBuffer bb = ByteBuffer.wrap(buf);
- clazz = defineClass(className,
- bb, getClass().getProtectionDomain());
- break;
- }
- return clazz;
- }
-
- public Class<?> define(int testCase) throws Exception {
- return define(-1, testCase);
- }
-
-}
-
-class PackageClassLoader extends ClassLoader {
- public PackageClassLoader() {
- super();
- }
-
- public Package definePackage(String name,
- String specTitle,
- String specVersion,
- String specVendor,
- String implTitle,
- String implVersion,
- String implVendor,
- URL sealBase)
- throws IllegalArgumentException {
- return super.definePackage(name, specTitle, specVersion,
- specVendor, implTitle, implVersion, implVendor, sealBase);
- }
-
- public Package getPackage(String name) {
- return super.getPackage(name);
- }
-
- public Package[] getPackages() {
- return super.getPackages();
- }
-
- public Class<?> findClass(String name)
- throws ClassNotFoundException {
- return super.findClass(name);
- }
-
- public String findLibrary(String libname) {
- return super.findLibrary(libname);
- }
-
- public Class<?> loadClass(String name, boolean resolve)
- throws ClassNotFoundException {
- return super.loadClass(name, resolve);
- }
-
- public URL findResource(String name) {
- return super.findResource(name);
- }
-
- public Enumeration<URL> findResources(String resName)
- throws IOException {
- return super.findResources(resName);
- }
-
- public Class<?> findSystemClazz(String name) throws ClassNotFoundException {
- return super.findSystemClass(name);
- }
-
- public Class<?> findLoadedClazz(String name) {
- return super.findLoadedClass(name);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassNotFoundExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassNotFoundExceptionTest.java
deleted file mode 100644
index b8051cc..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassNotFoundExceptionTest.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(ClassNotFoundException.class)
-public class ClassNotFoundExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.ClassNotFoundException#ClassNotFoundException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ClassNotFoundException",
- args = {}
- )
- public void test_Constructor() {
- ClassNotFoundException e = new ClassNotFoundException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.ClassNotFoundException#ClassNotFoundException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ClassNotFoundException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- ClassNotFoundException e = new ClassNotFoundException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ClassNotFoundException",
- args = {java.lang.String.class, java.lang.Throwable.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_Throwable() {
- String testMessage = "Test Message";
- Throwable thr = new Throwable();
- ClassNotFoundException cnfe = new ClassNotFoundException(testMessage, thr);
- assertEquals(testMessage, cnfe.getMessage());
- assertEquals(thr, cnfe.getException());
-
- cnfe = new ClassNotFoundException(null, thr);
- assertNull(cnfe.getMessage());
- assertEquals(thr, cnfe.getException());
-
- cnfe = new ClassNotFoundException(testMessage, null);
- assertNull(cnfe.getException());
- assertEquals(testMessage, cnfe.getMessage());
-
- cnfe = new ClassNotFoundException(null, null);
- assertNull(cnfe.getMessage());
- assertNull(cnfe.getException());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCause",
- args = {}
- )
- public void test_getCause() {
- ClassNotFoundException e = new ClassNotFoundException();
- assertNull(e.getCause());
-
- e = new ClassNotFoundException("Message");
- assertNull(e.getCause());
-
- NullPointerException cause = new NullPointerException();
- Throwable thr = new Throwable(cause);
- e = new ClassNotFoundException("Message", thr);
- assertEquals(thr, e.getCause());
-
- e = new ClassNotFoundException("Message", null);
- assertEquals(null, e.getCause());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getException",
- args = {}
- )
- public void test_getException() {
- ClassNotFoundException e = new ClassNotFoundException();
- assertNull(e.getException());
-
- e = new ClassNotFoundException("Message");
- assertNull(e.getException());
-
- NullPointerException cause = new NullPointerException();
- Throwable thr = new Throwable(cause);
- e = new ClassNotFoundException("Message", thr);
- assertEquals(thr, e.getException());
-
- e = new ClassNotFoundException("Message", null);
- assertEquals(null, e.getException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassTest.java
deleted file mode 100644
index c33a8e3..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassTest.java
+++ /dev/null
@@ -1,2265 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.InputStream;
-import java.io.Serializable;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.lang.reflect.Member;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.security.AccessControlContext;
-import java.security.AccessController;
-import java.security.BasicPermission;
-import java.security.DomainCombiner;
-import java.security.Permission;
-import java.security.PrivilegedAction;
-import java.security.ProtectionDomain;
-import java.security.Security;
-import java.util.AbstractList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.Vector;
-
-import tests.support.resource.Support_Resources;
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.BrokenTest;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@SuppressWarnings("deprecation")
-@TestTargetClass(Class.class)
-public class ClassTest extends junit.framework.TestCase {
-
- public static final String FILENAME =
- ClassTest.class.getPackage().getName().replace('.', '/') +
- "/test#.properties";
-
- final String packageName = getClass().getPackage().getName();
- final String classNameInitError1 = packageName + ".TestClass1";
- final String classNameInitError2 = packageName + ".TestClass1B";
- final String classNameLinkageError = packageName + ".TestClass";
- final String sourceJARfile = "illegalClasses.jar";
- final String illegalClassName = "illegalClass";
-
- static class StaticMember$Class {
- class Member2$A {
- }
- }
-
- class Member$Class {
- class Member3$B {
- }
- }
-
- public static class TestClass {
- @SuppressWarnings("unused")
- private int privField = 1;
-
- public int pubField = 2;
-
- private Object cValue = null;
-
- public Object ack = new Object();
-
- @SuppressWarnings("unused")
- private int privMethod() {
- return 1;
- }
-
- public int pubMethod() {
- return 2;
- }
-
- public Object cValue() {
- return cValue;
- }
-
- public TestClass() {
- }
-
- @SuppressWarnings("unused")
- private TestClass(Object o) {
- }
- }
-
- public static class SubTestClass extends TestClass {
- }
-
- interface Intf1 {
- public int field1 = 1;
- public int field2 = 1;
- void test();
- }
-
- interface Intf2 {
- public int field1 = 1;
- void test();
- }
-
- interface Intf3 extends Intf1 {
- public int field1 = 1;
- }
-
- interface Intf4 extends Intf1, Intf2 {
- public int field1 = 1;
- void test2(int a, Object b);
- }
-
- interface Intf5 extends Intf1 {
- }
-
- class Cls1 implements Intf2 {
- public int field1 = 2;
- public int field2 = 2;
- public void test() {
- }
- }
-
- class Cls2 extends Cls1 implements Intf1 {
- public int field1 = 2;
- @Override
- public void test() {
- }
- }
-
- class Cls3 implements Intf3, Intf4 {
- public void test() {
- }
- public void test2(int a, Object b) {
- }
- }
-
- static class Cls4 {
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAnnotations",
- args = {}
- )
- public void test_getAnnotations() {
- Annotation [] annotations = PublicTestClass.class.getAnnotations();
- assertEquals(1, annotations.length);
- assertEquals(TestAnnotation.class, annotations[0].annotationType());
-
- annotations = ExtendTestClass.class.getAnnotations();
- assertEquals(2, annotations.length);
-
- for(int i = 0; i < annotations.length; i++) {
- Class<? extends Annotation> type = annotations[i].annotationType();
- assertTrue("Annotation's type " + i + ": " + type,
- type.equals(Deprecated.class) ||
- type.equals(TestAnnotation.class));
- }
- }
-
- /**
- * @tests java.lang.Class#forName(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "java.lang.LinkageError can't be checked.",
- method = "forName",
- args = {java.lang.String.class}
- )
- @AndroidOnly("harmony specific: test with " +
- "'org.apache.harmony.luni.tests.java.lang.TestClass1'")
- public void test_forNameLjava_lang_String() throws Exception {
-
- assertSame("Class for name failed for java.lang.Object",
- Object.class, Class.forName("java.lang.Object"));
- assertSame("Class for name failed for [[Ljava.lang.Object;",
- Object[][].class, Class.forName("[[Ljava.lang.Object;"));
-
- assertSame("Class for name failed for [I",
- int[].class, Class.forName("[I"));
-
- try {
- Class.forName("int");
- fail();
- } catch (ClassNotFoundException e) {
- }
-
- try {
- Class.forName("byte");
- fail();
- } catch (ClassNotFoundException e) {
- }
- try {
- Class.forName("char");
- fail();
- } catch (ClassNotFoundException e) {
- }
-
- try {
- Class.forName("void");
- fail();
- } catch (ClassNotFoundException e) {
- }
-
- try {
- Class.forName("short");
- fail();
- } catch (ClassNotFoundException e) {
- }
- try {
- Class.forName("long");
- fail();
- } catch (ClassNotFoundException e) {
- }
-
- try {
- Class.forName("boolean");
- fail();
- } catch (ClassNotFoundException e) {
- }
- try {
- Class.forName("float");
- fail();
- } catch (ClassNotFoundException e) {
- }
- try {
- Class.forName("double");
- fail();
- } catch (ClassNotFoundException e) {
- }
-
- //regression test for JIRA 2162
- try {
- Class.forName("%");
- fail("should throw ClassNotFoundException.");
- } catch (ClassNotFoundException e) {
- }
-
- //Regression Test for HARMONY-3332
- String securityProviderClassName;
- int count = 1;
- while ((securityProviderClassName = Security
- .getProperty("security.provider." + count++)) != null) {
- Class.forName(securityProviderClassName);
- }
-
- try {
- Class.forName(classNameInitError1);
- fail("ExceptionInInitializerError or ClassNotFoundException " +
- "expected.");
- } catch (java.lang.ExceptionInInitializerError ie) {
- // Expected for the RI.
- } catch (java.lang.ClassNotFoundException ce) {
- // Expected for Android.
- }
- }
-
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "",
- method = "forName",
- args = {java.lang.String.class, boolean.class, java.lang.ClassLoader.class}
- )
- public void test_forNameLjava_lang_StringLbooleanLClassLoader() throws Exception {
-
- ClassLoader pcl = getClass().getClassLoader();
-
- Class<?> [] classes = {PublicTestClass.class, ExtendTestClass.class,
- ExtendTestClass1.class, TestInterface.class, String.class};
-
- for(int i = 0; i < classes.length; i++) {
- Class<?> clazz = Class.forName(classes[i].getName(), true, pcl);
- assertEquals(classes[i], clazz);
-
- clazz = Class.forName(classes[i].getName(), false, pcl);
- assertEquals(classes[i], clazz);
- }
-
- for(int i = 0; i < classes.length; i++) {
- Class<?> clazz = Class.forName(classes[i].getName(), true,
- ClassLoader.getSystemClassLoader());
- assertEquals(classes[i], clazz);
-
- clazz = Class.forName(classes[i].getName(), false,
- ClassLoader.getSystemClassLoader());
- assertEquals(classes[i], clazz);
- }
-
- try {
- Class.forName(null, true, pcl);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- try {
- Class.forName("NotExistClass", true, pcl);
- fail("ClassNotFoundException is not thrown for non existent class.");
- } catch(ClassNotFoundException cnfe) {
- //expected
- }
-
- try {
- Class.forName("String", false, pcl);
- fail("ClassNotFoundException is not thrown for non existent class.");
- } catch(ClassNotFoundException cnfe) {
- //expected
- }
-
- try {
- Class.forName("org.apache.harmony.luni.tests.java.PublicTestClass",
- false, pcl);
- fail("ClassNotFoundException is not thrown for non existent class.");
- } catch(ClassNotFoundException cnfe) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "",
- method = "forName",
- args = {java.lang.String.class, boolean.class, java.lang.ClassLoader.class}
- )
- @AndroidOnly("Class.forName method throws ClassNotFoundException on " +
- "Android.")
- public void test_forNameLjava_lang_StringLbooleanLClassLoader_AndroidOnly() throws Exception {
-
- // Android doesn't support loading class files from a jar.
- try {
-
- URL url = getClass().getClassLoader().getResource(
- packageName.replace(".", "/") + "/" + sourceJARfile);
-
- ClassLoader loader = new URLClassLoader(new URL[] { url },
- getClass().getClassLoader());
- try {
- Class.forName(classNameLinkageError, true, loader);
- fail("LinkageError or ClassNotFoundException expected.");
- } catch (java.lang.LinkageError le) {
- // Expected for the RI.
- } catch (java.lang.ClassNotFoundException ce) {
- // Expected for Android.
- }
- } catch(Exception e) {
- fail("Unexpected exception was thrown: " + e.toString());
- }
-
- try {
- Class.forName(classNameInitError2,
- true, getClass().getClassLoader());
- fail("ExceptionInInitializerError or ClassNotFoundException " +
- "should be thrown.");
- } catch (java.lang.ExceptionInInitializerError ie) {
- // Expected for the RI.
- // Remove this comment to let the test pass on Android.
- } catch (java.lang.ClassNotFoundException ce) {
- // Expected for Android.
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAnnotation",
- args = {java.lang.Class.class}
- )
- public void test_getAnnotation() {
- TestAnnotation target = PublicTestClass.class.getAnnotation(TestAnnotation.class);
- assertEquals(target.value(), PublicTestClass.class.getName());
-
- assertNull(PublicTestClass.class.getAnnotation(Deprecated.class));
-
- Deprecated target2 = ExtendTestClass.class.getAnnotation(Deprecated.class);
- assertNotNull(target2);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaredAnnotations",
- args = {}
- )
- public void test_getDeclaredAnnotations() {
- Annotation [] annotations = PublicTestClass.class.getDeclaredAnnotations();
- assertEquals(1, annotations.length);
-
- annotations = ExtendTestClass.class.getDeclaredAnnotations();
- assertEquals(2, annotations.length);
-
- annotations = TestInterface.class.getDeclaredAnnotations();
- assertEquals(0, annotations.length);
-
- annotations = String.class.getDeclaredAnnotations();
- assertEquals(0, annotations.length);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getEnclosingClass",
- args = {}
- )
- public void test_getEnclosingClass() {
- Class clazz = ExtendTestClass.class.getEnclosingClass();
- assertNull(clazz);
-
- assertEquals(getClass(), Cls1.class.getEnclosingClass());
- assertEquals(getClass(), Intf1.class.getEnclosingClass());
- assertEquals(getClass(), Cls4.class.getEnclosingClass());
- }
-
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getEnclosingMethod",
- args = {}
- )
- public void test_getEnclosingMethod() {
- Method clazz = ExtendTestClass.class.getEnclosingMethod();
- assertNull(clazz);
-
- PublicTestClass ptc = new PublicTestClass();
- try {
- assertEquals("getEnclosingMethod returns incorrect method.",
- PublicTestClass.class.getMethod("getLocalClass",
- (Class []) null),
- ptc.getLocalClass().getClass().getEnclosingMethod());
- } catch(NoSuchMethodException nsme) {
- fail("NoSuchMethodException was thrown.");
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getEnclosingConstructor",
- args = {}
- )
- public void test_getEnclosingConstructor() {
-
- PublicTestClass ptc = new PublicTestClass();
-
- assertEquals("getEnclosingConstructor method returns incorrect class.",
- PublicTestClass.class.getConstructors()[0],
- ptc.clazz.getClass().getEnclosingConstructor());
-
- assertNull("getEnclosingConstructor should return null for local " +
- "class declared in method.",
- ptc.getLocalClass().getClass().getEnclosingConstructor());
-
- assertNull("getEnclosingConstructor should return null for local " +
- "class declared in method.",
- ExtendTestClass.class.getEnclosingConstructor());
- }
-
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getEnumConstants",
- args = {}
- )
- public void test_getEnumConstants() {
- Object [] clazz = ExtendTestClass.class.getEnumConstants();
- assertNull(clazz);
- Object [] constants = TestEnum.class.getEnumConstants();
- assertEquals(TestEnum.values().length, constants.length);
- for(int i = 0; i < constants.length; i++) {
- assertEquals(TestEnum.values()[i], constants[i]);
- }
- assertEquals(0, TestEmptyEnum.class.getEnumConstants().length);
- }
- public enum TestEnum {
- ONE, TWO, THREE
- }
- public enum TestEmptyEnum {
- }
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "GenericSignatureFormatError, TypeNotPresentException, " +
- "MalformedParameterizedTypeException are not verified.",
- method = "getGenericInterfaces",
- args = {}
- )
- public void test_getGenericInterfaces() {
- Type [] types = ExtendTestClass1.class.getGenericInterfaces();
- assertEquals(0, types.length);
-
- Class [] interfaces = {TestInterface.class, Serializable.class,
- Cloneable.class};
- types = PublicTestClass.class.getGenericInterfaces();
- assertEquals(interfaces.length, types.length);
- for(int i = 0; i < types.length; i++) {
- assertEquals(interfaces[i], types[i]);
- }
-
- types = TestInterface.class.getGenericInterfaces();
- assertEquals(0, types.length);
-
- types = List.class.getGenericInterfaces();
- assertEquals(1, types.length);
- assertEquals(Collection.class, ((ParameterizedType)types[0]).getRawType());
-
- assertEquals(0, int.class.getGenericInterfaces().length);
- assertEquals(0, void.class.getGenericInterfaces().length);
- }
-
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "GenericSignatureFormatError, TypeNotPresentException, MalformedParameterizedTypeException are not verified.",
- method = "getGenericSuperclass",
- args = {}
- )
- public void test_getGenericSuperclass () {
- assertEquals(PublicTestClass.class,
- ExtendTestClass.class.getGenericSuperclass());
- assertEquals(ExtendTestClass.class,
- ExtendTestClass1.class.getGenericSuperclass());
- assertEquals(Object.class, PublicTestClass.class.getGenericSuperclass());
- assertEquals(Object.class, String.class.getGenericSuperclass());
- assertEquals(null, TestInterface.class.getGenericSuperclass());
-
- ParameterizedType type = (ParameterizedType) Vector.class.getGenericSuperclass();
- assertEquals(AbstractList.class, type.getRawType());
- }
-
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- method = "getPackage",
- args = {}
- )
- @AndroidOnly("Uses dalvik.system.PathClassLoader.")
- public void test_getPackage() {
-
- Package thisPackage = getClass().getPackage();
- assertEquals("org.apache.harmony.luni.tests.java.lang",
- thisPackage.getName());
-
- Package stringPackage = String.class.getPackage();
- assertNotNull("java.lang", stringPackage.getName());
-
- String hyts_package_name = "hyts_package_dex.jar";
- File resources = Support_Resources.createTempFolder();
- Support_Resources.copyFile(resources, "Package", hyts_package_name);
-
- String resPath = resources.toString();
- if (resPath.charAt(0) == '/' || resPath.charAt(0) == '\\')
- resPath = resPath.substring(1);
-
- try {
-
- URL resourceURL = new URL("file:/" + resPath + "/Package/"
- + hyts_package_name);
-
- ClassLoader cl = new dalvik.system.PathClassLoader(
- resourceURL.getPath(), getClass().getClassLoader());
-
- Class clazz = cl.loadClass("C");
- assertNull("getPackage for C.class should return null",
- clazz.getPackage());
-
- clazz = cl.loadClass("a.b.C");
- Package cPackage = clazz.getPackage();
- assertNotNull("getPackage for a.b.C.class should not return null",
- cPackage);
-
- /*
- * URLClassLoader doesn't work on Android for jar files
- *
- * URL url = getClass().getClassLoader().getResource(
- * packageName.replace(".", "/") + "/" + sourceJARfile);
- *
- * ClassLoader loader = new URLClassLoader(new URL[] { url }, null);
- *
- * try {
- * Class<?> clazz = loader.loadClass(illegalClassName);
- * Package pack = clazz.getPackage();
- * assertNull(pack);
- * } catch(ClassNotFoundException cne) {
- * fail("ClassNotFoundException was thrown for " + illegalClassName);
- * }
- */
- } catch(Exception e) {
- fail("Unexpected exception was thrown: " + e.toString());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "getProtectionDomain",
- args = {}
- )
- @BrokenTest("There is no protection domain set in Android.")
- public void test_getProtectionDomain() {
- ProtectionDomain pd = PublicTestClass.class.getProtectionDomain();
- assertNotNull("Test 1: Protection domain expected to be set.", pd);
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals("getProtectionDomain")) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- PublicTestClass.class.getProtectionDomain();
- fail("Test 2: SecurityException expected.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "",
- method = "getSigners",
- args = {}
- )
- public void test_getSigners() {
- assertNull(void.class.getSigners());
- assertNull(PublicTestClass.class.getSigners());
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSimpleName",
- args = {}
- )
- public void test_getSimpleName() {
- assertEquals("PublicTestClass", PublicTestClass.class.getSimpleName());
- assertEquals("void", void.class.getSimpleName());
- assertEquals("int[]", int[].class.getSimpleName());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTypeParameters",
- args = {}
- )
- public void test_getTypeParameters() {
- assertEquals(0, PublicTestClass.class.getTypeParameters().length);
- TypeVariable [] tv = TempTestClass1.class.getTypeParameters();
- assertEquals(1, tv.length);
- assertEquals(Object.class, tv[0].getBounds()[0]);
-
- TempTestClass2<String> tc = new TempTestClass2<String>();
- tv = tc.getClass().getTypeParameters();
- assertEquals(1, tv.length);
- assertEquals(String.class, tv[0].getBounds()[0]);
- }
-
- class TempTestClass1<T> {
- }
-
- class TempTestClass2<S extends String> extends TempTestClass1<S> {
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isAnnotation",
- args = {}
- )
- public void test_isAnnotation() {
- assertTrue(Deprecated.class.isAnnotation());
- assertTrue(TestAnnotation.class.isAnnotation());
- assertFalse(PublicTestClass.class.isAnnotation());
- assertFalse(String.class.isAnnotation());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isAnnotationPresent",
- args = {java.lang.Class.class}
- )
- public void test_isAnnotationPresent() {
- assertTrue(PublicTestClass.class.isAnnotationPresent(TestAnnotation.class));
- assertFalse(ExtendTestClass1.class.isAnnotationPresent(TestAnnotation.class));
- assertFalse(String.class.isAnnotationPresent(Deprecated.class));
- assertTrue(ExtendTestClass.class.isAnnotationPresent(TestAnnotation.class));
- assertTrue(ExtendTestClass.class.isAnnotationPresent(Deprecated.class));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isAnonymousClass",
- args = {}
- )
- public void test_isAnonymousClass() {
- assertFalse(PublicTestClass.class.isAnonymousClass());
- assertTrue((new Thread() {}).getClass().isAnonymousClass());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isEnum",
- args = {}
- )
- public void test_isEnum() {
- assertFalse(PublicTestClass.class.isEnum());
- assertFalse(ExtendTestClass.class.isEnum());
- assertTrue(TestEnum.ONE.getClass().isEnum());
- assertTrue(TestEnum.class.isEnum());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isLocalClass",
- args = {}
- )
- public void test_isLocalClass() {
- assertFalse(ExtendTestClass.class.isLocalClass());
- assertFalse(TestInterface.class.isLocalClass());
- assertFalse(TestEnum.class.isLocalClass());
- class InternalClass {}
- assertTrue(InternalClass.class.isLocalClass());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMemberClass",
- args = {}
- )
- public void test_isMemberClass() {
- assertFalse(ExtendTestClass.class.isMemberClass());
- assertFalse(TestInterface.class.isMemberClass());
- assertFalse(String.class.isMemberClass());
- assertTrue(TestEnum.class.isMemberClass());
- assertTrue(StaticMember$Class.class.isMemberClass());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isSynthetic",
- args = {}
- )
- public void test_isSynthetic() {
- assertFalse("Returned true for non synthetic class.",
- ExtendTestClass.class.isSynthetic());
- assertFalse("Returned true for non synthetic class.",
- TestInterface.class.isSynthetic());
- assertFalse("Returned true for non synthetic class.",
- String.class.isSynthetic());
-
- String className = "org.apache.harmony.luni.tests.java.lang.ClassLoaderTest$1";
-
- /*
- *try {
- * assertTrue("Returned false for synthetic class.",
- * getClass().getClassLoader().loadClass(className).
- * isSynthetic());
- *} catch(ClassNotFoundException cnfe) {
- * fail("Class " + className + " can't be found.");
- *}
- */
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isInstance",
- args = {java.lang.Object.class}
- )
- public void test_isInstance() {
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCanonicalName",
- args = {}
- )
- public void test_getCanonicalName() {
- String name = int[].class.getCanonicalName();
- Class [] classArray = { int.class, int[].class, String.class,
- PublicTestClass.class, TestInterface.class,
- ExtendTestClass.class };
- String [] classNames = {"int", "int[]", "java.lang.String",
- "org.apache.harmony.luni.tests.java.lang.PublicTestClass",
- "org.apache.harmony.luni.tests.java.lang.TestInterface",
- "org.apache.harmony.luni.tests.java.lang.ExtendTestClass"};
-
- for(int i = 0; i < classArray.length; i++) {
- assertEquals(classNames[i], classArray[i].getCanonicalName());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getClassLoader",
- args = {}
- )
- public void test_getClassLoader() {
-
- assertEquals(ExtendTestClass.class.getClassLoader(),
- PublicTestClass.class.getClassLoader());
-
- assertNull(int.class.getClassLoader());
- assertNull(void.class.getClassLoader());
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if ((perm instanceof RuntimePermission) &&
- perm.getName().equals("getClassLoader")) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- System.class.getClassLoader();
- } catch (SecurityException e) {
- fail("SecurityException should not be thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Class#getClasses()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getClasses",
- args = {}
- )
- public void test_getClasses() {
- assertEquals("Incorrect class array returned",
- 4, ClassTest.class.getClasses().length);
- }
-
- /**
- * @tests java.lang.Class#getClasses()
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- method = "getClasses",
- args = {}
- )
- @BrokenTest("Class.forName does not work with an URLClassLoader; " +
- "the VMClassLoader does not support loading classes from a " +
- "(jar) byte array.")
- public void test_getClasses_subtest0() {
- final Permission privCheckPermission = new BasicPermission("Privilege check") {
- private static final long serialVersionUID = 1L;
- };
-
- class MyCombiner implements DomainCombiner {
- boolean combine;
-
- public ProtectionDomain[] combine(ProtectionDomain[] executionDomains,
- ProtectionDomain[] parentDomains) {
- combine = true;
- return new ProtectionDomain[0];
- }
-
- private boolean recurring = false;
-
- public boolean isPriviledged() {
- if (recurring) {
- return true;
- }
- try {
- recurring = true;
- combine = false;
- try {
- AccessController.checkPermission(privCheckPermission);
- } catch (SecurityException e) {}
- return !combine;
- } finally {
- recurring = false;
- }
- }
- }
-
- final MyCombiner combiner = new MyCombiner();
- class SecurityManagerCheck extends SecurityManager {
- String reason;
-
- Class<?> checkClass;
-
- int checkType;
-
- int checkPermission;
-
- int checkMemberAccess;
-
- int checkPackageAccess;
-
- public void setExpected(String reason, Class<?> cls, int type) {
- this.reason = reason;
- checkClass = cls;
- checkType = type;
- checkPermission = 0;
- checkMemberAccess = 0;
- checkPackageAccess = 0;
- }
-
- @Override
- public void checkPermission(Permission perm) {
- if (combiner.isPriviledged())
- return;
- checkPermission++;
- }
-
- @Override
- public void checkMemberAccess(Class<?> cls, int type) {
- if (combiner.isPriviledged())
- return;
- checkMemberAccess++;
- assertEquals(reason + " unexpected class", checkClass, cls);
- assertEquals(reason + "unexpected type", checkType, type);
- }
-
- @Override
- public void checkPackageAccess(String packageName) {
- if (combiner.isPriviledged())
- return;
- checkPackageAccess++;
- String name = checkClass.getName();
- int index = name.lastIndexOf('.');
- String checkPackage = name.substring(0, index);
- assertEquals(reason + " unexpected package",
- checkPackage, packageName);
- }
-
- public void assertProperCalls() {
- assertEquals(reason + " unexpected checkPermission count",
- 0, checkPermission);
- assertEquals(reason + " unexpected checkMemberAccess count",
- 1, checkMemberAccess);
- assertEquals(reason + " unexpected checkPackageAccess count",
- 1, checkPackageAccess);
- }
- }
-
- AccessControlContext acc = new AccessControlContext(new ProtectionDomain[0]);
- AccessControlContext acc2 = new AccessControlContext(acc, combiner);
-
- PrivilegedAction<?> action = new PrivilegedAction<Object>() {
- public Object run() {
- File resources = Support_Resources.createTempFolder();
- try {
- Support_Resources.copyFile(resources, null, "hyts_security.jar");
- File file = new File(resources.toString() + "/hyts_security.jar");
- URL url = new URL("file:" + file.getPath());
- ClassLoader loader = new URLClassLoader(new URL[] { url }, null);
- Class<?> cls = Class.forName("packB.SecurityTestSub", false, loader);
- SecurityManagerCheck sm = new SecurityManagerCheck();
- System.setSecurityManager(sm);
- try {
- sm.setExpected("getClasses", cls, Member.PUBLIC);
- cls.getClasses();
- sm.assertProperCalls();
-
- sm.setExpected("getDeclaredClasses", cls, Member.DECLARED);
- cls.getDeclaredClasses();
- sm.assertProperCalls();
-
- sm.setExpected("getConstructor", cls, Member.PUBLIC);
- cls.getConstructor(new Class[0]);
- sm.assertProperCalls();
-
- sm.setExpected("getConstructors", cls, Member.PUBLIC);
- cls.getConstructors();
- sm.assertProperCalls();
-
- sm.setExpected("getDeclaredConstructor", cls, Member.DECLARED);
- cls.getDeclaredConstructor(new Class[0]);
- sm.assertProperCalls();
-
- sm.setExpected("getDeclaredConstructors", cls, Member.DECLARED);
- cls.getDeclaredConstructors();
- sm.assertProperCalls();
-
- sm.setExpected("getField", cls, Member.PUBLIC);
- cls.getField("publicField");
- sm.assertProperCalls();
-
- sm.setExpected("getFields", cls, Member.PUBLIC);
- cls.getFields();
- sm.assertProperCalls();
-
- sm.setExpected("getDeclaredField", cls, Member.DECLARED);
- cls.getDeclaredField("publicField");
- sm.assertProperCalls();
-
- sm.setExpected("getDeclaredFields", cls, Member.DECLARED);
- cls.getDeclaredFields();
- sm.assertProperCalls();
-
- sm.setExpected("getDeclaredMethod", cls, Member.DECLARED);
- cls.getDeclaredMethod("publicMethod", new Class[0]);
- sm.assertProperCalls();
-
- sm.setExpected("getDeclaredMethods", cls, Member.DECLARED);
- cls.getDeclaredMethods();
- sm.assertProperCalls();
-
- sm.setExpected("getMethod", cls, Member.PUBLIC);
- cls.getMethod("publicMethod", new Class[0]);
- sm.assertProperCalls();
-
- sm.setExpected("getMethods", cls, Member.PUBLIC);
- cls.getMethods();
- sm.assertProperCalls();
-
- sm.setExpected("newInstance", cls, Member.PUBLIC);
- cls.newInstance();
- sm.assertProperCalls();
- } finally {
- System.setSecurityManager(null);
- }
-/* Remove this comment to let the test pass on Android.
- } catch (java.lang.ClassNotFoundException ce) {
- // Expected for Android.
-*/
- } catch (Exception e) {
- if (e instanceof RuntimeException)
- throw (RuntimeException) e;
- fail("unexpected exception: " + e);
- }
- return null;
- }
- };
- AccessController.doPrivileged(action, acc2);
- }
-
- /**
- * @tests java.lang.Class#getComponentType()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getComponentType",
- args = {}
- )
- public void test_getComponentType() {
- assertSame("int array does not have int component type", int.class, int[].class
- .getComponentType());
- assertSame("Object array does not have Object component type", Object.class,
- Object[].class.getComponentType());
- assertNull("Object has non-null component type", Object.class.getComponentType());
- }
-
- /**
- * @tests java.lang.Class#getConstructor(java.lang.Class[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getConstructor",
- args = {java.lang.Class[].class}
- )
- public void test_getConstructor$Ljava_lang_Class()
- throws NoSuchMethodException {
- Constructor constr = TestClass.class.getConstructor(new Class[0]);
- assertNotNull(constr);
- assertEquals("org.apache.harmony.luni.tests.java.lang.ClassTest$TestClass",
- constr.getName());
- try {
- TestClass.class.getConstructor(Object.class);
- fail("Found private constructor");
- } catch (NoSuchMethodException e) {
- // Correct - constructor with obj is private
- }
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- TestClass.class.getConstructor(new Class[0]);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Class#getConstructors()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getConstructors",
- args = {}
- )
- public void test_getConstructors() throws Exception {
- Constructor[] c = TestClass.class.getConstructors();
- assertEquals("Incorrect number of constructors returned", 1, c.length);
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- TestClass.class.getConstructors();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Class#getDeclaredClasses()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaredClasses",
- args = {}
- )
- public void test_getDeclaredClasses() {
-
- Class [] declClasses = Object.class.getDeclaredClasses();
- assertEquals("Incorrect length of declared classes array is returned " +
- "for Object.", 0, declClasses.length);
-
- declClasses = PublicTestClass.class.getDeclaredClasses();
- assertEquals(2, declClasses.length);
-
- assertEquals(0, int.class.getDeclaredClasses().length);
- assertEquals(0, void.class.getDeclaredClasses().length);
-
- for(int i = 0; i < declClasses.length; i++) {
- Constructor<?> constr = declClasses[i].getDeclaredConstructors()[0];
- constr.setAccessible(true);
- PublicTestClass publicClazz = new PublicTestClass();
- try {
- Object o = constr.newInstance(publicClazz);
- assertTrue("Returned incorrect class: " + o.toString(),
- o.toString().startsWith("PrivateClass"));
- } catch(Exception e) {
- fail("Unexpected exception was thrown: " + e.toString());
- }
- }
-
-
- declClasses = TestInterface.class.getDeclaredClasses();
- assertEquals(0, declClasses.length);
-
- SecurityManager sm = new SecurityManager() {
-
- final String forbidenPermissionName = "user.dir";
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals(forbidenPermissionName)) {
- throw new SecurityException();
- }
- }
-
- public void checkMemberAccess(Class<?> clazz,
- int which) {
- if(clazz.equals(TestInterface.class)) {
- throw new SecurityException();
- }
- }
-
- public void checkPackageAccess(String pkg) {
- if(pkg.equals(PublicTestClass.class.getPackage())) {
- throw new SecurityException();
- }
- }
-
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- TestInterface.class.getDeclaredClasses();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- }
-
-
- /**
- * @tests java.lang.Class#getDeclaredConstructor(java.lang.Class[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaredConstructor",
- args = {java.lang.Class[].class}
- )
- public void test_getDeclaredConstructor$Ljava_lang_Class() throws Exception {
- Constructor<TestClass> c = TestClass.class.getDeclaredConstructor(new Class[0]);
- assertNull("Incorrect constructor returned", c.newInstance().cValue());
- c = TestClass.class.getDeclaredConstructor(Object.class);
-
- try {
- TestClass.class.getDeclaredConstructor(String.class);
- fail("NoSuchMethodException should be thrown.");
- } catch(NoSuchMethodException nsme) {
- //expected
- }
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- TestClass.class.getDeclaredConstructor(Object.class);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Class#getDeclaredConstructors()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaredConstructors",
- args = {}
- )
- public void test_getDeclaredConstructors() throws Exception {
- Constructor[] c = TestClass.class.getDeclaredConstructors();
- assertEquals("Incorrect number of constructors returned", 2, c.length);
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- TestClass.class.getDeclaredConstructors();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Class#getDeclaredField(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaredField",
- args = {java.lang.String.class}
- )
- public void test_getDeclaredFieldLjava_lang_String() throws Exception {
- Field f = TestClass.class.getDeclaredField("pubField");
- assertEquals("Returned incorrect field", 2, f.getInt(new TestClass()));
-
- try {
- TestClass.class.getDeclaredField(null);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- try {
- TestClass.class.getDeclaredField("NonExistentField");
- fail("NoSuchFieldException is not thrown.");
- } catch(NoSuchFieldException nsfe) {
- //expected
- }
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- TestClass.class.getDeclaredField("pubField");
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Class#getDeclaredFields()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaredFields",
- args = {}
- )
- public void test_getDeclaredFields() throws Exception {
- Field[] f = TestClass.class.getDeclaredFields();
- assertEquals("Returned incorrect number of fields", 4, f.length);
- f = SubTestClass.class.getDeclaredFields();
- // Declared fields do not include inherited
- assertEquals("Returned incorrect number of fields", 0, f.length);
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- TestClass.class.getDeclaredFields();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Class#getDeclaredMethod(java.lang.String,
- * java.lang.Class[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaredMethod",
- args = {java.lang.String.class, java.lang.Class[].class}
- )
- public void test_getDeclaredMethodLjava_lang_String$Ljava_lang_Class() throws Exception {
- Method m = TestClass.class.getDeclaredMethod("pubMethod", new Class[0]);
- assertEquals("Returned incorrect method", 2, ((Integer) (m.invoke(new TestClass())))
- .intValue());
- m = TestClass.class.getDeclaredMethod("privMethod", new Class[0]);
-
- try {
- TestClass.class.getDeclaredMethod(null, new Class[0]);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- try {
- TestClass.class.getDeclaredMethod("NonExistentMethod", new Class[0]);
- fail("NoSuchMethodException is not thrown.");
- } catch(NoSuchMethodException nsme) {
- //expected
- }
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- TestClass.class.getDeclaredMethod("pubMethod", new Class[0]);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Class#getDeclaredMethods()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaredMethods",
- args = {}
- )
- public void test_getDeclaredMethods() throws Exception {
- Method[] m = TestClass.class.getDeclaredMethods();
- assertEquals("Returned incorrect number of methods", 3, m.length);
- m = SubTestClass.class.getDeclaredMethods();
- assertEquals("Returned incorrect number of methods", 0, m.length);
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- TestClass.class.getDeclaredMethods();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Class#getDeclaringClass()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaringClass",
- args = {}
- )
- public void test_getDeclaringClass() {
- assertEquals(ClassTest.class, TestClass.class.getDeclaringClass());
- assertNull(PublicTestClass.class.getDeclaringClass());
- }
-
- /**
- * @tests java.lang.Class#getField(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getField",
- args = {java.lang.String.class}
- )
- public void test_getFieldLjava_lang_String() throws Exception {
- Field f = TestClass.class.getField("pubField");
- assertEquals("Returned incorrect field", 2, f.getInt(new TestClass()));
-
- f = PublicTestClass.class.getField("TEST_FIELD");
- assertEquals("Returned incorrect field", "test field",
- f.get(new PublicTestClass()));
-
- f = PublicTestClass.class.getField("TEST_INTERFACE_FIELD");
- assertEquals("Returned incorrect field", 0,
- f.getInt(new PublicTestClass()));
-
- try {
- f = TestClass.class.getField("privField");
- fail("Private field access failed to throw exception");
- } catch (NoSuchFieldException e) {
- // Correct
- }
-
- try {
- TestClass.class.getField(null);
- fail("NullPointerException is thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- SecurityManager sm = new SecurityManager() {
-
- final String forbidenPermissionName = "user.dir";
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals(forbidenPermissionName)) {
- throw new SecurityException();
- }
- }
-
- public void checkMemberAccess(Class<?> clazz,
- int which) {
- if(clazz.equals(TestClass.class)) {
- throw new SecurityException();
- }
- }
-
- public void checkPackageAccess(String pkg) {
- if(pkg.equals(TestClass.class.getPackage())) {
- throw new SecurityException();
- }
- }
-
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- TestClass.class.getField("pubField");
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Class#getFields()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getFields",
- args = {}
- )
- public void test_getFields2() throws Exception {
- Field[] f;
- Field expected = null;
-
- f = PublicTestClass.class.getFields();
- assertEquals("Test 1: Incorrect number of fields;", 2, f.length);
-
- f = Cls2.class.getFields();
- assertEquals("Test 2: Incorrect number of fields;", 6, f.length);
-
- f = Cls3.class.getFields();
- assertEquals("Test 2: Incorrect number of fields;", 5, f.length);
-
- for (Field field : f) {
- if (field.toString().equals("public static final int org.apache" +
- ".harmony.luni.tests.java.lang.ClassTest$Intf3.field1")) {
- expected = field;
- break;
- }
- }
- if (expected == null) {
- fail("Test 3: getFields() did not return all fields.");
- }
- assertEquals("Test 4: Incorrect field;", expected,
- Cls3.class.getField("field1"));
-
- expected = null;
- for (Field field : f) {
- if(field.toString().equals("public static final int org.apache" +
- ".harmony.luni.tests.java.lang.ClassTest$Intf1.field2")) {
- expected = field;
- break;
- }
- }
- if (expected == null) {
- fail("Test 5: getFields() did not return all fields.");
- }
- assertEquals("Test 6: Incorrect field;", expected,
- Cls3.class.getField("field2"));
- }
-
- /**
- * @tests java.lang.Class#getFields()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getFields",
- args = {}
- )
- public void test_getFields() throws Exception {
- Field[] f = TestClass.class.getFields();
- assertEquals("Test 1: Incorrect number of fields;", 2, f.length);
- f = SubTestClass.class.getFields();
- // Check inheritance of pub fields
- assertEquals("Test 2: Incorrect number of fields;", 2, f.length);
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- TestClass.class.getFields();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- Field expected = null;
- Field[] fields = Cls2.class.getFields();
- for (Field field : fields) {
- if(field.toString().equals("public int org.apache.harmony.luni" +
- ".tests.java.lang.ClassTest$Cls2.field1")) {
- expected = field;
- break;
- }
- }
- if (expected == null) {
- fail("getFields() did not return all fields");
- }
- assertEquals(expected, Cls2.class.getField("field1"));
- }
-
- /**
- * @tests java.lang.Class#getInterfaces()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInterfaces",
- args = {}
- )
- public void test_getInterfaces() {
- Class[] interfaces;
- List<?> interfaceList;
- interfaces = Object.class.getInterfaces();
- assertEquals("Incorrect interface list for Object", 0, interfaces.length);
- interfaceList = Arrays.asList(Vector.class.getInterfaces());
- assertTrue("Incorrect interface list for Vector", interfaceList
- .contains(Cloneable.class)
- && interfaceList.contains(Serializable.class)
- && interfaceList.contains(List.class));
-
- Class [] interfaces1 = Cls1.class.getInterfaces();
- assertEquals(1, interfaces1.length);
- assertEquals(Intf2.class, interfaces1[0]);
-
- Class [] interfaces2 = Cls2.class.getInterfaces();
- assertEquals(1, interfaces2.length);
- assertEquals(Intf1.class, interfaces2[0]);
-
- Class [] interfaces3 = Cls3.class.getInterfaces();
- assertEquals(2, interfaces3.length);
- assertEquals(Intf3.class, interfaces3[0]);
- assertEquals(Intf4.class, interfaces3[1]);
-
- Class [] interfaces4 = Cls4.class.getInterfaces();
- assertEquals(0, interfaces4.length);
- }
-
- /**
- * @tests java.lang.Class#getMethod(java.lang.String, java.lang.Class[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMethod",
- args = {java.lang.String.class, java.lang.Class[].class}
- )
- public void test_getMethodLjava_lang_String$Ljava_lang_Class() throws Exception {
- Method m = TestClass.class.getMethod("pubMethod", new Class[0]);
- assertEquals("Returned incorrect method", 2, ((Integer) (m.invoke(new TestClass())))
- .intValue());
-
- m = ExtendTestClass1.class.getMethod("getCount", new Class[0]);
- assertEquals("Returned incorrect method", 0, ((Integer) (m.invoke(new ExtendTestClass1())))
- .intValue());
-
- try {
- m = TestClass.class.getMethod("privMethod", new Class[0]);
- fail("Failed to throw exception accessing private method");
- } catch (NoSuchMethodException e) {
- // Correct
- return;
- }
-
- try {
- m = TestClass.class.getMethod("init", new Class[0]);
- fail("Failed to throw exception accessing to init method");
- } catch (NoSuchMethodException e) {
- // Correct
- return;
- }
-
- try {
- TestClass.class.getMethod("pubMethod", new Class[0]);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- TestClass.class.getMethod("pubMethod", new Class[0]);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Class#getMethods()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMethods",
- args = {}
- )
- public void test_getMethods() throws Exception {
- Method[] m = TestClass.class.getMethods();
- assertEquals("Returned incorrect number of methods",
- 2 + Object.class.getMethods().length, m.length);
- m = SubTestClass.class.getMethods();
- assertEquals("Returned incorrect number of sub-class methods",
- 2 + Object.class.getMethods().length, m.length);
- // Number of inherited methods
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- TestClass.class.getMethods();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- assertEquals("Incorrect number of methods", 10,
- Cls2.class.getMethods().length);
- assertEquals("Incorrect number of methods", 11,
- Cls3.class.getMethods().length);
-
- Method expected = null;
- Method[] methods = Cls2.class.getMethods();
- for (Method method : methods) {
- if(method.toString().equals("public void org.apache.harmony.luni" +
- ".tests.java.lang.ClassTest$Cls2.test()")) {
- expected = method;
- break;
- }
- }
- if (expected == null) {
- fail("getMethods() did not return all methods");
- }
- assertEquals(expected, Cls2.class.getMethod("test"));
-
- expected = null;
- methods = Cls3.class.getMethods();
- for (Method method : methods) {
- if(method.toString().equals("public void org.apache.harmony.luni" +
- ".tests.java.lang.ClassTest$Cls3.test()")) {
- expected = method;
- break;
- }
- }
- if (expected == null) {
- fail("getMethods() did not return all methods");
- }
- assertEquals(expected, Cls3.class.getMethod("test"));
-
- expected = null;
- methods = Cls3.class.getMethods();
- for (Method method : methods) {
- if(method.toString().equals("public void org.apache.harmony.luni" +
- ".tests.java.lang.ClassTest$Cls3.test2(int," +
- "java.lang.Object)")) {
- expected = method;
- break;
- }
- }
- if (expected == null) {
- fail("getMethods() did not return all methods");
- }
-
- assertEquals(expected, Cls3.class.getMethod("test2", int.class,
- Object.class));
-
- assertEquals("Incorrect number of methods", 1,
- Intf5.class.getMethods().length);
- }
-
- private static final class PrivateClass {
- }
- /**
- * @tests java.lang.Class#getModifiers()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getModifiers",
- args = {}
- )
- public void test_getModifiers() {
- int dcm = PrivateClass.class.getModifiers();
- assertFalse("default class is public", Modifier.isPublic(dcm));
- assertFalse("default class is protected", Modifier.isProtected(dcm));
- assertTrue("default class is not private", Modifier.isPrivate(dcm));
-
- int ocm = Object.class.getModifiers();
- assertTrue("public class is not public", Modifier.isPublic(ocm));
- assertFalse("public class is protected", Modifier.isProtected(ocm));
- assertFalse("public class is private", Modifier.isPrivate(ocm));
- }
-
- /**
- * @tests java.lang.Class#getName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getName",
- args = {}
- )
- public void test_getName() throws Exception {
- String className = Class.forName("java.lang.Object").getName();
- assertNotNull(className);
-
- assertEquals("Class getName printed wrong value", "java.lang.Object", className);
- assertEquals("Class getName printed wrong value", "int", int.class.getName());
- className = Class.forName("[I").getName();
- assertNotNull(className);
- assertEquals("Class getName printed wrong value", "[I", className);
-
- className = Class.forName("[Ljava.lang.Object;").getName();
- assertNotNull(className);
-
- assertEquals("Class getName printed wrong value", "[Ljava.lang.Object;", className);
- }
-
- /**
- * @tests java.lang.Class#getResource(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getResource",
- args = {java.lang.String.class}
- )
- public void test_getResourceLjava_lang_String() {
- final String name = "/";
- URL res = getClass().getResource(name + "HelloWorld.txt");
- assertNotNull(res);
- assertNull(getClass().getResource(
- "org/apache/harmony/luni/tests/java/lang/NonExistentResource"));
- assertNull(getClass().getResource(name + "NonExistentResource"));
- }
-
- /**
- * @tests java.lang.Class#getResourceAsStream(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getResourceAsStream",
- args = {java.lang.String.class}
- )
- public void test_getResourceAsStreamLjava_lang_String() throws Exception {
- String name = "/HelloWorld.txt";
- assertNotNull("the file " + name + " can not be found in this " +
- "directory", getClass().getResourceAsStream(name));
-
- final String nameBadURI = "org/apache/harmony/luni/tests/" +
- "test_resource.txt";
- assertNull("the file " + nameBadURI + " should not be found in this " +
- "directory",
- getClass().getResourceAsStream(nameBadURI));
-
- ClassLoader pcl = getClass().getClassLoader();
- Class<?> clazz = pcl.loadClass("org.apache.harmony.luni.tests.java.lang.ClassTest");
- assertNotNull(clazz.getResourceAsStream("HelloWorld1.txt"));
-
- try {
- getClass().getResourceAsStream(null);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.Class#getSuperclass()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSuperclass",
- args = {}
- )
- public void test_getSuperclass() {
- assertNull("Object has a superclass???", Object.class.getSuperclass());
- assertSame("Normal class has bogus superclass", InputStream.class,
- FileInputStream.class.getSuperclass());
- assertSame("Array class has bogus superclass", Object.class, FileInputStream[].class
- .getSuperclass());
- assertNull("Base class has a superclass", int.class.getSuperclass());
- assertNull("Interface class has a superclass", Cloneable.class.getSuperclass());
- }
-
- /**
- * @tests java.lang.Class#isArray()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isArray",
- args = {}
- )
- public void test_isArray() throws ClassNotFoundException {
- assertTrue("Non-array type claims to be.", !int.class.isArray());
- Class<?> clazz = null;
- clazz = Class.forName("[I");
- assertTrue("int Array type claims not to be.", clazz.isArray());
-
- clazz = Class.forName("[Ljava.lang.Object;");
- assertTrue("Object Array type claims not to be.", clazz.isArray());
-
- clazz = Class.forName("java.lang.Object");
- assertTrue("Non-array Object type claims to be.", !clazz.isArray());
- }
-
- /**
- * @tests java.lang.Class#isAssignableFrom(java.lang.Class)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isAssignableFrom",
- args = {java.lang.Class.class}
- )
- public void test_isAssignableFromLjava_lang_Class() {
- Class<?> clazz1 = null;
- Class<?> clazz2 = null;
-
- clazz1 = Object.class;
- clazz2 = Class.class;
- assertTrue("returned false for superclass",
- clazz1.isAssignableFrom(clazz2));
-
- clazz1 = TestClass.class;
- assertTrue("returned false for same class",
- clazz1.isAssignableFrom(clazz1));
-
- clazz1 = Runnable.class;
- clazz2 = Thread.class;
- assertTrue("returned false for implemented interface",
- clazz1.isAssignableFrom(clazz2));
-
- assertFalse("returned true not assignable classes",
- Integer.class.isAssignableFrom(String.class));
-
- try {
- clazz1.isAssignableFrom(null);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.Class#isInterface()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isInterface",
- args = {}
- )
- public void test_isInterface() throws ClassNotFoundException {
- assertTrue("Prim type claims to be interface.", !int.class.isInterface());
- Class<?> clazz = null;
- clazz = Class.forName("[I");
- assertTrue("Prim Array type claims to be interface.", !clazz.isInterface());
-
- clazz = Class.forName("java.lang.Runnable");
- assertTrue("Interface type claims not to be interface.", clazz.isInterface());
- clazz = Class.forName("java.lang.Object");
- assertTrue("Object type claims to be interface.", !clazz.isInterface());
-
- clazz = Class.forName("[Ljava.lang.Object;");
- assertTrue("Array type claims to be interface.", !clazz.isInterface());
- }
-
- /**
- * @tests java.lang.Class#isPrimitive()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isPrimitive",
- args = {}
- )
- public void test_isPrimitive() {
- assertFalse("Interface type claims to be primitive.",
- Runnable.class.isPrimitive());
- assertFalse("Object type claims to be primitive.",
- Object.class.isPrimitive());
- assertFalse("Prim Array type claims to be primitive.",
- int[].class.isPrimitive());
- assertFalse("Array type claims to be primitive.",
- Object[].class.isPrimitive());
- assertTrue("Prim type claims not to be primitive.",
- int.class.isPrimitive());
- assertFalse("Object type claims to be primitive.",
- Object.class.isPrimitive());
- }
-
- /**
- * @tests java.lang.Class#newInstance()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newInstance",
- args = {}
- )
- public void test_newInstance() throws Exception {
- Class<?> clazz = null;
- clazz = Class.forName("java.lang.Object");
- assertNotNull("new object instance was null", clazz.newInstance());
-
- clazz = Class.forName("java.lang.Throwable");
- assertSame("new Throwable instance was not a throwable",
- clazz, clazz.newInstance().getClass());
-
- clazz = Class.forName("java.lang.Integer");
- try {
- clazz.newInstance();
- fail("Exception for instantiating a newInstance with no default " +
- " constructor is not thrown");
- } catch (InstantiationException e) {
- // expected
- }
-
- try {
- TestClass3.class.newInstance();
- fail("IllegalAccessException is not thrown.");
- } catch(IllegalAccessException iae) {
- //expected
- }
-
- try {
- TestClass1C.class.newInstance();
- fail("ExceptionInInitializerError should be thrown.");
- } catch (java.lang.ExceptionInInitializerError ie) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.Class#newInstance()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "newInstance",
- args = {}
- )
- public void test_newInstance2() throws Exception {
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- TestClass.class.newInstance();
- fail("Test 1: SecurityException expected.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Class#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() throws ClassNotFoundException {
- assertEquals("Class toString printed wrong value",
- "int", int.class.toString());
- Class<?> clazz = null;
- clazz = Class.forName("[I");
- assertEquals("Class toString printed wrong value",
- "class [I", clazz.toString());
-
- clazz = Class.forName("java.lang.Object");
- assertEquals("Class toString printed wrong value",
- "class java.lang.Object", clazz.toString());
-
- clazz = Class.forName("[Ljava.lang.Object;");
- assertEquals("Class toString printed wrong value",
- "class [Ljava.lang.Object;", clazz.toString());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getResourceAsStream",
- args = {java.lang.String.class}
- )
- // Regression Test for JIRA-2047
- public void test_getResourceAsStream_withSharpChar() throws Exception{
- InputStream in = getClass().getResourceAsStream("/" + FILENAME);
- assertNotNull(in);
- in.close();
-
- in = getClass().getResourceAsStream(FILENAME);
- assertNull(in);
-
- in = this.getClass().getClassLoader().getResourceAsStream(
- FILENAME);
- assertNotNull(in);
- in.close();
- }
-
- /*
- * Regression test for HARMONY-2644:
- * Load system and non-system array classes via Class.forName()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ClassNotFoundException.",
- method = "forName",
- args = {java.lang.String.class}
- )
- public void test_forName_arrays() throws Exception {
- Class<?> c1 = getClass();
- String s = c1.getName();
- Class<?> a1 = Class.forName("[L" + s + ";");
- Class<?> a2 = Class.forName("[[L" + s + ";");
- assertSame(c1, a1.getComponentType());
- assertSame(a1, a2.getComponentType());
- Class<?> l4 = Class.forName("[[[[[J");
- assertSame(long[][][][][].class, l4);
-
- try{
- Class<?> clazz = Class.forName("[;");
- fail("1: " + clazz);
- } catch (ClassNotFoundException ok) {}
- try{
- Class<?> clazz = Class.forName("[[");
- fail("2:" + clazz);
- } catch (ClassNotFoundException ok) {}
- try{
- Class<?> clazz = Class.forName("[L");
- fail("3:" + clazz);
- } catch (ClassNotFoundException ok) {}
- try{
- Class<?> clazz = Class.forName("[L;");
- fail("4:" + clazz);
- } catch (ClassNotFoundException ok) {}
- try{
- Class<?> clazz = Class.forName(";");
- fail("5:" + clazz);
- } catch (ClassNotFoundException ok) {}
- try{
- Class<?> clazz = Class.forName("");
- fail("6:" + clazz);
- } catch (ClassNotFoundException ok) {}
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "asSubclass",
- args = {java.lang.Class.class}
- )
- public void test_asSubclass1() {
- assertEquals(ExtendTestClass.class,
- ExtendTestClass.class.asSubclass(PublicTestClass.class));
-
- assertEquals(PublicTestClass.class,
- PublicTestClass.class.asSubclass(TestInterface.class));
-
- assertEquals(ExtendTestClass1.class,
- ExtendTestClass1.class.asSubclass(PublicTestClass.class));
-
- assertEquals(PublicTestClass.class,
- PublicTestClass.class.asSubclass(PublicTestClass.class));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "asSubclass",
- args = {java.lang.Class.class}
- )
- public void test_asSubclass2() {
- try {
- PublicTestClass.class.asSubclass(ExtendTestClass.class);
- fail("Test 1: ClassCastException expected.");
- } catch(ClassCastException cce) {
- // Expected.
- }
-
- try {
- PublicTestClass.class.asSubclass(String.class);
- fail("Test 2: ClassCastException expected.");
- } catch(ClassCastException cce) {
- // Expected.
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "cast",
- args = {java.lang.Object.class}
- )
- public void test_cast() {
- Object o = PublicTestClass.class.cast(new ExtendTestClass());
- assertTrue(o instanceof ExtendTestClass);
-
- try {
- ExtendTestClass.class.cast(new PublicTestClass());
- fail("Test 1: ClassCastException expected.");
- } catch(ClassCastException cce) {
- //expected
- }
-
- try {
- ExtendTestClass.class.cast(new String());
- fail("ClassCastException is not thrown.");
- } catch(ClassCastException cce) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "desiredAssertionStatus",
- args = {}
- )
- public void test_desiredAssertionStatus() {
- Class [] classArray = { Object.class, Integer.class,
- String.class, PublicTestClass.class,
- ExtendTestClass.class, ExtendTestClass1.class};
-
- for(int i = 0; i < classArray.length; i++) {
- assertFalse("assertion status for " + classArray[i],
- classArray[i].desiredAssertionStatus());
- }
- }
-
-
-
- SecurityManager sm = new SecurityManager() {
-
- final String forbidenPermissionName = "user.dir";
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals(forbidenPermissionName)) {
- throw new SecurityException();
- }
- }
-
- public void checkMemberAccess(Class<?> clazz,
- int which) {
- if(clazz.equals(TestClass.class)) {
- throw new SecurityException();
- }
- }
-
- public void checkPackageAccess(String pkg) {
- if(pkg.equals(TestClass.class.getPackage())) {
- throw new SecurityException();
- }
- }
-
- };
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassTest2.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassTest2.java
deleted file mode 100644
index 07abda2..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassTest2.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-@TestTargetClass(Class.class)
-public class ClassTest2 extends junit.framework.TestCase {
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-
- /**
- * Tests loading a resource with a relative name.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getResourceAsStream",
- args = {java.lang.String.class}
- )
- public void testGetResourceAsStream1() throws IOException {
- Class clazz = getClass();
-
- InputStream stream = clazz.getResourceAsStream("HelloWorld.txt");
- assert(stream != null);
-
- byte[] buffer = new byte[20];
- int length = stream.read(buffer);
- String s = new String(buffer, 0, length);
- assert("Hello, World.".equals(s));
-
- stream.close();
- }
-
- /**
- * Tests loading a resource with a global name.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getResourceAsStream",
- args = {java.lang.String.class}
- )
- public void testGetResourceAsStream2() throws IOException {
- Class clazz = getClass();
-
- InputStream stream = clazz.getResourceAsStream("/org/apache/harmony/luni/tests/java/lang/HelloWorld.txt");
- assert(stream != null);
-
- byte[] buffer = new byte[20];
- int length = stream.read(buffer);
- String s = new String(buffer, 0, length);
- assert("Hello, World.".equals(s));
-
- stream.close();
-
- try {
- clazz.getResourceAsStream(null);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- assertNull(clazz.getResourceAsStream("/NonExistentResource"));
- assertNull(clazz.getResourceAsStream("org/apache/harmony/luni/tests/java/lang/HelloWorld.txt"));
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CloneNotSupportedExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CloneNotSupportedExceptionTest.java
deleted file mode 100644
index 58e86fa..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CloneNotSupportedExceptionTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(CloneNotSupportedException.class)
-public class CloneNotSupportedExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.CloneNotSupportedException#CloneNotSupportedException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "CloneNotSupportedException",
- args = {}
- )
- public void test_Constructor() {
- CloneNotSupportedException e = new CloneNotSupportedException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.CloneNotSupportedException#CloneNotSupportedException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "CloneNotSupportedException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- CloneNotSupportedException e = new CloneNotSupportedException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CompilerTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CompilerTest.java
deleted file mode 100644
index 5c01a36..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CompilerTest.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(Compiler.class)
-public class CompilerTest extends TestCase {
-
- /**
- * @tests java.lang.Compiler#command(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "command",
- args = {java.lang.Object.class}
- )
- public void test_commandLjava_lang_Object() {
-
- if(System.getProperty("java.compiler") != null) {
- try {
- assertNull("Incorrect behavior.", Compiler.command(new Object()));
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- // NullPointerException is not specified.
- Compiler.command(null);
- } else {
- Compiler.command("");
- }
- }
-
- /**
- * @tests java.lang.Compiler#compileClass(java.lang.Class)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compileClass",
- args = {java.lang.Class.class}
- )
- public void test_compileClassLjava_lang_Class() {
- try {
- // Do not test return value, may return true or false depending on
- // if the jit is enabled. Make the call to ensure it doesn't crash.
- Compiler.compileClass(Compiler.class);
- } catch (Exception e) {
- fail("Exception during test.");
- }
-
- // NullPointerException is not specified.
- Compiler.compileClass((Class) null);
- }
-
- /**
- * @tests java.lang.Compiler#compileClasses(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compileClasses",
- args = {java.lang.String.class}
- )
- public void test_compileClassesLjava_lang_String() {
- try {
- // Do not test return value, may return true or false depending on
- // if the jit is enabled. Make the call to ensure it doesn't crash.
- Compiler.compileClasses("Compiler");
- } catch (Exception e) {
- fail("Exception during test.");
- }
-
- // NullPointerException is not specified.
- Compiler.compileClasses((String) null);
- }
-
- /**
- * @tests java.lang.Compiler#disable()
- */
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "Doesn't verify that disable() method causes the Compiler to cease operation.",
- method = "disable",
- args = {}
- )
- public void test_disable() {
- try {
- Compiler.disable();
- Compiler.compileClass(Compiler.class);
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.lang.Compiler#enable()
- */
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "Doesn't verify that enable() method causes the Compiler to resume operation.",
- method = "enable",
- args = {}
- )
- public void test_enable() {
- try {
- Compiler.disable();
- Compiler.enable();
- Compiler.compileClass(Compiler.class);
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/DoubleTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/DoubleTest.java
deleted file mode 100644
index 3b2d405..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/DoubleTest.java
+++ /dev/null
@@ -1,1663 +0,0 @@
-/* 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.Locale;
-
-@TestTargetClass(Double.class)
-public class DoubleTest extends TestCase {
- private static final long rawBitsFor3_4en324ToN1[] = { 0x1L, 0x7L, 0x45L, 0x2b0L, 0x1ae2L,
- 0x10cd1L, 0xa8028L, 0x69018dL, 0x41a0f7eL, 0x29049aedL, 0x19a2e0d44L,
- 0x1005cc84acL, 0xa039fd2ebdL, 0x64243e3d361L, 0x3e96a6e641c6L, 0x271e284fe91b8L,
- 0x1872d931f1b131L, 0x4e8f8f7e6e1d7dL, 0x8319b9af04d26eL, 0xb7e0281ac6070aL,
- 0xedd832217788ccL, 0x122a71f54eab580L, 0x15750e72a2562e0L, 0x18d2520f4aebb98L,
- 0x1c2373498ed353fL, 0x1f6c501bf28828eL, 0x22c76422ef2a332L, 0x261c9e95d57a5ffL,
- 0x2963c63b4ad8f7fL, 0x2cbcb7ca1d8f35fL, 0x3015f2de527981bL, 0x335b6f95e717e22L,
- 0x36b24b7b60dddabL, 0x3a0f6f2d1c8aa8bL, 0x3d534af863ad52dL, 0x40a81db67c98a79L,
- 0x440912920ddf68bL, 0x474b5736915742eL, 0x4a9e2d0435ad13aL, 0x4e02dc22a18c2c4L,
- 0x5143932b49ef375L, 0x549477f61c6b052L, 0x57f995f3a385c67L, 0x5b3bfdb846339c0L,
- 0x5e8afd2657c0830L, 0x61edbc6fedb0a3dL, 0x653495c5f48e666L, 0x6881bb3771b1fffL,
- 0x6be22a054e1e7ffL, 0x6f2d5a4350d30ffL, 0x7278b0d42507d3fL, 0x75d6dd092e49c8fL,
- 0x79264a25bcee1daL, 0x7c6fdcaf2c29a50L, 0x7fcbd3daf7340e4L, 0x831f6468da8088eL,
- 0x86673d831120ab2L, 0x89c10ce3d568d5fL, 0x8d18a80e656185bL, 0x905ed211feb9e72L,
- 0x93b686967e6860eL, 0x9712141e0f013c9L, 0x9a56992592c18bbL, 0x9dac3f6ef771eeaL,
- 0xa10ba7a55aa7352L, 0xa44e918eb151027L, 0xa7a235f25da5430L, 0xab0561b77a8749eL,
- 0xae46ba2559291c6L, 0xb19868aeaf73637L, 0xb4fe82da5b503c5L, 0xb83f11c8791225bL,
- 0xbb8ed63a9756af2L, 0xbef28bc93d2c5afL, 0xc237975dc63bb8dL, 0xc5857d3537caa70L,
- 0xc8e6dc8285bd50cL, 0xcc3049d19396528L, 0xcf7c5c45f87be72L, 0xd2db7357769ae0eL,
- 0xd6292816aa20cc9L, 0xd973721c54a8ffbL, 0xdcd04ea369d33faL, 0xe0223126222407cL,
- 0xe36abd6faaad09bL, 0xe6c56ccb95584c2L, 0xea1b63ff3d572f9L, 0xed623cff0cacfb8L,
- 0xf0bacc3ecfd83a5L, 0xf414bfa741e7247L, 0xf759ef911260ed9L, 0xfab06b7556f9290L,
- 0xfe0e4329565bb9aL, 0x10151d3f3abf2a80L, 0x104a648f096ef520L, 0x10807ed965e55934L,
- 0x10b49e8fbf5eaf81L, 0x10e9c633af365b61L, 0x11201be04d81f91dL, 0x115422d860e27764L,
- 0x11892b8e791b153dL, 0x11bf76721761da8cL, 0x11f3aa074e9d2898L, 0x12289489224472beL,
- 0x125eb9ab6ad58f6dL, 0x1293340b22c579a4L, 0x12c8010deb76d80dL, 0x12fe015166548e11L,
- 0x1332c0d2dff4d8caL, 0x1367710797f20efdL, 0x139d4d497dee92bcL, 0x13d2504deeb51bb6L,
- 0x1406e4616a6262a3L, 0x143c9d79c4fafb4cL, 0x1471e26c1b1cdd0fL, 0x14a65b0721e41453L,
- 0x14dbf1c8ea5d1968L, 0x1511771d927a2fe1L, 0x1545d4e4f718bbd9L, 0x157b4a1e34deead0L,
- 0x15b10e52e10b52c2L, 0x15e551e7994e2772L, 0x161aa6617fa1b14fL, 0x1650a7fcefc50ed1L,
- 0x1684d1fc2bb65286L, 0x16ba067b36a3e727L, 0x16f0440d02267078L, 0x1724551042b00c96L,
- 0x17596a54535c0fbcL, 0x178fc4e9683313abL, 0x17c3db11e11fec4bL, 0x17f8d1d65967e75eL,
- 0x182f064befc1e135L, 0x186363ef75d92cc1L, 0x18983ceb534f77f1L, 0x18ce4c26282355eeL,
- 0x1902ef97d91615b5L, 0x1937ab7dcf5b9b22L, 0x196d965d433281eaL, 0x19a27dfa49ff9132L,
- 0x19d71d78dc7f757fL, 0x1a0ce4d7139f52dfL, 0x1a420f066c4393cbL, 0x1a7692c8075478beL,
- 0x1aac377a092996edL, 0x1ae1a2ac45b9fe54L, 0x1b160b5757287de9L, 0x1b4b8e2d2cf29d64L,
- 0x1b8138dc3c17a25eL, 0x1bb587134b1d8af6L, 0x1beae8d81de4edb4L, 0x1c20d18712af1490L,
- 0x1c5505e8d75ad9b4L, 0x1c8a47630d319021L, 0x1cc06c9de83efa15L, 0x1cf487c5624eb89aL,
- 0x1d29a9b6bae266c1L, 0x1d600a1234cd8038L, 0x1d940c96c200e046L, 0x1dc90fbc72811858L,
- 0x1dff53ab8f215e6eL, 0x1e33944b3974db05L, 0x1e68795e07d211c6L, 0x1e9e97b589c69637L,
- 0x1ed31ed1761c1de3L, 0x1f07e685d3a3255bL, 0x1f3de027488beeb2L, 0x1f72ac188d57752fL,
- 0x1fa7571eb0ad527bL, 0x1fdd2ce65cd8a71aL, 0x20123c0ffa076870L, 0x2046cb13f889428cL,
- 0x207c7dd8f6ab932fL, 0x20b1cea79a2b3bfeL, 0x20e6425180b60afdL, 0x211bd2e5e0e38dbcL,
- 0x215163cfac8e3896L, 0x2185bcc397b1c6bbL, 0x21bb2bf47d9e386aL, 0x21f0fb78ce82e342L,
- 0x22253a5702239c13L, 0x225a88ecc2ac8317L, 0x22909593f9abd1efL, 0x22c4baf8f816c66aL,
- 0x22f9e9b7361c7805L, 0x2330321281d1cb03L, 0x23643e9722463dc4L, 0x23994e3cead7cd35L,
- 0x23cfa1cc258dc082L, 0x2403c51f97789851L, 0x2438b6677d56be65L, 0x246ee4015cac6dffL,
- 0x24a34e80d9ebc4bfL, 0x24d822211066b5efL, 0x250e2aa95480636bL, 0x2542daa9d4d03e23L,
- 0x257791544a044dabL, 0x25ad75a95c856116L, 0x25e26989d9d35caeL, 0x261703ec504833d9L,
- 0x264cc4e7645a40d0L, 0x2681fb109eb86882L, 0x26b679d4c66682a2L, 0x26ec1849f800234bL,
- 0x27218f2e3b00160fL, 0x2755f2f9c9c01b93L, 0x278b6fb83c302277L, 0x27c125d3259e158bL,
- 0x27f56f47ef059aedL, 0x282acb19eac701a8L, 0x2860bef032bc6109L, 0x2894eeac3f6b794cL,
- 0x28ca2a574f46579eL, 0x29005a76918bf6c3L, 0x2934711435eef474L, 0x29698d59436ab191L,
- 0x299ff0af94455df5L, 0x29d3f66dbcab5ab9L, 0x2a08f4092bd63167L, 0x2a3f310b76cbbdc1L,
- 0x2a737ea72a3f5699L, 0x2aa85e50f4cf2c3fL, 0x2ade75e53202f74fL, 0x2b1309af3f41da91L,
- 0x2b47cc1b0f125135L, 0x2b7dbf21d2d6e583L, 0x2bb2977523c64f72L, 0x2be73d526cb7e34eL,
- 0x2c1d0ca707e5dc22L, 0x2c5227e864efa995L, 0x2c86b1e27e2b93faL, 0x2cbc5e5b1db678f9L,
- 0x2cf1baf8f2920b9cL, 0x2d2629b72f368e83L, 0x2d5bb424fb043223L, 0x2d9150971ce29f56L,
- 0x2dc5a4bce41b472bL, 0x2dfb0dec1d2218f6L, 0x2e30e8b392354f9aL, 0x2e6522e076c2a380L,
- 0x2e9a6b9894734c61L, 0x2ed0833f5cc80fbcL, 0x2f04a40f33fa13abL, 0x2f39cd1300f89896L,
- 0x2f70202be09b5f5eL, 0x2fa42836d8c23735L, 0x2fd932448ef2c503L, 0x300f7ed5b2af7643L,
- 0x3043af458fada9eaL, 0x30789b16f3991465L, 0x30aec1dcb07f597eL, 0x30e33929ee4f97efL,
- 0x3118077469e37deaL, 0x314e0951845c5d65L, 0x3182c5d2f2b9ba5fL, 0x31b77747af6828f7L,
- 0x31ed55199b423335L, 0x3222553001096001L, 0x3256ea7c014bb801L, 0x328ca51b019ea601L,
- 0x32c1e730e10327c1L, 0x32f660fd1943f1b1L, 0x332bf93c5f94ee1dL, 0x33617bc5bbbd14d2L,
- 0x3395dab72aac5a07L, 0x33cb5164f5577089L, 0x340112df1956a655L, 0x34355796dfac4febL,
- 0x346aad7c979763e5L, 0x34a0ac6ddebe9e6fL, 0x34d4d789566e460bL, 0x350a0d6bac09d78eL,
- 0x354048634b8626b9L, 0x35745a7c1e67b067L, 0x35a9711b26019c81L, 0x35dfcd61ef8203a1L,
- 0x3613e05d35b14245L, 0x3648d874831d92d6L, 0x367f0e91a3e4f78bL, 0x36b3691b066f1ab7L,
- 0x36e84361c80ae165L, 0x371e543a3a0d99beL, 0x3752f4a464488017L, 0x3787b1cd7d5aa01cL,
- 0x37bd9e40dcb14823L, 0x37f282e889eecd16L, 0x382723a2ac6a805cL, 0x385cec8b57852073L,
- 0x389213d716b33448L, 0x38c698ccdc60015aL, 0x38fc3f00137801b0L, 0x3931a7600c2b010eL,
- 0x396611380f35c151L, 0x399b9586130331a6L, 0x39d13d73cbe1ff08L, 0x3a058cd0beda7ec9L,
- 0x3a3af004ee911e7cL, 0x3a70d603151ab30dL, 0x3aa50b83da615fd1L, 0x3ada4e64d0f9b7c5L,
- 0x3b1070ff029c12dbL, 0x3b448d3ec3431792L, 0x3b79b08e7413dd76L, 0x3bb00e59088c6a6aL,
- 0x3be411ef4aaf8504L, 0x3c19166b1d5b6646L, 0x3c4f5c05e4b23fd7L, 0x3c839983aeef67e6L,
- 0x3cb87fe49aab41e0L, 0x3cee9fddc1561258L, 0x3d2323ea98d5cb77L, 0x3d57ece53f0b3e55L,
- 0x3d8de81e8ece0deaL, 0x3dc2b1131940c8b2L, 0x3df75d57df90fadfL, 0x3e2d34add7753996L,
- 0x3e6240eca6a943feL, 0x3e96d127d05394fdL, 0x3ecc8571c4687a3dL, 0x3f01d3671ac14c66L,
- 0x3f364840e1719f80L, 0x3f6bda5119ce075fL, 0x3fa16872b020c49cL, 0x3fd5c28f5c28f5c3L,
- 0x400B333333333333L };
-
- private static final long rawBitsFor1_2e0To309[] = { 0x3ff3333333333333L, 0x4028000000000000L,
- 0x405e000000000000L, 0x4092c00000000000L, 0x40c7700000000000L, 0x40fd4c0000000000L,
- 0x41324f8000000000L, 0x4166e36000000000L, 0x419c9c3800000000L, 0x41d1e1a300000000L,
- 0x42065a0bc0000000L, 0x423bf08eb0000000L, 0x427176592e000000L, 0x42a5d3ef79800000L,
- 0x42db48eb57e00000L, 0x43110d9316ec0000L, 0x434550f7dca70000L, 0x437aa535d3d0c000L,
- 0x43b0a741a4627800L, 0x43e4d1120d7b1600L, 0x441a055690d9db80L, 0x445043561a882930L,
- 0x4484542ba12a337cL, 0x44b969368974c05bL, 0x44efc3842bd1f072L, 0x4523da329b633647L,
- 0x4558d0bf423c03d9L, 0x458f04ef12cb04cfL, 0x45c363156bbee301L, 0x45f83bdac6ae9bc2L,
- 0x462e4ad1785a42b2L, 0x4662eec2eb3869afL, 0x4697aa73a606841bL, 0x46cd95108f882522L,
- 0x47027d2a59b51735L, 0x47371c74f0225d03L, 0x476ce3922c2af443L, 0x47a20e3b5b9ad8aaL,
- 0x47d691ca32818ed5L, 0x480c363cbf21f28aL, 0x4841a1e5f7753796L, 0x48760a5f7552857cL,
- 0x48ab8cf752a726daL, 0x48e1381a93a87849L, 0x491586213892965bL, 0x494ae7a986b73bf1L,
- 0x4980d0c9f4328577L, 0x49b504fc713f26d5L, 0x49ea463b8d8ef08aL, 0x4a206be538795656L,
- 0x4a5486de8697abecL, 0x4a89a896283d96e6L, 0x4ac0095dd9267e50L, 0x4af40bb54f701de4L,
- 0x4b290ea2a34c255dL, 0x4b5f524b4c1f2eb4L, 0x4b93936f0f937d31L, 0x4bc8784ad3785c7dL,
- 0x4bfe965d8856739cL, 0x4c331dfa75360842L, 0x4c67e57912838a52L, 0x4c9dded757246ce6L,
- 0x4cd2ab469676c410L, 0x4d0756183c147514L, 0x4d3d2b9e4b199259L, 0x4d723b42eeeffb78L,
- 0x4da6ca13aaabfa56L, 0x4ddc7c989556f8ebL, 0x4e11cddf5d565b93L, 0x4e46415734abf278L,
- 0x4e7bd1ad01d6ef15L, 0x4eb1630c2126556dL, 0x4ee5bbcf296feac9L, 0x4f1b2ac2f3cbe57bL,
- 0x4f50fab9d85f6f6dL, 0x4f8539684e774b48L, 0x4fba87c262151e1aL, 0x4ff094d97d4d32d0L,
- 0x5024ba0fdca07f84L, 0x5059e893d3c89f65L, 0x5090315c645d639fL, 0x50c43db37d74bc87L,
- 0x50f94d205cd1eba9L, 0x512fa06874066693L, 0x5163c4414884001cL, 0x5198b5519aa50023L,
- 0x51cee2a6014e402cL, 0x52034da7c0d0e81bL, 0x52382111b1052222L, 0x526e29561d466aabL,
- 0x52a2d9d5d24c02abL, 0x52d7904b46df0355L, 0x530d745e1896c42bL, 0x534268bacf5e3a9bL,
- 0x537702e98335c941L, 0x53acc3a3e4033b92L, 0x53e1fa466e82053bL, 0x541678d80a22868aL,
- 0x544c170e0cab282cL, 0x54818e68c7eaf91cL, 0x54b5f202f9e5b763L, 0x54eb6e83b85f253bL,
- 0x55212512533b7745L, 0x55556e56e80a5516L, 0x558ac9eca20cea5cL, 0x55c0be33e5481279L,
- 0x55f4edc0de9a1718L, 0x562a293116409cdeL, 0x566059beade8620bL, 0x5694702e59627a8dL,
- 0x56c98c39efbb1931L, 0x56ffef486ba9df7dL, 0x5733f58d434a2baeL, 0x5768f2f0941cb699L,
- 0x579f2facb923e440L, 0x57d37dcbf3b66ea8L, 0x58085d3ef0a40a52L, 0x583e748eaccd0ce6L,
- 0x587308d92c002810L, 0x58a7cb0f77003214L, 0x58ddbdd354c03e99L, 0x591296a414f82720L,
- 0x59473c4d1a3630e8L, 0x597d0b6060c3bd21L, 0x59b2271c3c7a5635L, 0x59e6b0e34b98ebc2L,
- 0x5a1c5d1c1e7f26b3L, 0x5a51ba31930f7830L, 0x5a8628bdf7d3563cL, 0x5abbb2ed75c82bcaL,
- 0x5af14fd4699d1b5fL, 0x5b25a3c984046236L, 0x5b5b0cbbe5057ac4L, 0x5b90e7f56f236cbaL,
- 0x5bc521f2caec47e9L, 0x5bfa6a6f7da759e3L, 0x5c308285ae88982eL, 0x5c64a3271a2abe39L,
- 0x5c99cbf0e0b56dc8L, 0x5cd01f768c71649dL, 0x5d0427542f8dbdc4L, 0x5d3931293b712d35L,
- 0x5d6f7d738a4d7882L, 0x5da3ae6836706b51L, 0x5dd89a02440c8626L, 0x5e0ec082d50fa7afL,
- 0x5e433851c529c8ceL, 0x5e78066636743b01L, 0x5eae07ffc41149c1L, 0x5ee2c4ffda8ace19L,
- 0x5f17763fd12d819fL, 0x5f4d53cfc578e207L, 0x5f825461db6b8d44L, 0x5fb6e97a52467095L,
- 0x5feca3d8e6d80cbbL, 0x6021e667904707f5L, 0x605660017458c9f2L, 0x608bf801d16efc6eL,
- 0x60c17b0122e55dc5L, 0x60f5d9c16b9eb536L, 0x612b5031c6866284L, 0x6161121f1c13fd92L,
- 0x619556a6e318fcf7L, 0x61caac509bdf3c34L, 0x6200abb2616b85a1L, 0x6234d69ef9c66709L,
- 0x626a0c46b83800cbL, 0x62a047ac3323007fL, 0x62d459973febc09fL, 0x63096ffd0fe6b0c6L,
- 0x633fcbfc53e05cf8L, 0x6373df7db46c3a1bL, 0x63a8d75d218748a2L, 0x63df0d3469e91acaL,
- 0x64136840c231b0beL, 0x64484250f2be1ceeL, 0x647e52e52f6da42aL, 0x64b2f3cf3da4869aL,
- 0x64e7b0c30d0da840L, 0x651d9cf3d0511251L, 0x655282186232ab72L, 0x6587229e7abf564fL,
- 0x65bceb46196f2be3L, 0x65f2130bcfe57b6eL, 0x662697cec3deda49L, 0x665c3dc274d690dbL,
- 0x6691a69989061a89L, 0x66c6103feb47a12bL, 0x66fb944fe6198976L, 0x67313cb1efcff5eaL,
- 0x67658bde6bc3f364L, 0x679aeed606b4f03dL, 0x67d0d545c4311626L, 0x68050a97353d5bb0L,
- 0x683a4d3d028cb29cL, 0x687070462197efa2L, 0x68a48c57a9fdeb8aL, 0x68d9af6d947d666cL,
- 0x69100da47cce6004L, 0x6944110d9c01f805L, 0x6979155103027606L, 0x69af5aa543c31387L,
- 0x69e398a74a59ec35L, 0x6a187ed11cf06742L, 0x6a4e9e85642c8112L, 0x6a8323135e9bd0abL,
- 0x6ab7ebd83642c4d6L, 0x6aede6ce43d3760cL, 0x6b22b040ea6429c7L, 0x6b575c5124fd3439L,
- 0x6b8d33656e3c8147L, 0x6bc2401f64e5d0cdL, 0x6bf6d0273e1f4500L, 0x6c2c84310da71640L,
- 0x6c61d29ea8886de8L, 0x6c96474652aa8962L, 0x6ccbd917e7552bbaL, 0x6d0167aef0953b54L,
- 0x6d35c19aacba8a29L, 0x6d6b320157e92cb4L, 0x6da0ff40d6f1bbf0L, 0x6dd53f110cae2aedL,
- 0x6e0a8ed54fd9b5a8L, 0x6e40994551e81189L, 0x6e74bf96a66215ebL, 0x6ea9ef7c4ffa9b66L,
- 0x6ee035adb1fca120L, 0x6f1443191e7bc967L, 0x6f4953df661abbc1L, 0x6f7fa8d73fa16ab2L,
- 0x6fb3c98687c4e2afL, 0x6fe8bbe829b61b5bL, 0x701eeae23423a232L, 0x705352cd6096455fL,
- 0x70882780b8bbd6b7L, 0x70be3160e6eacc64L, 0x70f2dedc9052bfbfL, 0x71279693b4676faeL,
- 0x715d7c38a1814b9aL, 0x71926da364f0cf40L, 0x71c7090c3e2d0310L, 0x71fccb4f4db843d4L,
- 0x7231ff1190932a65L, 0x72667ed5f4b7f4feL, 0x729c1e8b71e5f23dL, 0x72d19317272fb766L,
- 0x7305f7dcf0fba540L, 0x733b75d42d3a8e90L, 0x737129a49c44991aL, 0x73a5740dc355bf60L,
- 0x73dad111342b2f39L, 0x7410c2aac09afd83L, 0x7444f35570c1bce4L, 0x747a302accf22c1dL,
- 0x74b05e1ac0175b92L, 0x74e475a1701d3277L, 0x75199309cc247f15L, 0x754ff7cc3f2d9edaL,
- 0x7583fadfa77c8348L, 0x75b8f997915ba41aL, 0x75ef37fd75b28d21L, 0x762382fe698f9834L,
- 0x765863be03f37e41L, 0x768e7cad84f05dd2L, 0x76c30dec73163aa3L, 0x76f7d1678fdbc94cL,
- 0x772dc5c173d2bb9fL, 0x77629b98e863b543L, 0x7797427f227ca294L, 0x77cd131eeb1bcb39L,
- 0x78022bf352f15f04L, 0x7836b6f027adb6c5L, 0x786c64ac31992476L, 0x78a1beeb9effb6caL,
- 0x78d62ea686bfa47cL, 0x790bba50286f8d9bL, 0x794154721945b881L, 0x7975a98e9f9726a1L,
- 0x79ab13f2477cf049L, 0x79e0ec776cae162eL, 0x7a15279547d99bb9L, 0x7a4a717a99d002a8L,
- 0x7a8086eca02201a9L, 0x7ab4a8a7c82a8213L, 0x7ae9d2d1ba352298L, 0x7b2023c31461359fL,
- 0x7b542cb3d9798307L, 0x7b8937e0cfd7e3c8L, 0x7bbf85d903cddcbaL, 0x7bf3b3a7a260a9f4L,
- 0x7c28a0918af8d472L, 0x7c5ec8b5edb7098eL, 0x7c933d71b49265f9L, 0x7cc80cce21b6ff77L,
- 0x7cfe1001aa24bf55L, 0x7d32ca010a56f795L, 0x7d677c814cecb57aL, 0x7d9d5ba1a027e2d9L,
- 0x7dd259450418edc7L, 0x7e06ef96451f2939L, 0x7e3cab7bd666f388L, 0x7e71eb2d66005835L,
- 0x7ea665f8bf806e42L, 0x7edbff76ef6089d2L, 0x7f117faa559c5623L, 0x7f45df94eb036bacL,
- 0x7f7b577a25c44697L, 0x7fb116ac579aac1fL, 0x7fe55c576d815726L, 0x7ff0000000000000L };
-
- private void doTestCompareRawBits(String originalDoubleString, long expectedRawBits,
- String expectedString) {
- double result;
- long rawBits;
- String convertedString;
- result = Double.parseDouble(originalDoubleString);
- rawBits = Double.doubleToLongBits(result);
- convertedString = new Double(result).toString();
- assertEquals(expectedRawBits, rawBits);
- assertEquals(expectedString.toLowerCase(Locale.US), convertedString
- .toLowerCase(Locale.US));
- }
-
- private void test_toString(double dd, String answer) {
- assertEquals(answer, Double.toString(dd));
- Double d = new Double(dd);
- assertEquals(answer, Double.toString(d.doubleValue()));
- assertEquals(answer, d.toString());
- }
-
- /**
- * @tests java.lang.Double#Double(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Double",
- args = {double.class}
- )
- public void test_ConstructorD() {
- Double d = new Double(39089.88888888888888888888888888888888);
- assertEquals("Created incorrect double", 39089.88888888888888888888888888888888, d
- .doubleValue(), 0D);
- }
-
- /**
- * @tests java.lang.Double#Double(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Double",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- Double d = new Double("39089.88888888888888888888888888888888");
- assertEquals("Created incorrect double", 39089.88888888888888888888888888888888, d
- .doubleValue(), 0D);
-
- // REGRESSION for HARMONY-489
- try {
- d = new Double("1E+-20");
- fail("new Double(\"1E+-20\") should throw exception");
- } catch (NumberFormatException e) {
- // expected
- }
- }
-
- /**
- * @tests java.lang.Double#byteValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "byteValue",
- args = {}
- )
- public void test_byteValue() {
- Double d = new Double(1923311.47712);
- assertEquals("Returned incorrect byte value", (byte) -17, d.byteValue());
- d= new Double(Byte.MAX_VALUE);
- assertEquals("Returned incorrect byte value", Byte.MAX_VALUE, d.byteValue());
- d= new Double(Byte.MIN_VALUE);
- assertEquals("Returned incorrect byte value", Byte.MIN_VALUE, d.byteValue());
- d= new Double(Double.MAX_VALUE);
- assertEquals("Returned incorrect byte value", -1, d.byteValue());
- }
-
- /**
- * @tests java.lang.Double#compareTo(java.lang.Double)
- * @tests java.lang.Double#compare(double, double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compare",
- args = {double.class, double.class}
- )
- public void test_compare() {
- double[] values = new double[] { Double.NEGATIVE_INFINITY, -Double.MAX_VALUE, -2d,
- -Double.MIN_VALUE, -0d, 0d, Double.MIN_VALUE, 2d, Double.MAX_VALUE,
- Double.POSITIVE_INFINITY, Double.NaN };
- for (int i = 0; i < values.length; i++) {
- double d1 = values[i];
- assertTrue("compare() should be equal: " + d1, Double.compare(d1, d1) == 0);
- Double D1 = new Double(d1);
- assertTrue("compareTo() should be equal: " + d1, D1.compareTo(D1) == 0);
- for (int j = i + 1; j < values.length; j++) {
- double d2 = values[j];
- assertTrue("compare() " + d1 + " should be less " + d2,
- Double.compare(d1, d2) == -1);
- assertTrue("compare() " + d2 + " should be greater " + d1, Double.compare(d2,
- d1) == 1);
- Double D2 = new Double(d2);
- assertTrue("compareTo() " + d1 + " should be less " + d2,
- D1.compareTo(D2) == -1);
- assertTrue("compareTo() " + d2 + " should be greater " + d1,
- D2.compareTo(D1) == 1);
- }
- }
-
- try {
- new Double(0.0D).compareTo(null);
- fail("No NPE");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @tests java.lang.Double#doubleToLongBits(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "doubleToLongBits",
- args = {double.class}
- )
- public void test_doubleToLongBitsD() {
- // Test for method long java.lang.Double.doubleToLongBits(double)
- Double d = new Double(Double.MAX_VALUE);
- long lbits = Double.doubleToLongBits(d.doubleValue());
- double r = Double.longBitsToDouble(lbits);
-
- assertTrue("Bit conversion failed", d.doubleValue() == r);
-
- assertEquals(0x7ff8000000000000L, Double.doubleToLongBits(Double.NaN));
- assertEquals(0x7ff0000000000000L, Double.doubleToLongBits(Double.POSITIVE_INFINITY));
- assertEquals(0xfff0000000000000L, Double.doubleToLongBits(Double.NEGATIVE_INFINITY));
- }
-
- /**
- * @tests java.lang.Double#doubleToRawLongBits(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "doubleToRawLongBits",
- args = {double.class}
- )
- public void test_doubleToRawLongBitsD() {
- long l = 0x7ff80000000004d2L;
- double d = Double.longBitsToDouble(l);
- assertTrue("Wrong raw bits", Double.doubleToRawLongBits(d) == l);
-
- assertEquals(0x7ff8000000000000L, Double.doubleToLongBits(Double.NaN));
- assertEquals(0x7ff0000000000000L, Double.doubleToLongBits(Double.POSITIVE_INFINITY));
- assertEquals(0xfff0000000000000L, Double.doubleToLongBits(Double.NEGATIVE_INFINITY));
- }
-
- /**
- * @tests java.lang.Double#doubleValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "doubleValue",
- args = {}
- )
- public void test_doubleValue() {
- assertEquals("Incorrect double value returned", 999999999999999.9999999999999,
- new Double(999999999999999.9999999999999).doubleValue(), 0D);
- assertEquals(Double.POSITIVE_INFINITY, new Double("1.7976931348623159E308").doubleValue());
- assertEquals(Double.NEGATIVE_INFINITY, new Double("-1.7976931348623159E308").doubleValue());
- assertEquals(Double.MAX_VALUE, new Double("1.7976931348623157E308").doubleValue());
- assertEquals(Double.MIN_VALUE, new Double("4.9E-324").doubleValue());
- }
-
- /**
- * @tests java.lang.Double#floatValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "floatValue",
- args = {}
- )
- public void test_floatValue() {
- // Test for method float java.lang.Double.floatValue()
- assertTrue(
- "Incorrect float value returned ",
- Math.abs(new Double(999999999999999.9999999999999d).
- floatValue() - 999999999999999.9999999999999f) < 1);
- assertEquals(Float.POSITIVE_INFINITY, new Double("3.4028236E38").floatValue());
- assertEquals(Float.NEGATIVE_INFINITY, new Double("-3.4028236E38").floatValue());
- assertEquals(Float.MAX_VALUE, new Double("3.4028235E38").floatValue());
- assertEquals(Float.MIN_VALUE, new Double("1.4E-45").floatValue());
- }
-
- /**
- * @tests java.lang.Double#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- // Test for method int java.lang.Double.hashCode()
- for (int i = -1000; i < 1000; i++) {
- Double d = new Double(i);
- Double dd = new Double(i);
- assertTrue("Should not be identical ", d != dd);
- assertTrue("Should be equals 1 ", d.equals(dd));
- assertTrue("Should be equals 2 ", dd.equals(d));
- assertTrue("Should have identical values ", dd.doubleValue() == d.doubleValue());
- assertTrue("Invalid hash for equal but not identical doubles ", d.hashCode() == dd
- .hashCode());
- }
- assertEquals("Magic assumption hasCode (0.0) = 0 failed", 0, new Double(0.0).hashCode());
- }
-
- /**
- * @tests java.lang.Double#intValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "intValue",
- args = {}
- )
- public void test_intValue() {
- // Test for method int java.lang.Double.intValue()
- Double d = new Double(1923311.47712);
- assertEquals("Returned incorrect int value", 1923311, d.intValue());
- assertEquals("Returned incorrect int value", Integer.MAX_VALUE,
- new Double(2147483648d).intValue());
- assertEquals("Returned incorrect int value", Integer.MIN_VALUE,
- new Double(-2147483649d).intValue());
- }
-
- /**
- * @tests java.lang.Double#isInfinite()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isInfinite",
- args = {}
- )
- public void test_isInfinite() {
- // Test for method boolean java.lang.Double.isInfinite()
- assertTrue("NEGATIVE_INFINITY returned false", new Double(Double.NEGATIVE_INFINITY)
- .isInfinite());
- assertTrue("POSITIVE_INFINITY returned false", new Double(Double.POSITIVE_INFINITY)
- .isInfinite());
- assertTrue("Non infinite number returned true", !(new Double(1000).isInfinite()));
- }
-
- /**
- * @tests java.lang.Double#isInfinite(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isInfinite",
- args = {double.class}
- )
- public void test_isInfiniteD() {
- // Test for method boolean java.lang.Double.isInfinite(double)
- assertTrue("Infinity check failed", Double.isInfinite(Double.NEGATIVE_INFINITY)
- && (Double.isInfinite(Double.POSITIVE_INFINITY))
- && !(Double.isInfinite(Double.MAX_VALUE)));
- }
-
- /**
- * @tests java.lang.Double#isNaN()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isNaN",
- args = {}
- )
- public void test_isNaN() {
- // Test for method boolean java.lang.Double.isNaN()
- Double d = new Double(0.0 / 0.0);
- assertTrue("NAN returned false", d.isNaN());
- d = new Double(0);
- assertTrue("Non NAN returned true", !d.isNaN());
- }
-
- /**
- * @tests java.lang.Double#isNaN(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isNaN",
- args = {double.class}
- )
- public void test_isNaND() {
- // Test for method boolean java.lang.Double.isNaN(double)
-
- Double d = new Double(0.0 / 0.0);
- assertTrue("NAN check failed", Double.isNaN(d.doubleValue()));
-
- assertFalse("Doesn't return false value", Double.isNaN(new Double(Double.MAX_VALUE)));
- }
-
- /**
- * @tests java.lang.Double#longBitsToDouble(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "longBitsToDouble",
- args = {long.class}
- )
- public void test_longBitsToDoubleJ() {
- // Test for method double java.lang.Double.longBitsToDouble(long)
-
- Double d = new Double(Double.MAX_VALUE);
- long lbits = Double.doubleToLongBits(d.doubleValue());
- double r = Double.longBitsToDouble(lbits);
-
- assertTrue("Bit conversion failed", d.doubleValue() == r);
- }
-
- /**
- * @tests java.lang.Double#longValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "longValue",
- args = {}
- )
- public void test_longValue() {
- // Test for method long java.lang.Double.longValue()
- Double d = new Double(1923311.47712);
- assertEquals("Returned incorrect long value", 1923311, d.longValue());
- }
-
- /**
- * @tests java.lang.Double#parseDouble(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies boundary values and the loop due to the difference in the expected output string.",
- method = "parseDouble",
- args = {java.lang.String.class}
- )
- @KnownFailure("parseDouble returns different value on Android " +
- "for 0x44b52d02c7e14af6L, it returns 1.0e23.")
- public void test_parseDoubleLjava_lang_String() {
- assertEquals("Incorrect double returned, expected zero.", 0.0, Double
- .parseDouble("2.4703282292062327208828439643411e-324"), 0.0);
- assertTrue("Incorrect double returned, expected minimum double.", Double
- .parseDouble("2.4703282292062327208828439643412e-324") == Double.MIN_VALUE);
-
- for (int i = 324; i > 0; i--) {
- Double.parseDouble("3.4e-" + i);
- }
- for (int i = 0; i <= 309; i++) {
- Double.parseDouble("1.2e" + i);
- }
-
- /*
- * The first two cases and the last four cases have to placed outside
- * the loop due to the difference in the expected output string.
- */
- doTestCompareRawBits("3.4e-324", rawBitsFor3_4en324ToN1[0], "4.9e-324");
- doTestCompareRawBits("3.4e-323", rawBitsFor3_4en324ToN1[1], "3.5e-323");
- for (int i = 322; i > 3; i--) {
- String testString, expectedString;
- testString = expectedString = "3.4e-" + i;
- doTestCompareRawBits(testString, rawBitsFor3_4en324ToN1[324 - i], expectedString);
- }
- doTestCompareRawBits("3.4e-3", rawBitsFor3_4en324ToN1[321], "0.0034");
- doTestCompareRawBits("3.4e-2", rawBitsFor3_4en324ToN1[322], "0.034");
- doTestCompareRawBits("3.4e-1", rawBitsFor3_4en324ToN1[323], "0.34");
- doTestCompareRawBits("3.4e-0", rawBitsFor3_4en324ToN1[324], "3.4");
-
- doTestCompareRawBits("1.2e0", rawBitsFor1_2e0To309[0], "1.2");
- doTestCompareRawBits("1.2e1", rawBitsFor1_2e0To309[1], "12.0");
- doTestCompareRawBits("1.2e2", rawBitsFor1_2e0To309[2], "120.0");
- doTestCompareRawBits("1.2e3", rawBitsFor1_2e0To309[3], "1200.0");
- doTestCompareRawBits("1.2e4", rawBitsFor1_2e0To309[4], "12000.0");
- doTestCompareRawBits("1.2e5", rawBitsFor1_2e0To309[5], "120000.0");
- doTestCompareRawBits("1.2e6", rawBitsFor1_2e0To309[6], "1200000.0");
- for (int i = 7; i <= 308; i++) {
- String testString, expectedString;
- testString = expectedString = "1.2e" + i;
- doTestCompareRawBits(testString, rawBitsFor1_2e0To309[i], expectedString);
- }
- doTestCompareRawBits("1.2e309", rawBitsFor1_2e0To309[309], "Infinity");
-
- doTestCompareRawBits(
- "111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000.92233720368547758079223372036854775807",
- 0x7e054218c295e43fL, "1.1122233344455567E299");
- doTestCompareRawBits(
- "-111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000111222333444555666777888999000.92233720368547758079223372036854775807",
- 0xfe054218c295e43fL, "-1.1122233344455567E299");
-
- doTestCompareRawBits("1.234123412431233E107", 0x562ae7a25fe706ebL,
- "1.234123412431233E107");
- doTestCompareRawBits("1.2341234124312331E107", 0x562ae7a25fe706ecL,
- "1.2341234124312331E107");
- doTestCompareRawBits("1.2341234124312332E107", 0x562ae7a25fe706ecL,
- "1.2341234124312331E107");
- doTestCompareRawBits("-1.234123412431233E107", 0xd62ae7a25fe706ebL,
- "-1.234123412431233E107");
- doTestCompareRawBits("-1.2341234124312331E107", 0xd62ae7a25fe706ecL,
- "-1.2341234124312331E107");
- doTestCompareRawBits("-1.2341234124312332E107", 0xd62ae7a25fe706ecL,
- "-1.2341234124312331E107");
-
- doTestCompareRawBits("9.999999999999999e22", 0x44b52d02c7e14af6L,
- "9.999999999999999e22");
-
- /*
- * These particular tests verify that the extreme boundary conditions
- * are converted correctly.
- */
- doTestCompareRawBits("0.0e-309", 0L, "0.0");
- doTestCompareRawBits("-0.0e-309", 0x8000000000000000L, "-0.0");
- doTestCompareRawBits("0.0e309", 0L, "0.0");
- doTestCompareRawBits("-0.0e309", 0x8000000000000000L, "-0.0");
- doTestCompareRawBits("0.1e309", 0x7fe1ccf385ebc8a0L, "1.0e308");
- doTestCompareRawBits("0.2e309", 0x7ff0000000000000L, "Infinity");
- doTestCompareRawBits("65e-325", 1L, "4.9e-324");
- doTestCompareRawBits("1000e-326", 2L, "1.0e-323");
-
- doTestCompareRawBits("4.0e-306", 0x86789e3750f791L, "4.0e-306");
- doTestCompareRawBits("2.22507e-308", 0xffffe2e8159d0L, "2.22507e-308");
- doTestCompareRawBits(
- "111222333444555666777888999000111228999000.92233720368547758079223372036854775807",
- 0x48746da623f1dd8bL, "1.1122233344455567E41");
- doTestCompareRawBits(
- "-111222333444555666777888999000111228999000.92233720368547758079223372036854775807",
- 0xc8746da623f1dd8bL, "-1.1122233344455567E41");
- doTestCompareRawBits(
- "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890.987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210",
- 0x54820fe0ba17f469L, "1.2345678901234567E99");
- doTestCompareRawBits(
- "-1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890.987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210987654321098765432109876543210",
- 0xd4820fe0ba17f469L, "-1.2345678901234567E99");
-
- doTestCompareRawBits(
- "179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.01",
- 0x7fefffffffffffffL, "1.7976931348623157E308");
- doTestCompareRawBits(
- "-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.01",
- 0xffefffffffffffffL, "-1.7976931348623157E308");
- doTestCompareRawBits(
- "1112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001234567890",
- 0x7ff0000000000000L, "Infinity");
- doTestCompareRawBits(
- "-1112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001112223334445556667778889990001234567890",
- 0xfff0000000000000L, "-Infinity");
- doTestCompareRawBits(
- "179769313486231590000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.01",
- 0x7ff0000000000000L, "Infinity");
- doTestCompareRawBits(
- "-179769313486231590000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.01",
- 0xfff0000000000000L, "-Infinity");
- doTestCompareRawBits(
- "0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157",
- 0x2b392a32afcc661eL, "1.7976931348623157E-100");
- doTestCompareRawBits(
- "-0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157",
- 0xab392a32afcc661eL, "-1.7976931348623157E-100");
- doTestCompareRawBits(
- "0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157",
- 0x1b3432f0cb68e61L, "1.7976931348623157E-300");
- doTestCompareRawBits(
- "-0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157",
- 0x81b3432f0cb68e61L, "-1.7976931348623157E-300");
- doTestCompareRawBits(
- "0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157",
- 0x2117b590b942L, "1.79769313486234E-310");
- doTestCompareRawBits(
- "-0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157",
- 0x80002117b590b942L, "-1.79769313486234E-310");
- doTestCompareRawBits(
- "0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157",
- 0xe37L, "1.798E-320");
- doTestCompareRawBits(
- "-0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000017976931348623157",
- 0x8000000000000e37L, "-1.798E-320");
- doTestCompareRawBits(
- "0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
- 0x2L, "1.0E-323");
- doTestCompareRawBits(
- "-0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001",
- 0x8000000000000002L, "-1.0E-323");
- doTestCompareRawBits(
- "0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000055595409854908458349204328908234982349050934129878452378432452458968024357823490509341298784523784324524589680243578234905093412987845237843245245896802435782349050934129878452378432452458968024357868024357823490509341298784523784324524589680243578234905093412987845237843245245896802435786802435782349050934129878452378432452458968024357823490509341298784523784324524589680243578",
- 0x1L, "4.9E-324");
- doTestCompareRawBits(
- "-0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000055595409854908458349204328908234982349050934129878452378432452458968024357823490509341298784523784324524589680243578234905093412987845237843245245896802435782349050934129878452378432452458968024357868024357823490509341298784523784324524589680243578234905093412987845237843245245896802435786802435782349050934129878452378432452458968024357823490509341298784523784324524589680243578",
- 0x8000000000000001L, "-4.9E-324");
- }
-
- /**
- * @tests java.lang.Double#parseDouble(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NumberFormatException.",
- method = "parseDouble",
- args = {java.lang.String.class}
- )
- public void test_parseDouble_LString_Illegal() {
- try {
- Double.parseDouble("0.0p0D");
- fail("Should throw NumberFormatException.");
- } catch (NumberFormatException e) {
- // expected
- }
-
- try {
- Double.parseDouble("+0x.p1d");
- fail("Should throw NumberFormatException.");
- } catch (NumberFormatException e) {
- // expected
- }
-
- try {
- Double.parseDouble("0Xg.gp1D");
- fail("Should throw NumberFormatException.");
- } catch (NumberFormatException e) {
- // expected
- }
-
- try {
- Double.parseDouble("-0x1.1p");
- fail("Should throw NumberFormatException.");
- } catch (NumberFormatException e) {
- // expected
- }
-
- try {
- Double.parseDouble("+0x 1.1 p2d");
- fail("Should throw NumberFormatException.");
- } catch (NumberFormatException e) {
- // expected
- }
-
- try {
- Double.parseDouble("x1.1p2d");
- fail("Should throw NumberFormatException.");
- } catch (NumberFormatException e) {
- // expected
- }
-
- try {
- Double.parseDouble(" 0x-2.1p2");
- fail("Should throw NumberFormatException.");
- } catch (NumberFormatException e) {
- // expected
- }
-
- try {
- Double.parseDouble(" 0x2.1pad");
- fail("Should throw NumberFormatException.");
- } catch (NumberFormatException e) {
- // expected
- }
-
- try {
- Double.parseDouble(" 0x111.222p 22d");
- fail("Should throw NumberFormatException.");
- } catch (NumberFormatException e) {
- // expected
- }
- }
-
- /**
- * @tests java.lang.Double#parseDouble(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't check exception.",
- method = "parseDouble",
- args = {java.lang.String.class}
- )
- public void test_parseDouble_LString_FromHexString() {
- double actual;
- double expected;
-
- actual = Double.parseDouble("0x0.0p0D");
- assertEquals("Returned incorrect value", 0.0d, actual, 0.0D);
-
- actual = Double.parseDouble("0xa.ap+9d");
- assertEquals("Returned incorrect value", 5440.0d, actual, 0.0D);
-
- actual = Double.parseDouble("+0Xb.10ap8");
- assertEquals("Returned incorrect value", 2832.625d, actual, 0.0D);
-
- actual = Double.parseDouble("-0X.a0P2D");
- assertEquals("Returned incorrect value", -2.5d, actual, 0.0D);
-
- actual = Double.parseDouble("\r 0x22.1p2d \t");
- assertEquals("Returned incorrect value", 136.25d, actual, 0.0D);
-
- actual = Double.parseDouble("0x1.0p-1");
- assertEquals("Returned incorrect value", 0.5, actual, 0.0D);
-
- actual = Double
- .parseDouble("0x00000000000000000000000000000000001.0p-1");
- assertEquals("Returned incorrect value", 0.5, actual, 0.0D);
-
- actual = Double.parseDouble("0x1.0p-00000000000000000000000000001");
- assertEquals("Returned incorrect value", 0.5, actual, 0.0D);
-
- actual = Double.parseDouble("0x.100000000000000000000000000000000p1");
- assertEquals("Returned incorrect value", 0.125, actual, 0.0D);
-
- actual = Double.parseDouble("0x0.0p999999999999999999999999999999999999999999999999999999999999999");
- assertEquals("Returned incorrect value", 0.0, actual, 0.0D);
-
- actual = Double.parseDouble("0xf1.0p9999999999999999999999999999999999999999999999999999999999999999");
- assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, actual, 0.0D);
-
- actual = Double.parseDouble("0xffffffffffffffffffffffffffffffffffff.ffffffffffffffffffffffffffffffffffffffffffffffp1");
- expected = Double.longBitsToDouble(0x4900000000000000L);
- assertEquals("Returned incorrect value", expected, actual, 0.0D);
-
- actual = Double.parseDouble("0x0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001p1600");
- expected = Double.longBitsToDouble(0x7f30000000000000L);
- assertEquals("Returned incorrect value", expected, actual, 0.0D);
-
- actual = Double.parseDouble("0x0.0p-999999999999999999999999999999999999999999999999999999");
- assertEquals("Returned incorrect value", 0.0, actual, 0.0D);
-
- actual = Double.parseDouble("0xf1.0p-9999999999999999999999999999999999999999999999999999999999999999");
- assertEquals("Returned incorrect value", 0.0, actual, 0.0D);
-
- actual = Double.parseDouble("0x10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000p-1600");
- expected = Double.longBitsToDouble(0xf0000000000000L);
- assertEquals("Returned incorrect value", expected, actual, 0.0D);
-
- actual = Double.parseDouble("0x1.p9223372036854775807");
- assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, actual, 0.0D);
-
- actual = Double.parseDouble("0x1.p9223372036854775808");
- assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, actual, 0.0D);
-
- actual = Double.parseDouble("0x10.p9223372036854775808");
- assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, actual, 0.0D);
-
- actual = Double.parseDouble("0xabcd.ffffffffp+2000");
- assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, actual, 0.0D);
-
- actual = Double.parseDouble("0x1.p-9223372036854775808");
- assertEquals("Returned incorrect value", 0.0, actual, 0.0D);
-
- actual = Double.parseDouble("0x1.p-9223372036854775809");
- assertEquals("Returned incorrect value", 0.0, actual, 0.0D);
-
- actual = Double.parseDouble("0x.1p-9223372036854775809");
- assertEquals("Returned incorrect value", 0.0, actual, 0.0D);
-
- actual = Double.parseDouble("0xabcd.ffffffffffffffp-2000");
- assertEquals("Returned incorrect value", 0.0, actual, 0.0D);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test for hotfix in native code of double parser.",
- method = "parseDouble",
- args = {java.lang.String.class}
- )
- public void test_parseDouble_LString_AndroidRegression() {
- // Android regression test
- long startTime = System.currentTimeMillis();
- double actual = Double.parseDouble("9e551027");
- assertTrue("parsing double 9e551027 took too long.",
- (System.currentTimeMillis() - startTime) < 1000);
- assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY,
- actual, 0.0D);
- }
-
- /**
- * @tests java.lang.Double#parseDouble(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies positive functionality.",
- method = "parseDouble",
- args = {java.lang.String.class}
- )
- public void test_parseDouble_LString_NormalPositiveExponent() {
- long[] expecteds = {
- 0x3f323456789abcdfL, 0x40e111012345678aL, 0x41a1110091a2b3c5L,
- 0x4259998091a2b3c5L, 0x4311110048d159e2L, 0x43c5554048d159e2L,
- 0x4479998048d159e2L, 0x452dddc048d159e2L, 0x45e111002468acf1L,
- 0x469333202468acf1L, 0x4751011001234568L, 0x4802112101234568L,
- 0x48b3213201234568L, 0x4964314301234568L, 0x4a15415401234568L,
- 0x4ac6516501234568L, 0x4b77617601234568L, 0x4c28718701234568L,
- 0x4cd9819801234568L, 0x4d9049048091a2b4L, 0x4e4101100091a2b4L,
- 0x4ef189188091a2b4L, 0x4fa211210091a2b4L, 0x505299298091a2b4L,
- 0x510321320091a2b4L, 0x51b3a93a8091a2b4L, 0x526431430091a2b4L,
- 0x5314b94b8091a2b4L, 0x53c841840091a2b4L, 0x5478c98c8091a2b4L,
- 0x552981980091a2b4L, 0x55da09a08091a2b4L, 0x568a91a90091a2b4L,
- 0x573b19b18091a2b4L, 0x57eba1ba0091a2b4L, 0x589c29c28091a2b4L,
- 0x594cb1cb0091a2b4L, 0x5a001d01c048d15aL, 0x5ab061060048d15aL,
- 0x5b60a50a4048d15aL, 0x5c1101100048d15aL, 0x5cc145144048d15aL,
- 0x5d7189188048d15aL, 0x5e21cd1cc048d15aL, 0x5ed211210048d15aL,
- 0x5f8255254048d15aL, 0x603419418048d15aL, 0x60e45d45c048d15aL,
- 0x6194a14a0048d15aL, 0x6244e54e4048d15aL, 0x62f541540048d15aL,
- 0x63a585584048d15aL, 0x6455c95c8048d15aL, 0x65060d60c048d15aL,
- 0x65b651650048d15aL, 0x666815814048d15aL, 0x671859858048d15aL,
- 0x67c89d89c048d15aL, 0x6878e18e0048d15aL, 0x692925924048d15aL,
- 0x69d981980048d15aL, 0x6a89c59c4048d15aL, 0x6b3a09a08048d15aL,
- 0x6bea4da4c048d15aL, 0x6c9c11c10048d15aL, 0x6d4c55c54048d15aL,
- 0x6dfc99c98048d15aL, 0x6eacddcdc048d15aL, 0x6f5d21d20048d15aL,
- 0x700d65d64048d15aL, 0x70bdc1dc0048d15aL, 0x716e05e04048d15aL,
- 0x721e49e48048d15aL, 0x72d00700602468adL, 0x73802902802468adL,
- 0x74304b04a02468adL, 0x74e06d06c02468adL, 0x75908f08e02468adL,
- 0x7640b10b002468adL, 0x76f0d30d202468adL, 0x77a10110002468adL,
- 0x78512312202468adL, 0x79020520402468adL, 0x79b22722602468adL,
- 0x7a624924802468adL, 0x7b126b26a02468adL, 0x7bc28d28c02468adL,
- 0x7c72af2ae02468adL, 0x7d22d12d002468adL, 0x7dd2f32f202468adL,
- 0x7e832132002468adL, 0x7f40011001012345L, 0x7ff0000000000000L,
- 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L,
- 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L,
- 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L,
- 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L,
- 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L,
- 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L,
- 0x7ff0000000000000L, 0x7ff0000000000000L };
-
- for (int i = 0; i < expecteds.length; i++) {
- int part = i*11;
- String inputString = "0x" + part + "." + part + "0123456789abcdefp" + part;
-
- double actual = Double.parseDouble(inputString);
- double expected = Double.longBitsToDouble(expecteds[i]);
-
- String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected));
- String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual));
- String errorMsg = i + "th input string is:<" + inputString
- + ">.The expected result should be:<" + expectedString
- + ">, but was: <" + actualString + ">. ";
-
- assertEquals(errorMsg, expected, actual, 0.0D);
- }
- }
-
- /**
- * @tests java.lang.Double#parseDouble(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies positive functionality.",
- method = "parseDouble",
- args = {java.lang.String.class}
- )
- public void test_parseDouble_LString_NormalNegativeExponent() {
- long[] expecteds = {
- 0x3f323456789abcdfL, 0x3f8111012345678aL, 0x3ee1110091a2b3c5L,
- 0x3e39998091a2b3c5L, 0x3d91110048d159e2L, 0x3ce5554048d159e2L,
- 0x3c39998048d159e2L, 0x3b8dddc048d159e2L, 0x3ae111002468acf1L,
- 0x3a3333202468acf1L, 0x3991011001234568L, 0x38e2112101234568L,
- 0x3833213201234568L, 0x3784314301234568L, 0x36d5415401234568L,
- 0x3626516501234568L, 0x3577617601234568L, 0x34c8718701234568L,
- 0x3419819801234568L, 0x337049048091a2b4L, 0x32c101100091a2b4L,
- 0x321189188091a2b4L, 0x316211210091a2b4L, 0x30b299298091a2b4L,
- 0x300321320091a2b4L, 0x2f53a93a8091a2b4L, 0x2ea431430091a2b4L,
- 0x2df4b94b8091a2b4L, 0x2d4841840091a2b4L, 0x2c98c98c8091a2b4L,
- 0x2be981980091a2b4L, 0x2b3a09a08091a2b4L, 0x2a8a91a90091a2b4L,
- 0x29db19b18091a2b4L, 0x292ba1ba0091a2b4L, 0x287c29c28091a2b4L,
- 0x27ccb1cb0091a2b4L, 0x27201d01c048d15aL, 0x267061060048d15aL,
- 0x25c0a50a4048d15aL, 0x251101100048d15aL, 0x246145144048d15aL,
- 0x23b189188048d15aL, 0x2301cd1cc048d15aL, 0x225211210048d15aL,
- 0x21a255254048d15aL, 0x20f419418048d15aL, 0x20445d45c048d15aL,
- 0x1f94a14a0048d15aL, 0x1ee4e54e4048d15aL, 0x1e3541540048d15aL,
- 0x1d8585584048d15aL, 0x1cd5c95c8048d15aL, 0x1c260d60c048d15aL,
- 0x1b7651650048d15aL, 0x1ac815814048d15aL, 0x1a1859858048d15aL,
- 0x19689d89c048d15aL, 0x18b8e18e0048d15aL, 0x180925924048d15aL,
- 0x175981980048d15aL, 0x16a9c59c4048d15aL, 0x15fa09a08048d15aL,
- 0x154a4da4c048d15aL, 0x149c11c10048d15aL, 0x13ec55c54048d15aL,
- 0x133c99c98048d15aL, 0x128cddcdc048d15aL, 0x11dd21d20048d15aL,
- 0x112d65d64048d15aL, 0x107dc1dc0048d15aL, 0xfce05e04048d15aL,
- 0xf1e49e48048d15aL, 0xe700700602468adL, 0xdc02902802468adL,
- 0xd104b04a02468adL, 0xc606d06c02468adL, 0xbb08f08e02468adL,
- 0xb00b10b002468adL, 0xa50d30d202468adL, 0x9a10110002468adL,
- 0x8f12312202468adL, 0x8420520402468adL, 0x7922722602468adL,
- 0x6e24924802468adL, 0x6326b26a02468adL, 0x5828d28c02468adL,
- 0x4d2af2ae02468adL, 0x422d12d002468adL, 0x372f32f202468adL,
- 0x2c32132002468adL, 0x220011001012345L, 0x170121012012345L,
- 0xc0231023012345L, 0x10341034012345L, 0x208a208a024L,
- 0x41584158L, 0x83388L, 0x108L,
- 0x0L, 0x0L, 0x0L,
- 0x0L, 0x0L, 0x0L,
- 0x0L, 0x0L, 0x0L,
- 0x0L, 0x0L, 0x0L,
- 0x0L, 0x0L };
-
- for (int i = 0; i < expecteds.length; i++) {
- int part = i*11;
- String inputString = "0x" + part + "." + part + "0123456789abcdefp-" + part;
-
- double actual = Double.parseDouble(inputString);
- double expected = Double.longBitsToDouble(expecteds[i]);
-
- String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected));
- String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual));
- String errorMsg = i + "th input string is:<" + inputString
- + ">.The expected result should be:<" + expectedString
- + ">, but was: <" + actualString + ">. ";
-
- assertEquals(errorMsg, expected, actual, 0.0D);
- }
- }
-
- /**
- * @tests java.lang.Double#parseDouble(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies max boundary.",
- method = "parseDouble",
- args = {java.lang.String.class}
- )
- public void test_parseDouble_LString_MaxNormalBoundary() {
- long[] expecteds = {
- 0x7fefffffffffffffL, 0x7fefffffffffffffL, 0x7fefffffffffffffL,
- 0x7fefffffffffffffL, 0x7fefffffffffffffL, 0x7fefffffffffffffL,
- 0x7fefffffffffffffL, 0x7ff0000000000000L, 0x7ff0000000000000L,
- 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L,
- 0x7ff0000000000000L, 0x7ff0000000000000L, 0x7ff0000000000000L,
-
- 0xffefffffffffffffL, 0xffefffffffffffffL, 0xffefffffffffffffL,
- 0xffefffffffffffffL, 0xffefffffffffffffL, 0xffefffffffffffffL,
- 0xffefffffffffffffL, 0xfff0000000000000L, 0xfff0000000000000L,
- 0xfff0000000000000L, 0xfff0000000000000L, 0xfff0000000000000L,
- 0xfff0000000000000L, 0xfff0000000000000L, 0xfff0000000000000L };
-
- String[] inputs = {
- "0x1.fffffffffffffp1023",
- "0x1.fffffffffffff000000000000000000000000001p1023",
- "0x1.fffffffffffff1p1023",
- "0x1.fffffffffffff100000000000000000000000001p1023",
- "0x1.fffffffffffff1fffffffffffffffffffffffffffffffffffffffffffffp1023",
- "0x1.fffffffffffff7p1023",
- "0x1.fffffffffffff700000000000000000000000001p1023",
- "0x1.fffffffffffff8p1023",
- "0x1.fffffffffffff800000000000000000000000001p1023",
- "0x1.fffffffffffff8fffffffffffffffffffffffffffffffffffffffffffffp1023",
- "0x1.fffffffffffff9p1023",
- "0x1.fffffffffffff900000000000000000000000001p1023",
- "0x1.ffffffffffffffp1023",
- "0x1.ffffffffffffff00000000000000000000000001p1023",
- "0x1.fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp1023",
-
- "-0x1.fffffffffffffp1023",
- "-0x1.fffffffffffff000000000000000000000000001p1023",
- "-0x1.fffffffffffff1p1023",
- "-0x1.fffffffffffff100000000000000000000000001p1023",
- "-0x1.fffffffffffff1fffffffffffffffffffffffffffffffffffffffffffffp1023",
- "-0x1.fffffffffffff7p1023",
- "-0x1.fffffffffffff700000000000000000000000001p1023",
- "-0x1.fffffffffffff8p1023",
- "-0x1.fffffffffffff800000000000000000000000001p1023",
- "-0x1.fffffffffffff8fffffffffffffffffffffffffffffffffffffffffffffp1023",
- "-0x1.fffffffffffff9p1023",
- "-0x1.fffffffffffff900000000000000000000000001p1023",
- "-0x1.ffffffffffffffp1023",
- "-0x1.ffffffffffffff00000000000000000000000001p1023",
- "-0x1.fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp1023" };
-
- for (int i = 0; i < inputs.length; i++) {
- double actual = Double.parseDouble(inputs[i]);
- double expected = Double.longBitsToDouble(expecteds[i]);
-
- String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected));
- String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual));
- String errorMsg = i + "th input string is:<" + inputs[i]
- + ">.The expected result should be:<" + expectedString
- + ">, but was: <" + actualString + ">. ";
-
- assertEquals(errorMsg, expected, actual, 0.0D);
- }
- }
-
- /**
- * @tests java.lang.Double#parseDouble(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies Min boundary.",
- method = "parseDouble",
- args = {java.lang.String.class}
- )
- public void test_parseDouble_LString_MinNormalBoundary() {
- long[] expecteds = {
- 0x10000000000000L, 0x10000000000000L, 0x10000000000000L,
- 0x10000000000000L, 0x10000000000000L, 0x10000000000000L,
- 0x10000000000000L, 0x10000000000000L, 0x10000000000001L,
- 0x10000000000001L, 0x10000000000001L, 0x10000000000001L,
- 0x10000000000001L, 0x10000000000001L, 0x10000000000001L,
-
- 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L,
- 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L,
- 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000001L,
- 0x8010000000000001L, 0x8010000000000001L, 0x8010000000000001L,
- 0x8010000000000001L, 0x8010000000000001L, 0x8010000000000001L };
-
- String[] inputs = {
- "0x1.0p-1022",
- "0x1.00000000000001p-1022",
- "0x1.000000000000010000000000000000001p-1022",
- "0x1.00000000000001fffffffffffffffffffffffffffffffffp-1022",
- "0x1.00000000000007p-1022",
- "0x1.000000000000070000000000000000001p-1022",
- "0x1.00000000000007fffffffffffffffffffffffffffffffffp-1022",
- "0x1.00000000000008p-1022",
- "0x1.000000000000080000000000000000001p-1022",
- "0x1.00000000000008fffffffffffffffffffffffffffffffffp-1022",
- "0x1.00000000000009p-1022",
- "0x1.000000000000090000000000000000001p-1022",
- "0x1.00000000000009fffffffffffffffffffffffffffffffffp-1022",
- "0x1.0000000000000fp-1022",
- "0x1.0000000000000ffffffffffffffffffffffffffffffffffp-1022",
-
- "-0x1.0p-1022",
- "-0x1.00000000000001p-1022",
- "-0x1.000000000000010000000000000000001p-1022",
- "-0x1.00000000000001fffffffffffffffffffffffffffffffffp-1022",
- "-0x1.00000000000007p-1022",
- "-0x1.000000000000070000000000000000001p-1022",
- "-0x1.00000000000007fffffffffffffffffffffffffffffffffp-1022",
- "-0x1.00000000000008p-1022",
- "-0x1.000000000000080000000000000000001p-1022",
- "-0x1.00000000000008fffffffffffffffffffffffffffffffffp-1022",
- "-0x1.00000000000009p-1022",
- "-0x1.000000000000090000000000000000001p-1022",
- "-0x1.00000000000009fffffffffffffffffffffffffffffffffp-1022",
- "-0x1.0000000000000fp-1022",
- "-0x1.0000000000000ffffffffffffffffffffffffffffffffffp-1022" };
-
- for (int i = 0; i < inputs.length; i++) {
- double actual = Double.parseDouble(inputs[i]);
- double expected = Double.longBitsToDouble(expecteds[i]);
-
- String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected));
- String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual));
- String errorMsg = i + "th input string is:<" + inputs[i]
- + ">.The expected result should be:<" + expectedString
- + ">, but was: <" + actualString + ">. ";
-
- assertEquals(errorMsg, expected, actual, 0.0D);
- }
- }
-
- /**
- * @tests java.lang.Double#parseDouble(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies Max boundary.",
- method = "parseDouble",
- args = {java.lang.String.class}
- )
- public void test_parseDouble_LString_MaxSubNormalBoundary() {
- long[] expecteds = {
- 0xfffffffffffffL, 0xfffffffffffffL, 0xfffffffffffffL,
- 0xfffffffffffffL, 0xfffffffffffffL, 0xfffffffffffffL,
- 0xfffffffffffffL, 0x10000000000000L, 0x10000000000000L,
- 0x10000000000000L, 0x10000000000000L, 0x10000000000000L,
- 0x10000000000000L, 0x10000000000000L, 0x10000000000000L,
-
- 0x800fffffffffffffL, 0x800fffffffffffffL, 0x800fffffffffffffL,
- 0x800fffffffffffffL, 0x800fffffffffffffL, 0x800fffffffffffffL,
- 0x800fffffffffffffL, 0x8010000000000000L, 0x8010000000000000L,
- 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L,
- 0x8010000000000000L, 0x8010000000000000L, 0x8010000000000000L };
-
- String[] inputs = {
- "0x0.fffffffffffffp-1022",
- "0x0.fffffffffffff00000000000000000000000000000000001p-1022",
- "0x0.fffffffffffff1p-1022",
- "0x0.fffffffffffff10000000000000000000000000000000001p-1022",
- "0x0.fffffffffffff1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022",
- "0x0.fffffffffffff7p-1022",
- "0x0.fffffffffffff7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022",
- "0x0.fffffffffffff8p-1022",
- "0x0.fffffffffffff80000000000000000000000000000000001p-1022",
- "0x0.fffffffffffff8ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022",
- "0x0.fffffffffffff9p-1022",
- "0x0.fffffffffffff9ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022",
- "0x0.ffffffffffffffp-1022",
- "0x0.ffffffffffffff0000000000000000000000000000000001p-1022",
- "0x0.ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022",
-
- "-0x0.fffffffffffffp-1022",
- "-0x0.fffffffffffff00000000000000000000000000000000001p-1022",
- "-0x0.fffffffffffff1p-1022",
- "-0x0.fffffffffffff10000000000000000000000000000000001p-1022",
- "-0x0.fffffffffffff1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022",
- "-0x0.fffffffffffff7p-1022",
- "-0x0.fffffffffffff7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022",
- "-0x0.fffffffffffff8p-1022",
- "-0x0.fffffffffffff80000000000000000000000000000000001p-1022",
- "-0x0.fffffffffffff8ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022",
- "-0x0.fffffffffffff9p-1022",
- "-0x0.fffffffffffff9ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022",
- "-0x0.ffffffffffffffp-1022",
- "-0x0.ffffffffffffff0000000000000000000000000000000001p-1022",
- "-0x0.ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-1022" };
-
- for (int i = 0; i < inputs.length; i++) {
- double actual = Double.parseDouble(inputs[i]);
- double expected = Double.longBitsToDouble(expecteds[i]);
-
- String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected));
- String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual));
- String errorMsg = i + "th input string is:<" + inputs[i]
- + ">.The expected result should be:<" + expectedString
- + ">, but was: <" + actualString + ">. ";
-
- assertEquals(errorMsg, expected, actual, 0.0D);
- }
- }
-
- /**
- * @tests java.lang.Double#parseDouble(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies Min boundary.",
- method = "parseDouble",
- args = {java.lang.String.class}
- )
- public void test_parseDouble_LString_MinSubNormalBoundary() {
- long[] expecteds = {
- 0x1L, 0x1L, 0x2L,
- 0x1L, 0x1L, 0x1L,
- 0x2L, 0x2L, 0x2L,
- 0x2L, 0x2L, 0x2L,
- 0x2L, 0x2L, 0x2L,
-
- 0x8000000000000001L, 0x8000000000000001L, 0x8000000000000002L,
- 0x8000000000000001L, 0x8000000000000001L, 0x8000000000000001L,
- 0x8000000000000002L, 0x8000000000000002L, 0x8000000000000002L,
- 0x8000000000000002L, 0x8000000000000002L, 0x8000000000000002L,
- 0x8000000000000002L, 0x8000000000000002L, 0x8000000000000002L };
-
- String[] inputs = {
- "0x0.0000000000001p-1022",
- "0x0.00000000000010000000000000000001p-1022",
- "0x0.0000000000001fffffffffffffffffffffffffffffffffp-1022",
- "0x0.00000000000017p-1022",
- "0x0.000000000000170000000000000000001p-1022",
- "0x0.00000000000017fffffffffffffffffffffffffffffffffp-1022",
- "0x0.00000000000018p-1022",
- "0x0.000000000000180000000000000000001p-1022",
- "0x0.00000000000018fffffffffffffffffffffffffffffffffp-1022",
- "0x0.00000000000019p-1022",
- "0x0.000000000000190000000000000000001p-1022",
- "0x0.00000000000019fffffffffffffffffffffffffffffffffp-1022",
- "0x0.0000000000001fp-1022",
- "0x0.0000000000001f0000000000000000001p-1022",
- "0x0.0000000000001ffffffffffffffffffffffffffffffffffp-1022",
-
- "-0x0.0000000000001p-1022",
- "-0x0.00000000000010000000000000000001p-1022",
- "-0x0.0000000000001fffffffffffffffffffffffffffffffffp-1022",
- "-0x0.00000000000017p-1022",
- "-0x0.000000000000170000000000000000001p-1022",
- "-0x0.00000000000017fffffffffffffffffffffffffffffffffp-1022",
- "-0x0.00000000000018p-1022",
- "-0x0.000000000000180000000000000000001p-1022",
- "-0x0.00000000000018fffffffffffffffffffffffffffffffffp-1022",
- "-0x0.00000000000019p-1022",
- "-0x0.000000000000190000000000000000001p-1022",
- "-0x0.00000000000019fffffffffffffffffffffffffffffffffp-1022",
- "-0x0.0000000000001fp-1022",
- "-0x0.0000000000001f0000000000000000001p-1022",
- "-0x0.0000000000001ffffffffffffffffffffffffffffffffffp-1022" };
-
- for (int i = 0; i < inputs.length; i++) {
- double actual = Double.parseDouble(inputs[i]);
- double expected = Double.longBitsToDouble(expecteds[i]);
-
- String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected));
- String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual));
- String errorMsg = i + "th input string is:<" + inputs[i]
- + ">.The expected result should be:<" + expectedString
- + ">, but was: <" + actualString + ">. ";
-
- assertEquals(errorMsg, expected, actual, 0.0D);
- }
- }
-
- /**
- * @tests java.lang.Double#parseDouble(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies zero boundary.",
- method = "parseDouble",
- args = {java.lang.String.class}
- )
- public void test_parseDouble_LString_ZeroBoundary() {
- long[] expecteds = {
- 0x0L, 0x0L, 0x0L,
- 0x1L, 0x1L, 0x1L,
- 0x1L, 0x1L, 0x1L,
- 0x8000000000000000L, 0x8000000000000000L, 0x8000000000000000L,
- 0x8000000000000001L, 0x8000000000000001L, 0x8000000000000001L,
- 0x8000000000000001L, 0x8000000000000001L, 0x8000000000000001L };
-
- String[] inputs = {
- "0x0.00000000000004p-1022",
- "0x0.00000000000007ffffffffffffffffffffffp-1022",
- "0x0.00000000000008p-1022",
- "0x0.000000000000080000000000000000001p-1022",
- "0x0.00000000000008fffffffffffffffffffffffffffffffp-1022",
- "0x0.00000000000009p-1022",
- "0x0.000000000000090000000000000000001p-1022",
- "0x0.00000000000009fffffffffffffffffffffffffffffffffp-1022",
- "0x0.0000000000000fffffffffffffffffffffffffffffffffffp-1022",
-
- "-0x0.00000000000004p-1022",
- "-0x0.00000000000007ffffffffffffffffffffffp-1022",
- "-0x0.00000000000008p-1022",
- "-0x0.000000000000080000000000000000001p-1022",
- "-0x0.00000000000008fffffffffffffffffffffffffffffffp-1022",
- "-0x0.00000000000009p-1022",
- "-0x0.000000000000090000000000000000001p-1022",
- "-0x0.00000000000009fffffffffffffffffffffffffffffffffp-1022",
- "-0x0.0000000000000fffffffffffffffffffffffffffffffffffp-1022" };
-
- for (int i = 0; i < inputs.length; i++) {
- double actual = Double.parseDouble(inputs[i]);
- double expected = Double.longBitsToDouble(expecteds[i]);
-
- String expectedString = "0x" + Long.toHexString(Double.doubleToLongBits(expected));
- String actualString = "0x" + Long.toHexString(Double.doubleToLongBits(actual));
- String errorMsg = i + "th input string is:<" + inputs[i]
- + ">.The expected result should be:<" + expectedString
- + ">, but was: <" + actualString + ">. ";
-
- assertEquals(errorMsg, expected, actual, 0.0D);
- }
- }
-
- /**
- * @tests java.lang.Double#shortValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "shortValue",
- args = {}
- )
- public void test_shortValue() {
- // Test for method short java.lang.Double.shortValue()
- Double d = new Double(1923311.47712);
- assertEquals("Returned incorrect short value", 22767, d.shortValue());
- }
-
- /**
- * @tests java.lang.Double#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.lang.Double.toString()
- test_toString(1.7976931348623157E308, "1.7976931348623157E308");
- test_toString(5.0E-4, "5.0E-4");
- }
-
- /**
- * @tests java.lang.Double#toString(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {double.class}
- )
- public void test_toStringD() {
- // Test for method java.lang.String java.lang.Double.toString(double)
- test_toString(1.7976931348623157E308, "1.7976931348623157E308");
- test_toString(1.0 / 0.0, "Infinity");
- test_toString(0.0 / 0.0, "NaN");
- test_toString(-1.0 / 0.0, "-Infinity");
-
- double d;
- d = Double.longBitsToDouble(0x470fffffffffffffL);
- test_toString(d, "2.0769187434139308E34");
- d = Double.longBitsToDouble(0x4710000000000000L);
- test_toString(d, "2.076918743413931E34");
-
- d = Double.longBitsToDouble(0x470000000000000aL);
- test_toString(d, "1.0384593717069678E34");
- d = Double.longBitsToDouble(0x470000000000000bL);
- test_toString(d, "1.038459371706968E34");
-
- d = Double.longBitsToDouble(0x4700000000000017L);
- test_toString(d, "1.0384593717069708E34");
- d = Double.longBitsToDouble(0x4700000000000018L);
- test_toString(d, "1.038459371706971E34");
-
- d = Double.longBitsToDouble(0x4700000000000024L);
- test_toString(d, "1.0384593717069738E34");
- d = Double.longBitsToDouble(0x4700000000000025L);
- test_toString(d, "1.038459371706974E34");
-
- d = Double.longBitsToDouble(0x4700000000000031L);
- test_toString(d, "1.0384593717069768E34");
- d = Double.longBitsToDouble(0x4700000000000032L);
- test_toString(d, "1.038459371706977E34");
-
- d = Double.longBitsToDouble(0x470000000000003eL);
- test_toString(d, "1.0384593717069798E34");
- d = Double.longBitsToDouble(0x470000000000003fL);
- test_toString(d, "1.03845937170698E34");
-
- d = Double.longBitsToDouble(0x7e00000000000003L);
- test_toString(d, "8.371160993642719E298");
- d = Double.longBitsToDouble(0x7e00000000000004L);
- test_toString(d, "8.37116099364272E298");
-
- d = Double.longBitsToDouble(0x7e00000000000008L);
- test_toString(d, "8.371160993642728E298");
- d = Double.longBitsToDouble(0x7e00000000000009L);
- test_toString(d, "8.37116099364273E298");
-
- d = Double.longBitsToDouble(0x7e00000000000013L);
- test_toString(d, "8.371160993642749E298");
- d = Double.longBitsToDouble(0x7e00000000000014L);
- test_toString(d, "8.37116099364275E298");
-
- d = Double.longBitsToDouble(0x7e00000000000023L);
- test_toString(d, "8.371160993642779E298");
- d = Double.longBitsToDouble(0x7e00000000000024L);
- test_toString(d, "8.37116099364278E298");
-
- d = Double.longBitsToDouble(0x7e0000000000002eL);
- test_toString(d, "8.371160993642799E298");
- d = Double.longBitsToDouble(0x7e0000000000002fL);
- test_toString(d, "8.3711609936428E298");
-
- d = Double.longBitsToDouble(0xda00000000000001L);
- test_toString(d, "-3.3846065602060736E125");
- d = Double.longBitsToDouble(0xda00000000000002L);
- test_toString(d, "-3.384606560206074E125");
-
- d = Double.longBitsToDouble(0xda00000000000005L);
- test_toString(d, "-3.3846065602060766E125");
- d = Double.longBitsToDouble(0xda00000000000006L);
- test_toString(d, "-3.384606560206077E125");
-
- d = Double.longBitsToDouble(0xda00000000000009L);
- test_toString(d, "-3.3846065602060796E125");
- d = Double.longBitsToDouble(0xda0000000000000aL);
- test_toString(d, "-3.38460656020608E125");
-
- d = Double.longBitsToDouble(0xda0000000000000dL);
- test_toString(d, "-3.3846065602060826E125");
- d = Double.longBitsToDouble(0xda0000000000000eL);
- test_toString(d, "-3.384606560206083E125");
- }
-
- /**
- * @tests java.lang.Double#valueOf(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {java.lang.String.class}
- )
- public void test_valueOfLjava_lang_String() {
- // Test for method java.lang.Double
- // java.lang.Double.valueOf(java.lang.String)
- assertTrue("Incorrect double returned", Math.abs(Double.valueOf("999999999999.999")
- .doubleValue() - 999999999999.999d) < 1);
-
- try {
- Double.valueOf(null);
- fail("Expected Double.valueOf(null) to throw NPE.");
- } catch (NullPointerException ex) {
- // expected
- } catch (Throwable ex) {
- fail("Expected Double.valueOf(null) to throw NPE not " + ex.getClass().getName());
- }
-
- try {
- Double.valueOf("");
- fail("Expected Double.valueOf(\"\") to throw NFE");
- } catch (NumberFormatException e) {
- // expected
- }
-
- Double pi = Double.valueOf("3.141592654");
- assertEquals(3.141592654, pi.doubleValue(), 0D);
-
- Double posZero = Double.valueOf("+0.0");
- Double negZero = Double.valueOf("-0.0");
- assertFalse("Doubletest0", posZero.equals(negZero));
-
- // Tests for double values by name.
- Double expectedNaN = new Double(Double.NaN);
-
- Double posNaN = Double.valueOf("NaN");
- assertTrue("Doubletest1", posNaN.equals(expectedNaN));
-
- Double posNaNSigned = Double.valueOf("+NaN");
- assertTrue("Doubletest2", posNaNSigned.equals(expectedNaN));
-
- Double negNaNSigned = Double.valueOf("-NaN");
- assertTrue("Doubletest3", negNaNSigned.equals(expectedNaN));
-
- Double posInfinite = Double.valueOf("Infinity");
- assertTrue("Doubletest4", posInfinite.equals(new Double(Double.POSITIVE_INFINITY)));
-
- Double posInfiniteSigned = Double.valueOf("+Infinity");
- assertTrue("Doubletest5", posInfiniteSigned
- .equals(new Double(Double.POSITIVE_INFINITY)));
-
- Double negInfiniteSigned = Double.valueOf("-Infinity");
- assertTrue("Doubletest6", negInfiniteSigned
- .equals(new Double(Double.NEGATIVE_INFINITY)));
- }
-
- /**
- * @tests java.lang.Double#compareTo(java.lang.Double)
- * @tests java.lang.Double#compare(double, double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.lang.Double.class}
- )
- public void test_compareToLjava_lang_Double() {
- // A selection of double values in ascending order.
- double[] values = new double[] { Double.NEGATIVE_INFINITY, -Double.MAX_VALUE, -2d,
- -Double.MIN_VALUE, -0d, 0d, Double.MIN_VALUE, 2d, Double.MAX_VALUE,
- Double.POSITIVE_INFINITY, Double.NaN };
- for (int i = 0; i < values.length; i++) {
- double d1 = values[i];
-
- // Test that each value compares equal to itself; and each object is
- // equal to another object like itself.
- assertTrue("Assert 0: compare() should be equal: " + d1,
- Double.compare(d1, d1) == 0);
- Double objDouble = new Double(d1);
- assertTrue("Assert 1: compareTo() should be equal: " + d1, objDouble
- .compareTo(objDouble) == 0);
-
- // Test that the Double-defined order is respected
- for (int j = i + 1; j < values.length; j++) {
- double d2 = values[j];
- assertTrue("Assert 2: compare() " + d1 + " should be less " + d2, Double
- .compare(d1, d2) == -1);
- assertTrue("Assert 3: compare() " + d2 + " should be greater " + d1, Double
- .compare(d2, d1) == 1);
- Double D2 = new Double(d2);
- assertTrue("Assert 4: compareTo() " + d1 + " should be less " + d2, objDouble
- .compareTo(D2) == -1);
- assertTrue("Assert 5: compareTo() " + d2 + " should be greater " + d1, D2
- .compareTo(objDouble) == 1);
- }
- }
-
- try {
- new Double(0.0D).compareTo(null);
- fail("No NPE");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @tests java.lang.Double#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- Double d1 = new Double(87654321.12345d);
- Double d2 = new Double(87654321.12345d);
- Double d3 = new Double(0.0002f);
- assertTrue("Assert 0: Equality test failed", d1.equals(d2) && !(d1.equals(d3)));
-
- assertTrue("Assert 2: NaN should not be == Nan", Double.NaN != Double.NaN);
- assertTrue("Assert 3: NaN should not be == Nan", new Double(Double.NaN)
- .equals(new Double(Double.NaN)));
- assertTrue("Assert 4: -0d should be == 0d", 0d == -0d);
- assertTrue("Assert 5: -0d should not be equals() 0d", !new Double(0d)
- .equals(new Double(-0d)));
-
- Double dmax = new Double(Double.MAX_VALUE);
- Double dmax1 = new Double(Double.MAX_VALUE);
-
- assertTrue("Equality test failed", dmax.equals(dmax1) && !(dmax.equals(new Object())));
- }
-
- /**
- * @tests java.lang.Double#toHexString(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toHexString",
- args = {double.class}
- )
- public void test_toHexStringF() {
- // the follow values come from the Double Javadoc/Spec
- assertEquals("0x0.0p0", Double.toHexString(0.0D));
- assertEquals("-0x0.0p0", Double.toHexString(-0.0D));
- assertEquals("0x1.0p0", Double.toHexString(1.0D));
- assertEquals("-0x1.0p0", Double.toHexString(-1.0D));
- assertEquals("0x1.0p1", Double.toHexString(2.0D));
- assertEquals("0x1.8p1", Double.toHexString(3.0D));
- assertEquals("0x1.0p-1", Double.toHexString(0.5D));
- assertEquals("0x1.0p-2", Double.toHexString(0.25D));
- assertEquals("0x1.fffffffffffffp1023", Double.toHexString(Double.MAX_VALUE));
- assertEquals("0x0.0000000000001p-1022", Double.toHexString(Double.MIN_VALUE));
-
- // test edge cases
- assertEquals("NaN", Double.toHexString(Double.NaN));
- assertEquals("-Infinity", Double.toHexString(Double.NEGATIVE_INFINITY));
- assertEquals("Infinity", Double.toHexString(Double.POSITIVE_INFINITY));
-
- // test various numbers
- assertEquals("-0x1.da8p6", Double.toHexString(-118.625D));
- assertEquals("0x1.2957874cccccdp23", Double.toHexString(9743299.65D));
- assertEquals("0x1.2957874cccccdp23", Double.toHexString(9743299.65000D));
- assertEquals("0x1.2957874cccf63p23", Double.toHexString(9743299.650001234D));
- assertEquals("0x1.700d1061d3333p33", Double.toHexString(12349743299.65000D));
-
- // test HARMONY-2132
- assertEquals("0x1.01p10", Double.toHexString(0x1.01p10));
- }
-
- /**
- * @tests java.lang.Double#valueOf(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {double.class}
- )
- public void test_valueOfD() {
- assertEquals(new Double(Double.MIN_VALUE), Double.valueOf(Double.MIN_VALUE));
- assertEquals(new Double(Double.MAX_VALUE), Double.valueOf(Double.MAX_VALUE));
- assertEquals(new Double(0), Double.valueOf(0));
-
- int s = -128;
- while (s < 128) {
- assertEquals(new Double(s), Double.valueOf(s));
- assertEquals(new Double(s + 0.1D), Double.valueOf(s + 0.1D));
- s++;
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/EnumConstantNotPresentExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/EnumConstantNotPresentExceptionTest.java
deleted file mode 100644
index d91584b..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/EnumConstantNotPresentExceptionTest.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/* 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(EnumConstantNotPresentException.class)
-public class EnumConstantNotPresentExceptionTest extends TestCase {
-
- public enum Fixture {
- ONE,TWO,THREE
- }
-
- /**
- * @test java.lang.EnumConstantNotPresentException#EnumConstantNotPresentException(Class<?
- * extends Enum>, String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "EnumConstantNotPresentException",
- args = {java.lang.Class.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_ClassLjava_lang_String() {
- String tm = "Test Message";
- EnumConstantNotPresentException ecnpe = new
- EnumConstantNotPresentException(Fixture.class, tm);
-
- assertEquals("Constant name is incorrect: " + ecnpe.constantName() +
- " instead of " + tm, tm, ecnpe.constantName());
-
- try {
- new EnumConstantNotPresentException(null, "");
- fail("No NPE");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @test java.lang.EnumConstantNotPresentException#enumType()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "enumType",
- args = {}
- )
- public void test_enumType() {
- EnumConstantNotPresentException e = new EnumConstantNotPresentException(Fixture.class, "FOUR");
- assertEquals(Fixture.class, e.enumType());
- }
-
- /**
- * @test java.lang.EnumConstantNotPresentException#constantName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "constantName",
- args = {}
- )
- public void test_constantName() {
- EnumConstantNotPresentException e = new EnumConstantNotPresentException(Fixture.class, "FOUR");
- assertEquals("FOUR", e.constantName());
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/EnumTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/EnumTest.java
deleted file mode 100644
index ccaddeb..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/EnumTest.java
+++ /dev/null
@@ -1,346 +0,0 @@
-/* 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-import tests.util.SerializationTester;
-
-import java.util.HashMap;
-
-@TestTargetClass(Enum.class)
-public class EnumTest extends TestCase {
-
- enum Sample {
- LARRY, MOE, CURLY
- }
-
- Sample larry = Sample.LARRY;
-
- Sample moe = Sample.MOE;
-
- enum Empty {
- }
-
- enum Bogus {
- UNUSED
- }
-
- enum Color {
- Red, Green, Blue {};
- }
-
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "Can't be tested, according to the spec this constructor can't be invoked.",
- method = "Enum",
- args = {java.lang.String.class, int.class}
- )
- public void test_EnumLStringLlang() {
- //TODO
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "Can't be tested, according to the spec.",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- //TODO
- }
-
- /**
- * @tests java.lang.Enum#compareTo(java.lang.Enum)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.lang.Enum.class}
- )
- public void test_compareToLjava_lang_Enum() {
- assertTrue(0 < Sample.MOE.compareTo(Sample.LARRY));
- assertEquals(0, Sample.MOE.compareTo(Sample.MOE));
- assertTrue(0 > Sample.MOE.compareTo(Sample.CURLY));
- try {
- Sample.MOE.compareTo((Sample)null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.Enum#equals(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- assertFalse(moe.equals("bob"));
- assertTrue(moe.equals(Sample.MOE));
- assertFalse(Sample.LARRY.equals(Sample.CURLY));
- assertTrue(Sample.LARRY.equals(larry));
- assertFalse(Sample.CURLY.equals(null));
- }
-
- /**
- * @tests java.lang.Enum#getDeclaringClass()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaringClass",
- args = {}
- )
- public void test_getDeclaringClass() {
- assertEquals(Sample.class, moe.getDeclaringClass());
- }
-
- /**
- * @tests java.lang.Enum#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- assertEquals (moe.hashCode(), moe.hashCode());
- assertTrue (moe.hashCode() != Sample.LARRY.hashCode());
-
- }
-
- /**
- * @tests java.lang.Enum#name()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "name",
- args = {}
- )
- public void test_name() {
- assertEquals("MOE", moe.name());
- }
-
- /**
- * @tests java.lang.Enum#ordinal()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ordinal",
- args = {}
- )
- public void test_ordinal() {
- assertEquals(0, larry.ordinal());
- assertEquals(1, moe.ordinal());
- assertEquals(2, Sample.CURLY.ordinal());
- }
-
- /**
- * @tests java.lang.Enum#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- assertTrue(moe.toString().equals("MOE"));
- }
-
- /**
- * @tests java.lang.Enum#valueOf(Class, String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {java.lang.Class.class, java.lang.String.class}
- )
- public void test_valueOfLjava_lang_String() {
- assertSame(Sample.CURLY, Sample.valueOf("CURLY"));
- assertSame(Sample.LARRY, Sample.valueOf("LARRY"));
- assertSame(moe, Sample.valueOf("MOE"));
- try {
- Sample.valueOf("non-existant");
- fail("Expected an exception");
- } catch (IllegalArgumentException e){
- // Expected
- }
- try {
- Sample.valueOf(null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // May be caused by some compilers' code
- } catch (IllegalArgumentException e) {
- // other compilers will throw this
- }
-
-
- Sample s = Enum.valueOf(Sample.class, "CURLY");
- assertSame(s, Sample.CURLY);
- s = Enum.valueOf(Sample.class, "LARRY");
- assertSame(larry, s);
- s = Enum.valueOf(Sample.class, "MOE");
- assertSame(s, moe);
- try {
- Enum.valueOf(Bogus.class, "MOE");
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- try {
- Enum.valueOf((Class<Sample>)null, "a string");
- fail("Expected an exception");
- } catch (NullPointerException e) {
- // May be caused by some compilers' code
- } catch (IllegalArgumentException e) {
- // other compilers will throw this
- }
- try {
- Enum.valueOf(Sample.class, null);
- fail("Expected an exception");
- } catch (NullPointerException e) {
- // May be caused by some compilers' code
- } catch (IllegalArgumentException e) {
- // other compilers will throw this
- }
- try {
- Enum.valueOf((Class<Sample>)null, (String)null);
- fail("Expected an exception");
- } catch (NullPointerException e) {
- // May be caused by some compilers' code
- } catch (IllegalArgumentException e) {
- // other compilers will throw this
- }
- }
-
- /**
- * @tests java.lang.Enum#values
- */
- @TestTargetNew(
- level = TestLevel.TODO,
- notes = "Tests the values() method which is not in the API since it is" +
- "automatically created by the compiler for enum types",
- method = "!values",
- args = {}
- )
- public void test_values() {
- Sample[] myValues = Sample.values();
- assertEquals(3, myValues.length);
-
- assertEquals(Sample.LARRY, myValues[0]);
- assertEquals(Sample.MOE, myValues[1]);
- assertEquals(Sample.CURLY, myValues[2]);
-
- assertEquals(0, Empty.values().length);
- }
-
- /**
- * @test Serialization/deserilazation compatibility with Harmony.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Serialization/deserilazation compatibility.",
- method = "!SerializationGolden",
- args = {}
- )
- public void _test_compatibilitySerialization_inClass_Complex_Harmony() throws Exception{
- // TODO migrate to the new testing framework
- assertTrue(SerializationTester.assertCompabilityEquals(new MockEnum2(),
- "serialization/org/apache/harmony/luni/tests/java/lang/EnumTest.harmony.ser"));
- }
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- // test a map class that has enums.
- // regression test for Harmony-1163
- HashMap<Color, Integer> enumColorMap = new HashMap<Color, Integer>();
- enumColorMap.put(Color.Red, 1);
- enumColorMap.put(Color.Blue, 3);
-
- Object[] testCases = { enumColorMap, Sample.CURLY };
-
- SerializationTest.verifySelf(testCases);
-
- // test a class that has enums as its fields.
- MockEnum mock = new MockEnum();
- MockEnum test = (MockEnum) SerializationTest.copySerializable(mock);
- assertEquals(mock.i, test.i);
- assertEquals(mock.str, test.str);
- assertEquals(mock.samEnum, test.samEnum);
-
- // test a class that has enums and a string of same name as its fields.
- MockEnum2 mock2 = new MockEnum2();
- MockEnum2 test2 = (MockEnum2) SerializationTest.copySerializable(mock2);
- assertEquals(mock2.i, test2.i);
- assertEquals(mock2.str, test2.str);
- assertEquals(mock2.samEnum, test2.samEnum);
-
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- // regression test for Harmony-1163
- HashMap<Color, Integer> enumColorMap = new HashMap<Color, Integer>();
- enumColorMap.put(Color.Red, 1);
- enumColorMap.put(Color.Blue, 3);
-
- Object[] testCases = { Sample.CURLY, new MockEnum(),
- // test a class that has enums and a string of same name as its fields.
- new MockEnum2(),
- // test a map class that has enums.
- enumColorMap, };
-
- SerializationTest.verifyGolden(this, testCases);
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ErrorTest.java
deleted file mode 100644
index 03735c2..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ErrorTest.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(Error.class)
-public class ErrorTest extends TestCase {
-
- /**
- * @tests java.lang.Error#Error()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Error",
- args = {}
- )
- public void test_Constructor() {
- Error e = new Error();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.Error#Error(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Error",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- Error e = new Error("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Error",
- args = {java.lang.String.class, java.lang.Throwable.class}
- )
- public void test_ConstructorLjava_lang_StringLThrowable() {
- Throwable thr = new Throwable();
- String message = "Test message";
- Error err = new Error(message, thr);
- assertEquals(message, err.getMessage());
- assertEquals(thr, err.getCause());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Error",
- args = {java.lang.Throwable.class}
- )
- public void test_ConstructorLThrowable() {
- Throwable thr = new Throwable();
- Error err = new Error(thr);
- assertEquals(thr, err.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExceptionInInitializerErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExceptionInInitializerErrorTest.java
deleted file mode 100644
index 6614090..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExceptionInInitializerErrorTest.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(ExceptionInInitializerError.class)
-public class ExceptionInInitializerErrorTest extends junit.framework.TestCase {
-
- /**
- * @tests java.lang.ExceptionInInitializerError#ExceptionInInitializerError()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ExceptionInInitializerError",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCause",
- args = {}
- )
- })
- public void test_Constructor() {
- ExceptionInInitializerError e = new ExceptionInInitializerError();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.ExceptionInInitializerError#ExceptionInInitializerError(java.lang.String)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ExceptionInInitializerError",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCause",
- args = {}
- )
- })
- public void test_ConstructorLjava_lang_String() {
- ExceptionInInitializerError e = new ExceptionInInitializerError("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.ExceptionInInitializerExceptionInInitializerError#ExceptionInInitializerError(java.lang.Throwable)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ExceptionInInitializerError",
- args = {java.lang.Throwable.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCause",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getException",
- args = {}
- )
- })
- public void test_ConstructorLjava_lang_Throwable() {
- NullPointerException npe = new NullPointerException("fixture");
- ExceptionInInitializerError e = new ExceptionInInitializerError(npe);
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertSame(npe, e.getException());
- assertSame(npe, e.getCause());
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExceptionTest.java
deleted file mode 100644
index 9057269..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExceptionTest.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(Exception.class)
-public class ExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.Exception#Exception()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Exception",
- args = {}
- )
- public void test_Constructor() {
- Exception e = new Exception();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.Exception#Exception(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Exception",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- Exception e = new Exception("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Exception",
- args = {java.lang.String.class, java.lang.Throwable.class}
- )
- public void test_ConstructorLjava_lang_StringLThrowable() {
- Throwable thr = new Throwable();
- String message = "Test message";
- Exception err = new Exception(message, thr);
- assertEquals(message, err.getMessage());
- assertEquals(thr, err.getCause());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Exception",
- args = {java.lang.Throwable.class}
- )
- public void test_ConstructorLThrowable() {
- Throwable thr = new Throwable();
- Exception err = new Exception(thr);
- assertEquals(thr, err.getCause());
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExtendTestClass.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExtendTestClass.java
deleted file mode 100644
index 2b461f5..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExtendTestClass.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-@Deprecated
-@TestAnnotation("org.apache.harmony.luni.tests.java.lang.ExtendTestClass")
-public class ExtendTestClass extends PublicTestClass {
-
- private static final long serialVersionUID = 1L;
-
- public enum enumExm {ONE, TWO, THREE};
- @Override
- public void setCount(int value) {
-
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExtendTestClass1.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExtendTestClass1.java
deleted file mode 100644
index 8af91f1..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExtendTestClass1.java
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-public class ExtendTestClass1 extends ExtendTestClass {
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/FloatTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/FloatTest.java
deleted file mode 100644
index 2b03e5a..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/FloatTest.java
+++ /dev/null
@@ -1,1282 +0,0 @@
-/* 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(Float.class)
-public class FloatTest extends TestCase {
-
- private static final int rawBitsFor3_4eN38To38[] = { 0x1394470, 0x2e7958c, 0x490bd77, 0x634ecd5,
- 0x7e2280b, 0x98d5907, 0xb30af48, 0xcdcdb1a, 0xe8a08f0, 0x102c8b2d, 0x11d7adf8,
- 0x1386ccbb, 0x15287fe9, 0x16d29fe4, 0x1883a3ee, 0x1a248cea, 0x1bcdb025, 0x1d808e17,
- 0x1f20b19d, 0x20c8de04, 0x227b1585, 0x241ced73, 0x25c428d0, 0x27753303, 0x29193fe2,
- 0x2abf8fdb, 0x2c6f73d1, 0x2e15a863, 0x2fbb127c, 0x3169d71a, 0x33122671, 0x34b6b00d,
- 0x36645c10, 0x380eb98a, 0x39b267ec, 0x3b5f01e8, 0x3d0b6131, 0x3eae397d, 0x4059c7dc,
- 0x42081cea, 0x43aa2424, 0x4554ad2d, 0x4704ec3c, 0x48a6274b, 0x4a4fb11e, 0x4c01ceb3,
- 0x4da2425f, 0x4f4ad2f7, 0x50fd87b5, 0x529e74d1, 0x54461205, 0x55f79687, 0x579abe14,
- 0x59416d99, 0x5af1c900, 0x5c971da0, 0x5e3ce508, 0x5fec1e4a, 0x619392ee, 0x633877a9,
- 0x64e69594, 0x66901d7c, 0x683424dc, 0x69e12e12, 0x6b8cbccb, 0x6d2febfe, 0x6edbe6fe,
- 0x7089705f, 0x722bcc76, 0x73d6bf94, 0x758637bc, 0x7727c5ac, 0x78d1b717, 0x7a83126e,
- 0x7c23d70a, 0x7dcccccc, 0x7f7fffff };
-
- private static final String expectedStringFor3_4eN38To38[] = { "3.4028235E-38", "3.4028235E-37",
- "3.4028233E-36", "3.4028234E-35", "3.4028236E-34", "3.4028236E-33",
- "3.4028234E-32", "3.4028234E-31", "3.4028233E-30", "3.4028236E-29",
- "3.4028235E-28", "3.4028235E-27", "3.4028233E-26", "3.4028235E-25",
- "3.4028233E-24", "3.4028235E-23", "3.4028236E-22", "3.4028235E-21",
- "3.4028236E-20", "3.4028236E-19", "3.4028236E-18", "3.4028235E-17",
- "3.4028236E-16", "3.4028234E-15", "3.4028234E-14", "3.4028235E-13",
- "3.4028234E-12", "3.4028235E-11", "3.4028236E-10", "3.4028234E-9", "3.4028236E-8",
- "3.4028236E-7", "3.4028235E-6", "3.4028235E-5", "3.4028233E-4", "0.0034028236",
- "0.034028236", "0.34028235", "3.4028234", "34.028236", "340.28235", "3402.8235",
- "34028.234", "340282.34", "3402823.5", "3.4028236E7", "3.40282336E8",
- "3.40282342E9", "3.40282348E10", "3.40282343E11", "3.40282337E12", "3.40282353E13",
- "3.4028234E14", "3.4028234E15", "3.40282356E16", "3.40282356E17", "3.40282356E18",
- "3.4028236E19", "3.4028235E20", "3.4028233E21", "3.4028235E22", "3.4028233E23",
- "3.4028236E24", "3.4028234E25", "3.4028233E26", "3.4028234E27", "3.4028235E28",
- "3.4028236E29", "3.4028233E30", "3.4028235E31", "3.4028233E32", "3.4028236E33",
- "3.4028236E34", "3.4028234E35", "3.4028236E36", "3.4028235E37", "3.4028235E38" };
-
- private static final int rawBitsFor1_17eN38To38[] = { 0x80800000, 0x82200000, 0x83c80000,
- 0x857a0000, 0x871c4000, 0x88c35000, 0x8a742400, 0x8c189680, 0x8dbebc20, 0x8f6e6b28,
- 0x911502f9, 0x92ba43b7, 0x9468d4a5, 0x961184e7, 0x97b5e621, 0x99635fa9, 0x9b0e1bca,
- 0x9cb1a2bc, 0x9e5e0b6b, 0xa00ac723, 0xa1ad78ec, 0xa358d727, 0xa5078678, 0xa6a96816,
- 0xa853c21c, 0xaa045951, 0xaba56fa6, 0xad4ecb8f, 0xaf013f39, 0xb0a18f08, 0xb249f2ca,
- 0xb3fc6f7c, 0xb59dc5ae, 0xb7453719, 0xb8f684df, 0xba9a130c, 0xbc4097ce, 0xbdf0bdc2,
- 0xbf967699, 0xc13c1440, 0xc2eb1950, 0xc492efd2, 0xc637abc6, 0xc7e596b8, 0xc98f7e33,
- 0xcb335dc0, 0xcce0352f, 0xce8c213e, 0xd02f298d, 0xd1daf3f0, 0xd388d876, 0xd52b0e94,
- 0xd6d5d239, 0xd885a363, 0xda270c3c, 0xdbd0cf4b, 0xdd82818f, 0xdf2321f3, 0xe0cbea70,
- 0xe27ee50b, 0xe41f4f27, 0xe5c722f1, 0xe778ebad, 0xe91b934c, 0xeac2781f, 0xec731627,
- 0xee17edd8, 0xefbde94f, 0xf16d63a2, 0xf3145e45, 0xf4b975d7, 0xf667d34c, 0xf810e410,
- 0xf9b51d14, 0xfb626459, 0xfd0d7eb7, 0xfeb0de65 };
-
- private static final String expectedStringFor1_17eN38To38[] = { "-1.17549435E-38",
- "-1.1754944E-37", "-1.17549435E-36", "-1.17549435E-35", "-1.1754944E-34",
- "-1.17549435E-33", "-1.17549435E-32", "-1.1754944E-31", "-1.17549435E-30",
- "-1.17549435E-29", "-1.1754944E-28", "-1.1754943E-27", "-1.17549435E-26",
- "-1.1754943E-25", "-1.1754944E-24", "-1.1754943E-23", "-1.1754944E-22",
- "-1.1754943E-21", "-1.1754943E-20", "-1.1754943E-19", "-1.1754944E-18",
- "-1.1754944E-17", "-1.1754943E-16", "-1.1754943E-15", "-1.1754944E-14",
- "-1.1754943E-13", "-1.1754944E-12", "-1.1754943E-11", "-1.1754943E-10",
- "-1.1754944E-9", "-1.1754944E-8", "-1.1754943E-7", "-1.1754944E-6",
- "-1.1754943E-5", "-1.1754943E-4", "-0.0011754944", "-0.011754943", "-0.117549434",
- "-1.1754943", "-11.754944", "-117.54944", "-1175.4944", "-11754.943", "-117549.44",
- "-1175494.4", "-1.1754944E7", "-1.17549432E8", "-1.1754944E9", "-1.17549435E10",
- "-1.17549433E11", "-1.17549433E12", "-1.17549438E13", "-1.17549438E14",
- "-1.1754943E15", "-1.17549432E16", "-1.17549432E17", "-1.17549434E18",
- "-1.1754944E19", "-1.1754944E20", "-1.1754943E21", "-1.1754943E22",
- "-1.1754944E23", "-1.17549434E24", "-1.1754943E25", "-1.1754943E26",
- "-1.17549434E27", "-1.1754943E28", "-1.1754944E29", "-1.1754943E30",
- "-1.1754943E31", "-1.1754944E32", "-1.1754943E33", "-1.1754944E34",
- "-1.1754944E35", "-1.1754944E36", "-1.1754943E37", "-1.1754943E38" };
-
- private void doTestCompareRawBits(String originalFloatString, int expectedRawBits,
- String expectedString) {
- int rawBits;
- float result = Float.parseFloat(originalFloatString);
- rawBits = Float.floatToIntBits(result);
- assertEquals("Original float(" + originalFloatString + ") Converted float(" + result
- + ") Expecting:" + Integer.toHexString(expectedRawBits) + " Got: "
- + Integer.toHexString(rawBits), expectedRawBits, rawBits);
- }
-
- /**
- * @tests java.lang.Float#Float(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Float",
- args = {float.class}
- )
- public void test_ConstructorF() {
- // Test for method java.lang.Float(float)
-
- Float f = new Float(900.89f);
- assertTrue("Created incorrect float", f.floatValue() == 900.89f);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Float",
- args = {double.class}
- )
- public void test_ConstructorD() {
-
- Float f = new Float(Double.MAX_VALUE);
- assertTrue("Created incorrect float", f.floatValue() == Float.POSITIVE_INFINITY);
- }
-
- /**
- * @tests java.lang.Float#Float(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Float",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.lang.Float(java.lang.String)
-
- Float f = new Float("900.89");
- assertTrue("Created incorrect Float", f.floatValue() == 900.89f);
- try {
- new Float("900.89ff");
- fail("NumberFormatException is not thrown.");
- } catch(NumberFormatException nfe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.Float#byteValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "byteValue",
- args = {}
- )
- public void test_byteValue() {
- // Test for method byte java.lang.Float.byteValue()
- Float f = new Float(0.46874f);
- Float f2 = new Float(90.8f);
- assertTrue("Returned incorrect byte value", f.byteValue() == 0 && f2.byteValue() == 90);
- }
-
- /**
- * @tests java.lang.Float#compareTo(java.lang.Float)
- * @tests java.lang.Float#compare(float, float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compare",
- args = {float.class, float.class}
- )
- public void test_compare() {
- float[] values = new float[] { Float.NEGATIVE_INFINITY, -Float.MAX_VALUE, -2f,
- -Float.MIN_VALUE, -0f, 0f, Float.MIN_VALUE, 2f, Float.MAX_VALUE,
- Float.POSITIVE_INFINITY, Float.NaN };
- for (int i = 0; i < values.length; i++) {
- float f1 = values[i];
- assertTrue("compare() should be equal: " + f1, Float.compare(f1, f1) == 0);
- Float F1 = new Float(f1);
- assertTrue("compareTo() should be equal: " + f1, F1.compareTo(F1) == 0);
- for (int j = i + 1; j < values.length; j++) {
- float f2 = values[j];
- assertTrue("compare() " + f1 + " should be less " + f2,
- Float.compare(f1, f2) == -1);
- assertTrue("compare() " + f2 + " should be greater " + f1, Float
- .compare(f2, f1) == 1);
- Float F2 = new Float(f2);
- assertTrue("compareTo() " + f1 + " should be less " + f2,
- F1.compareTo(F2) == -1);
- assertTrue("compareTo() " + f2 + " should be greater " + f1,
- F2.compareTo(F1) == 1);
- }
- }
-
- try {
- new Float(0.0F).compareTo(null);
- fail("No NPE");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @tests java.lang.Float#doubleValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "doubleValue",
- args = {}
- )
- public void test_doubleValue() {
- // Test for method double java.lang.Float.doubleValue()
- assertTrue("Incorrect double value returned", Math.abs(new Float(999999.999f)
- .doubleValue() - 999999.999d) < 1);
- }
-
- /**
- * @tests java.lang.Float#floatToIntBits(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "floatToIntBits",
- args = {float.class}
- )
- public void test_floatToIntBitsF() {
- float f = 9876.2345f;
- int bits = Float.floatToIntBits(f);
- float r = Float.intBitsToFloat(bits);
- assertTrue("Incorrect intBits returned", f == r);
-
- assertEquals(0x7f800000, Float.floatToIntBits(Float.POSITIVE_INFINITY));
- assertEquals(0xff800000, Float.floatToIntBits(Float.NEGATIVE_INFINITY));
- assertEquals(0x7fc00000, Float.floatToIntBits(Float.NaN));
- }
-
- /**
- * @tests java.lang.Float#floatToRawIntBits(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "floatToRawIntBits",
- args = {float.class}
- )
- public void test_floatToRawIntBitsF() {
- int i = 0x7fc004d2;
- float f = Float.intBitsToFloat(i);
- assertTrue("Wrong raw bits", Float.floatToRawIntBits(f) == i);
-
- assertEquals(0x7f800000, Float.floatToRawIntBits(Float.POSITIVE_INFINITY));
- assertEquals(0xff800000, Float.floatToRawIntBits(Float.NEGATIVE_INFINITY));
- assertEquals(0x7fc00000, Float.floatToRawIntBits(Float.NaN));
- }
-
- /**
- * @tests java.lang.Float#floatValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "floatValue",
- args = {}
- )
- public void test_floatValue() {
- // Test for method float java.lang.Float.floatValue()
- Float f = new Float(87.657f);
- Float f2 = new Float(-0.876f);
- assertTrue("Returned incorrect floatValue", f.floatValue() == 87.657f
- && (f2.floatValue() == -0.876f));
-
- }
-
- /**
- * @tests java.lang.Float#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- // Test for method int java.lang.Float.hashCode()
- Float f = new Float(1908.8786f);
- assertTrue("Returned invalid hash code for 1908.8786f", f.hashCode() == Float
- .floatToIntBits(1908.8786f));
-
- f = new Float(-1.112f);
- assertTrue("Returned invalid hash code for -1.112", f.hashCode() == Float
- .floatToIntBits(-1.112f));
-
- f = new Float(0f);
- assertTrue("Returned invalid hash code for 0", f.hashCode() == Float.floatToIntBits(0f));
-
- assertTrue(new Float(Float.MAX_VALUE).hashCode() != new Float(Float.MIN_VALUE).hashCode());
- }
-
- /**
- * @tests java.lang.Float#intBitsToFloat(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "intBitsToFloat",
- args = {int.class}
- )
- public void test_intBitsToFloatI() {
- float f = 9876.2345f;
- int bits = Float.floatToIntBits(f);
- float r = Float.intBitsToFloat(bits);
- assertEquals("Incorrect intBits returned", f, r, 0F);
-
- assertEquals(Float.POSITIVE_INFINITY, Float.intBitsToFloat(0x7f800000));
- assertEquals(Float.NEGATIVE_INFINITY, Float.intBitsToFloat(0xff800000));
-
- assertEquals(Float.NaN, Float.intBitsToFloat(0x7f800001));
- assertEquals(Float.NaN, Float.intBitsToFloat(0x7fffffff));
- assertEquals(Float.NaN, Float.intBitsToFloat(0xff800001));
- assertEquals(Float.NaN, Float.intBitsToFloat(0xffffffff));
- }
-
- /**
- * @tests java.lang.Float#intValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "intValue",
- args = {}
- )
- public void test_intValue() {
- // Test for method int java.lang.Float.intValue()
- Float f = new Float(0.46874f);
- Float f2 = new Float(90.8f);
- assertTrue("Returned incorrect int value", f.intValue() == 0 && f2.intValue() == 90);
- assertEquals(Integer.MAX_VALUE, new Float(Float.MAX_VALUE).intValue());
- assertEquals(0, new Float(Float.MIN_VALUE).intValue());
- }
-
- /**
- * @tests java.lang.Float#isInfinite()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isInfinite",
- args = {}
- )
- public void test_isInfinite() {
- // Test for method boolean java.lang.Float.isInfinite()
- assertTrue("Infinity check failed",
- (new Float(Float.POSITIVE_INFINITY).isInfinite() && new Float(
- Float.NEGATIVE_INFINITY).isInfinite())
- && !(new Float(0.13131414f).isInfinite()));
- }
-
- /**
- * @tests java.lang.Float#isInfinite(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isInfinite",
- args = {float.class}
- )
- public void test_isInfiniteF() {
- // Test for method boolean java.lang.Float.isInfinite(float)
-
- assertTrue("Infinity check failed", Float.isInfinite(Float.POSITIVE_INFINITY)
- && (Float.isInfinite(Float.NEGATIVE_INFINITY)) && !(Float.isInfinite(1.0f)));
- }
-
- /**
- * @tests java.lang.Float#isNaN()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isNaN",
- args = {}
- )
- public void test_isNaN() {
- // Test for method boolean java.lang.Float.isNaN()
- assertTrue("NAN check failed", new Float(Float.NaN).isNaN()
- && !(new Float(1.0f).isNaN()));
- }
-
- /**
- * @tests java.lang.Float#isNaN(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isNaN",
- args = {float.class}
- )
- public void test_isNaNF() {
- // Test for method boolean java.lang.Float.isNaN(float)
- assertTrue("NaN check failed", Float.isNaN(Float.NaN) && !(Float.isNaN(12.09f))
- && !Float.isNaN(Float.MAX_VALUE) && !Float.isNaN(Float.MIN_VALUE));
- }
-
- /**
- * @tests java.lang.Float#longValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "longValue",
- args = {}
- )
- public void test_longValue() {
- // Test for method long java.lang.Float.longValue()
- Float f = new Float(0.46874f);
- Float f2 = new Float(90.8f);
- assertTrue("Returned incorrect long value", f.longValue() == 0 && f2.longValue() == 90);
- assertEquals(Long.MAX_VALUE, new Float(Float.MAX_VALUE).longValue());
- assertEquals(0, new Float(Float.MIN_VALUE).longValue());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NumberFormatException.",
- method = "parseFloat",
- args = {java.lang.String.class}
- )
- public void test_parseFloatLExceptions() {
- String [] incorrectStrings = {"", ";", "99999999EE999999", "99999l",
- "0x1.f.ffffep127"};
- for(int i = 0; i < incorrectStrings.length; i++) {
- try {
- Float.parseFloat(incorrectStrings[i]);
- fail("NumberFormatException is not thrown for string: "
- + incorrectStrings[i]);
- } catch(NumberFormatException nfe) {
- //expected
- }
- }
- }
-
- /**
- * @tests java.lang.Float#parseFloat(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies boundary cases.",
- method = "parseFloat",
- args = {java.lang.String.class}
- )
- public void test_parseFloatLjava_lang_String() {
- assertEquals("Incorrect float returned, expected zero.", 0.0, Float
- .parseFloat("7.0064923216240853546186479164495e-46"), 0.0);
- assertEquals("Incorrect float returned, expected minimum float.", Float.MIN_VALUE,
- Float.parseFloat("7.0064923216240853546186479164496e-46"), 0.0);
-
- doTestCompareRawBits(
- "0.000000000000000000000000000000000000011754942807573642917278829910357665133228589927589904276829631184250030649651730385585324256680905818939208984375",
- 0x800000, "1.17549435E-38");
- doTestCompareRawBits(
- "0.00000000000000000000000000000000000001175494280757364291727882991035766513322858992758990427682963118425003064965173038558532425668090581893920898437499999f",
- 0x7fffff, "1.1754942E-38");
-
- /* Test a set of regular floats with exponents from -38 to +38 */
- for (int i = 38; i > 3; i--) {
- String testString;
- testString = "3.4028234663852886e-" + i;
- doTestCompareRawBits(testString, rawBitsFor3_4eN38To38[38 - i],
- expectedStringFor3_4eN38To38[38 - i]);
- }
- doTestCompareRawBits("3.4028234663852886e-3", rawBitsFor3_4eN38To38[38 - 3],
- expectedStringFor3_4eN38To38[38 - 3]);
- doTestCompareRawBits("3.4028234663852886e-2", rawBitsFor3_4eN38To38[38 - 2],
- expectedStringFor3_4eN38To38[38 - 2]);
- doTestCompareRawBits("3.4028234663852886e-1", rawBitsFor3_4eN38To38[38 - 1],
- expectedStringFor3_4eN38To38[38 - 1]);
- doTestCompareRawBits("3.4028234663852886e-0", rawBitsFor3_4eN38To38[38 - 0],
- expectedStringFor3_4eN38To38[38 - 0]);
- doTestCompareRawBits("3.4028234663852886e+1", rawBitsFor3_4eN38To38[38 + 1],
- expectedStringFor3_4eN38To38[38 + 1]);
- doTestCompareRawBits("3.4028234663852886e+2", rawBitsFor3_4eN38To38[38 + 2],
- expectedStringFor3_4eN38To38[38 + 2]);
- doTestCompareRawBits("3.4028234663852886e+3", rawBitsFor3_4eN38To38[38 + 3],
- expectedStringFor3_4eN38To38[38 + 3]);
- doTestCompareRawBits("3.4028234663852886e+4", rawBitsFor3_4eN38To38[38 + 4],
- expectedStringFor3_4eN38To38[38 + 4]);
- doTestCompareRawBits("3.4028234663852886e+5", rawBitsFor3_4eN38To38[38 + 5],
- expectedStringFor3_4eN38To38[38 + 5]);
- doTestCompareRawBits("3.4028234663852886e+6", rawBitsFor3_4eN38To38[38 + 6],
- expectedStringFor3_4eN38To38[38 + 6]);
-
- for (int i = 7; i < 39; i++) {
- String testString;
- testString = "3.4028234663852886e+" + i;
- doTestCompareRawBits(testString, rawBitsFor3_4eN38To38[38 + i],
- expectedStringFor3_4eN38To38[38 + i]);
- }
-
- /* Test another set of regular floats with exponents from -38 to +38 */
- for (int i = 38; i > 3; i--) {
- String testString;
- testString = "-1.1754943508222875e-" + i;
- doTestCompareRawBits(testString, rawBitsFor1_17eN38To38[38 - i],
- expectedStringFor1_17eN38To38[38 - i]);
- }
- doTestCompareRawBits("-1.1754943508222875e-3", rawBitsFor1_17eN38To38[38 - 3],
- expectedStringFor1_17eN38To38[38 - 3]);
- doTestCompareRawBits("-1.1754943508222875e-2", rawBitsFor1_17eN38To38[38 - 2],
- expectedStringFor1_17eN38To38[38 - 2]);
- doTestCompareRawBits("-1.1754943508222875e-1", rawBitsFor1_17eN38To38[38 - 1],
- expectedStringFor1_17eN38To38[38 - 1]);
- doTestCompareRawBits("-1.1754943508222875e-0", rawBitsFor1_17eN38To38[38 - 0],
- expectedStringFor1_17eN38To38[38 - 0]);
- doTestCompareRawBits("-1.1754943508222875e+1", rawBitsFor1_17eN38To38[38 + 1],
- expectedStringFor1_17eN38To38[38 + 1]);
- doTestCompareRawBits("-1.1754943508222875e+2", rawBitsFor1_17eN38To38[38 + 2],
- expectedStringFor1_17eN38To38[38 + 2]);
- doTestCompareRawBits("-1.1754943508222875e+3", rawBitsFor1_17eN38To38[38 + 3],
- expectedStringFor1_17eN38To38[38 + 3]);
- doTestCompareRawBits("-1.1754943508222875e+4", rawBitsFor1_17eN38To38[38 + 4],
- expectedStringFor1_17eN38To38[38 + 4]);
- doTestCompareRawBits("-1.1754943508222875e+5", rawBitsFor1_17eN38To38[38 + 5],
- expectedStringFor1_17eN38To38[38 + 5]);
- doTestCompareRawBits("-1.1754943508222875e+6", rawBitsFor1_17eN38To38[38 + 6],
- expectedStringFor1_17eN38To38[38 + 6]);
-
- for (int i = 7; i < 39; i++) {
- String testString;
- testString = "-1.1754943508222875e+" + i;
- doTestCompareRawBits(testString, rawBitsFor1_17eN38To38[38 + i],
- expectedStringFor1_17eN38To38[38 + i]);
- }
-
- /* Test denormalized floats (floats with exponents <= -38 */
- doTestCompareRawBits("1.1012984643248170E-45", 1, "1.4E-45");
- doTestCompareRawBits("-1.1012984643248170E-45", 0x80000001, "-1.4E-45");
- doTestCompareRawBits("1.0E-45", 1, "1.4E-45");
- doTestCompareRawBits("-1.0E-45", 0x80000001, "-1.4E-45");
- doTestCompareRawBits("0.9E-45", 1, "1.4E-45");
- doTestCompareRawBits("-0.9E-45", 0x80000001, "-1.4E-45");
- doTestCompareRawBits("4.203895392974451e-45", 3, "4.2E-45");
- doTestCompareRawBits("-4.203895392974451e-45", 0x80000003, "-4.2E-45");
- doTestCompareRawBits("0.004E-45", 0, "0.0");
- doTestCompareRawBits("-0.004E-45", 0x80000000, "-0.0");
-
- /*
- * Test for large floats close to and greater than 3.4028235E38 and
- * -3.4028235E38
- */
- doTestCompareRawBits("1.2E+38", 0x7eb48e52, "1.2E38");
- doTestCompareRawBits("-1.2E+38", 0xfeb48e52, "-1.2E38");
- doTestCompareRawBits("3.2E+38", 0x7f70bdc2, "3.2E38");
- doTestCompareRawBits("-3.2E+38", 0xff70bdc2, "-3.2E38");
- doTestCompareRawBits("3.4E+38", 0x7f7fc99e, "3.4E38");
- doTestCompareRawBits("-3.4E+38", 0xff7fc99e, "-3.4E38");
- doTestCompareRawBits("3.4028234663852886E+38", 0x7f7fffff, "3.4028235E38");
- doTestCompareRawBits("-3.4028234663852886E+38", 0xff7fffff, "-3.4028235E38");
- doTestCompareRawBits("3.405E+38", 0x7f800000, "Infinity");
- doTestCompareRawBits("-3.405E+38", 0xff800000, "-Infinity");
- doTestCompareRawBits("3.41E+38", 0x7f800000, "Infinity");
- doTestCompareRawBits("-3.41E+38", 0xff800000, "-Infinity");
- doTestCompareRawBits("3.42E+38", 0x7f800000, "Infinity");
- doTestCompareRawBits("-3.42E+38", 0xff800000, "-Infinity");
- doTestCompareRawBits("1.0E+39", 0x7f800000, "Infinity");
- doTestCompareRawBits("-1.0E+39", 0xff800000, "-Infinity");
- }
-
- /**
- * @tests java.lang.Float#parseFloat(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies boundary values.",
- method = "parseFloat",
- args = {java.lang.String.class}
- )
- public void test_parseFloat_LString_Unusual() {
- float actual;
-
- actual = Float.parseFloat("0x00000000000000000000000000000000000000000.0000000000000000000000000000000000000p0000000000000000000000000000000000");
- assertEquals("Returned incorrect value", 0.0f, actual, 0.0F);
-
- actual = Float.parseFloat("+0Xfffff.fffffffffffffffffffffffffffffffp+99F");
- assertEquals("Returned incorrect value", 6.64614E35f, actual, 0.0F);
-
- actual = Float.parseFloat("-0X.123456789abcdefp+99f");
- assertEquals("Returned incorrect value", -4.5072022E28f, actual, 0.0F);
-
- actual = Float.parseFloat("-0X123456789abcdef.p+1f");
- assertEquals("Returned incorrect value", -1.63971062E17f, actual, 0.0F);
-
- actual = Float.parseFloat("-0X000000000000000000000000000001abcdef.0000000000000000000000000001abefp00000000000000000000000000000000000000000004f");
- assertEquals("Returned incorrect value", -4.48585472E8f, actual, 0.0F);
-
- actual = Float.parseFloat("0X0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001234p600f");
- assertEquals("Returned incorrect value", 5.907252E33f, actual, 0.0F);
-
- actual = Float.parseFloat("0x1.p9223372036854775807");
- assertEquals("Returned incorrect value", Float.POSITIVE_INFINITY, actual, 0.0F);
-
- actual = Float.parseFloat("0x1.p9223372036854775808");
- assertEquals("Returned incorrect value", Float.POSITIVE_INFINITY, actual, 0.0F);
-
- actual = Float.parseFloat("0x10.p9223372036854775808");
- assertEquals("Returned incorrect value", Float.POSITIVE_INFINITY, actual, 0.0F);
-
- actual = Float.parseFloat("0xabcd.ffffffffp+2000");
- assertEquals("Returned incorrect value", Float.POSITIVE_INFINITY, actual, 0.0F);
-
- actual = Float.parseFloat("0x1.p-9223372036854775808");
- assertEquals("Returned incorrect value", 0.0f, actual, 0.0F);
-
- actual = Float.parseFloat("0x1.p-9223372036854775809");
- assertEquals("Returned incorrect value", 0.0f, actual, 0.0F);
-
- actual = Float.parseFloat("0x.1p-9223372036854775809");
- assertEquals("Returned incorrect value", 0.0f, actual, 0.0F);
- }
-
- /**
- * @tests java.lang.Float#parseFloat(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies positive exponent.",
- method = "parseFloat",
- args = {java.lang.String.class}
- )
- public void test_parseFloat_LString_NormalPositiveExponent() {
- int[] expecteds = {
- 0x3991a2b4, 0x43cc0247, 0x47909009,
- 0x4ac0c009, 0x4e109005, 0x5140c005,
- 0x5458d805, 0x57848402, 0x5a909002,
- 0x5da8a802, 0x60c0c002, 0x63cccc02,
- 0x66e4e402, 0x69f0f002, 0x6d048401,
- 0x70109001, 0x73169601, 0x76810810,
- 0x79840840, 0x7c8a08a0, 0x7f800000,
- 0x7f800000, 0x7f800000, 0x7f800000,
- 0x7f800000,
- };
-
- for (int i = 0; i < expecteds.length; i++) {
- int part = i * 6;
- String inputString = "0x" + part + "." + part + "0123456789abcdefp" + part;
-
- float actual = Float.parseFloat(inputString);
- float expected = Float.intBitsToFloat(expecteds[i]);
-
- String expectedString = Integer.toHexString(Float.floatToIntBits(expected));
- String actualString = Integer.toHexString(Float.floatToIntBits(actual));
- String errorMsg = i + "th input string is:<" + inputString
- + ">.The expected result should be:<" + expectedString
- + ">, but was: <" + actualString + ">. ";
-
- assertEquals(errorMsg, expected, actual, 0.0F);
- }
- }
-
- /**
- * @tests java.lang.Float#parseFloat(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies negative exponent.",
- method = "parseFloat",
- args = {java.lang.String.class}
- )
- public void test_parseFloat_LString_NormalNegativeExponent() {
- int[] expecteds = {
- 0x3991a2b4,
- 0x3d6e0247,
- 0x3aa0a009,
- 0x37848405,
- 0x3420a005,
- 0x30d4d405,
- 0x2d848402,
- 0x2a129202,
- 0x26acac02,
- 0x2346c602,
- 0x1fe0e002,
- 0x1c6eee02,
- 0x19048401,
- 0x15919101,
- 0x12189801,
- 0xf028828,
- 0xb890890,
- 0x80c88c8,
- 0x4930930,
- 0x1198998,
- 0x28028,
- 0x51c,
- 0xb,
- 0x0,
- 0x0,
- };
-
- for (int i = 0; i < expecteds.length; i++) {
- int part = i * 7;
- String inputString = "0x" + part + "." + part + "0123456789abcdefp-" + part;
-
- float actual = Float.parseFloat(inputString);
- float expected = Float.intBitsToFloat(expecteds[i]);
-
- String expectedString = Integer.toHexString(Float.floatToIntBits(expected));
- String actualString = Integer.toHexString(Float.floatToIntBits(actual));
- String errorMsg = i + "th input string is:<" + inputString
- + ">.The expected result should be:<" + expectedString
- + ">, but was: <" + actualString + ">. ";
-
- assertEquals(errorMsg, expected, actual, 0.0F);
- }
- }
-
- /**
- * @tests java.lang.Float#parseFloat(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies max boundary value. Doesn't verify NumberFormatException.",
- method = "parseFloat",
- args = {java.lang.String.class}
- )
- public void test_parseFloat_LString_MaxNormalBoundary() {
- int[] expecteds ={
- 0x7f7fffff,
- 0x7f7fffff,
- 0x7f7fffff,
- 0x7f800000,
- 0x7f800000,
- 0x7f800000,
-
- 0xff7fffff,
- 0xff7fffff,
- 0xff7fffff,
- 0xff800000,
- 0xff800000,
- 0xff800000,
- };
-
- String[] inputs = {
- "0x1.fffffep127",
- "0x1.fffffe000000000000000000000000000000000000000000000001p127",
- "0x1.fffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp127",
- "0x1.ffffffp127",
- "0x1.ffffff000000000000000000000000000000000000000000000001p127",
- "0x1.ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp127",
-
- "-0x1.fffffep127",
- "-0x1.fffffe000000000000000000000000000000000000000000000001p127",
- "-0x1.fffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp127",
- "-0x1.ffffffp127",
- "-0x1.ffffff000000000000000000000000000000000000000000000001p127",
- "-0x1.ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp127",
- };
-
- for (int i = 0; i < inputs.length; i++) {
- float actual = Float.parseFloat(inputs[i]);
- float expected = Float.intBitsToFloat(expecteds[i]);
-
- String expectedString = Integer.toHexString(Float.floatToIntBits(expected));
- String actualString = Integer.toHexString(Float.floatToIntBits(actual));
- String errorMsg = i + "th input string is:<" + inputs[i]
- + ">.The expected result should be:<" + expectedString
- + ">, but was: <" + actualString + ">. ";
-
- assertEquals(errorMsg, expected, actual, 0.0F);
- }
- }
-
- /**
- * @tests java.lang.Float#parseFloat(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies min boundary value.",
- method = "parseFloat",
- args = {java.lang.String.class}
- )
- public void test_parseFloat_LString_MinNormalBoundary() {
- int expecteds[] = {
- 0x800000,
- 0x800000,
- 0x800000,
- 0x800000,
- 0x800001,
- 0x800001,
-
- 0x80800000,
- 0x80800000,
- 0x80800000,
- 0x80800000,
- 0x80800001,
- 0x80800001,
- };
-
- String inputs[] = {
- "0x1.0p-126",
- "0x1.00000000000000000000000000000000000000000000001p-126",
- "0x1.000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
- "0x1.000001p-126",
- "0x1.000001000000000000000000000000000000000000000001p-126",
- "0x1.000001fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
-
- "-0x1.0p-126",
- "-0x1.00000000000000000000000000000000000000000000001p-126",
- "-0x1.000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
- "-0x1.000001p-126",
- "-0x1.000001000000000000000000000000000000000000000001p-126",
- "-0x1.000001fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
- };
-
- for (int i = 0; i < inputs.length; i++) {
- float actual = Float.parseFloat(inputs[i]);
- float expected = Float.intBitsToFloat(expecteds[i]);
-
- String expectedString = Integer.toHexString(Float.floatToIntBits(expected));
- String actualString = Integer.toHexString(Float.floatToIntBits(actual));
- String errorMsg = i + "th input string is:<" + inputs[i]
- + ">.The expected result should be:<" + expectedString
- + ">, but was: <" + actualString + ">. ";
-
- assertEquals(errorMsg, expected, actual, 0.0F);
- }
- }
-
- /**
- * @tests java.lang.Float#parseFloat(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies max boundary value.",
- method = "parseFloat",
- args = {java.lang.String.class}
- )
- public void test_parseFloat_LString_MaxSubNormalBoundary() {
- int expecteds[] = {
- 0x7fffff,
- 0x7fffff,
- 0x7fffff,
- 0x800000,
- 0x800000,
- 0x800000,
-
- 0x807fffff,
- 0x807fffff,
- 0x807fffff,
- 0x80800000,
- 0x80800000,
- 0x80800000,
- };
-
- String inputs[] = {
- "0x0.fffffep-126",
- "0x0.fffffe000000000000000000000000000000000000000000000000000001p-126",
- "0x0.fffffefffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
- "0x0.ffffffp-126",
- "0x0.ffffff0000000000000000000000000000000000000000000000000000001p-126",
- "0x0.ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
-
- "-0x0.fffffep-126",
- "-0x0.fffffe000000000000000000000000000000000000000000000000000001p-126",
- "-0x0.fffffefffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
- "-0x0.ffffffp-126",
- "-0x0.ffffff0000000000000000000000000000000000000000000000000000001p-126",
- "-0x0.ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
- };
-
- for (int i = 0; i < inputs.length; i++) {
- float actual = Float.parseFloat(inputs[i]);
- float expected = Float.intBitsToFloat(expecteds[i]);
-
- String expectedString = Integer.toHexString(Float.floatToIntBits(expected));
- String actualString = Integer.toHexString(Float.floatToIntBits(actual));
- String errorMsg = i + "th input string is:<" + inputs[i]
- + ">.The expected result should be:<" + expectedString
- + ">, but was: <" + actualString + ">. ";
-
- assertEquals(errorMsg, expected, actual, 0.0F);
- }
- }
-
- /**
- * @tests java.lang.Float#parseFloat(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies min boundary value.",
- method = "parseFloat",
- args = {java.lang.String.class}
- )
- public void test_parseFloat_LString_MinSubNormalBoundary() {
- int expecteds[] = {
- 0x1,
- 0x1,
- 0x1,
- 0x2,
- 0x2,
- 0x2,
-
- 0x80000001,
- 0x80000001,
- 0x80000001,
- 0x80000002,
- 0x80000002,
- 0x80000002,
- };
-
- String inputs[] = {
- "0x0.000002p-126",
- "0x0.00000200000000000000000000000000000000000001p-126",
- "0x0.000002ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
- "0x0.000003p-126",
- "0x0.000003000000000000000000000000000000000000001p-126",
- "0x0.000003ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
-
- "-0x0.000002p-126",
- "-0x0.00000200000000000000000000000000000000000001p-126",
- "-0x0.000002ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
- "-0x0.000003p-126",
- "-0x0.000003000000000000000000000000000000000000001p-126",
- "-0x0.000003ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
- };
-
- for (int i = 0; i < inputs.length; i++) {
- float actual = Float.parseFloat(inputs[i]);
- float expected = Float.intBitsToFloat(expecteds[i]);
-
- String expectedString = Integer.toHexString(Float.floatToIntBits(expected));
- String actualString = Integer.toHexString(Float.floatToIntBits(actual));
- String errorMsg = i + "th input string is:<" + inputs[i]
- + ">.The expected result should be:<" + expectedString
- + ">, but was: <" + actualString + ">. ";
-
- assertEquals(errorMsg, expected, actual, 0.0F);
- }
- }
-
- /**
- * @tests java.lang.Float#parseFloat(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies zero boundary value.",
- method = "parseFloat",
- args = {java.lang.String.class}
- )
- public void test_parseFloat_LString_ZeroBoundary() {
- int expecteds[] = {
- 0x0,
- 0x0,
- 0x0,
- 0x0,
- 0x1,
- 0x1,
-
- 0x80000000,
- 0x80000000,
- 0x80000000,
- 0x80000000,
- 0x80000001,
- 0x80000001,
- };
-
- String inputs[] = {
- "0x0.000000000000000p-126",
- "0x0.000000000000000000000000000000000000000000000001p-126",
- "0x0.000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
- "0x0.000001p-126",
- "0x0.000001000000000000000000000000000000000000000001p-126",
- "0x0.000001fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
-
- "-0x0.000000000000000p-126",
- "-0x0.000000000000000000000000000000000000000000000001p-126",
- "-0x0.000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
- "-0x0.000001p-126",
- "-0x0.000001000000000000000000000000000000000000000001p-126",
- "-0x0.000001fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffp-126",
- };
-
- for (int i = 0; i < inputs.length; i++) {
- float actual = Float.parseFloat(inputs[i]);
- float expected = Float.intBitsToFloat(expecteds[i]);
-
- String expectedString = Integer.toHexString(Float.floatToIntBits(expected));
- String actualString = Integer.toHexString(Float.floatToIntBits(actual));
- String errorMsg = i + "th input string is:<" + inputs[i]
- + ">.The expected result should be:<" + expectedString
- + ">, but was: <" + actualString + ">. ";
-
- assertEquals(errorMsg, expected, actual, 0.0F);
- }
- }
-
- /**
- * @tests java.lang.Float#shortValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "shortValue",
- args = {}
- )
- public void test_shortValue() {
- // Test for method short java.lang.Float.shortValue()
- Float f = new Float(0.46874f);
- Float f2 = new Float(90.8f);
- assertTrue("Returned incorrect short value", f.shortValue() == 0
- && f2.shortValue() == 90);
- }
-
- /**
- * @tests java.lang.Float#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.lang.Float.toString()
-
- test_toString(12.90898f, "12.90898");
-
- test_toString(1.7014118346046924e+38F, "1.7014118E38");
- }
-
- /**
- * @tests java.lang.Float#toString(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {float.class}
- )
- public void test_toStringF() {
- // Test for method java.lang.String java.lang.Float.toString(float)
-
- float ff;
- String answer;
-
- ff = 12.90898f;
- answer = "12.90898";
- assertTrue("Incorrect String representation want " + answer + ", got "
- + Float.toString(ff), Float.toString(ff).equals(answer));
-
- ff = Float.MAX_VALUE;
- answer = "3.4028235E38";
- assertTrue("Incorrect String representation want " + answer + ", got "
- + Float.toString(ff), Float.toString(ff).equals(answer));
- }
-
- /**
- * @tests java.lang.Float#valueOf(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {java.lang.String.class}
- )
- public void test_valueOfLjava_lang_String() {
- // Test for method java.lang.Float
- // java.lang.Float.valueOf(java.lang.String)
-
- Float wanted = new Float(432.1235f);
- Float got = Float.valueOf("432.1235");
- assertTrue("Incorrect float returned--wanted: " + wanted + " but got: " + got, got
- .equals(wanted));
-
- wanted = new Float(0f);
- got = Float.valueOf("0");
- assertTrue("Incorrect float returned--wanted: " + wanted + " but got: " + got, got
- .equals(wanted));
-
- wanted = new Float(-1212.3232f);
- got = Float.valueOf("-1212.3232");
- assertTrue("Incorrect float returned--wanted: " + wanted + " but got: " + got, got
- .equals(wanted));
-
- try {
- Float.valueOf(null);
- fail("Expected Float.valueOf(null) to throw NPE.");
- } catch (NullPointerException ex) {
- // expected
- } catch (Exception ex) {
- fail("Expected Float.valueOf(null) to throw NPE not " + ex.getClass().getName());
- }
-
- try {
- Float.valueOf("");
- fail("Expected Float.valueOf(\"\") to throw NFE");
- } catch (NumberFormatException e) {
- // expected
- }
-
- Float posZero = Float.valueOf("+0.0");
- Float negZero = Float.valueOf("-0.0");
- assertFalse("Floattest0", posZero.equals(negZero));
- assertTrue("Floattest1", 0.0f == -0.0f);
-
- // Tests for float values by name.
- Float expectedNaN = new Float(Float.NaN);
-
- Float posNaN = Float.valueOf("NaN");
- assertTrue("Floattest2", posNaN.equals(expectedNaN));
-
- Float posNaNSigned = Float.valueOf("+NaN");
- assertTrue("Floattest3", posNaNSigned.equals(expectedNaN));
-
- Float negNaNSigned = Float.valueOf("-NaN");
- assertTrue("Floattest4", negNaNSigned.equals(expectedNaN));
-
- Float posInfinite = Float.valueOf("Infinity");
- assertTrue("Floattest5", posInfinite.equals(new Float(Float.POSITIVE_INFINITY)));
-
- Float posInfiniteSigned = Float.valueOf("+Infinity");
- assertTrue("Floattest6", posInfiniteSigned.equals(new Float(Float.POSITIVE_INFINITY)));
-
- Float negInfiniteSigned = Float.valueOf("-Infinity");
- assertTrue("Floattest7", negInfiniteSigned.equals(new Float(Float.NEGATIVE_INFINITY)));
- }
-
- private void test_toString(float ff, String answer) {
- // Test for method java.lang.String java.lang.Double.toString(double)
- assertTrue("Incorrect String representation want " + answer + ", got ("
- + Float.toString(ff) + ")", Float.toString(ff).equals(answer));
- Float f = new Float(ff);
- assertTrue("Incorrect String representation want " + answer + ", got ("
- + Float.toString(f.floatValue()) + ")", Float.toString(f.floatValue()).equals(
- answer));
- assertTrue("Incorrect String representation want " + answer + ", got (" + f.toString()
- + ")", f.toString().equals(answer));
- }
-
- /**
- * @tests java.lang.Float#compareTo(java.lang.Float)
- * @tests java.lang.Float#compare(float, float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.lang.Float.class}
- )
- public void test_compareToLjava_lang_Float() {
- // A selection of float values in ascending order.
- float[] values = new float[] { Float.NEGATIVE_INFINITY, -Float.MAX_VALUE, -2f,
- -Float.MIN_VALUE, -0f, 0f, Float.MIN_VALUE, 2f, Float.MAX_VALUE,
- Float.POSITIVE_INFINITY, Float.NaN };
-
- for (int i = 0; i < values.length; i++) {
- float f1 = values[i];
-
- // Test that each value compares equal to itself; and each object is
- // equal to another object
- // like itself
- assertTrue("Assert 0: compare() should be equal: " + f1, Float.compare(f1, f1) == 0);
- Float objFloat = new Float(f1);
- assertTrue("Assert 1: compareTo() should be equal: " + objFloat, objFloat
- .compareTo(objFloat) == 0);
-
- // Test that the Float-defined order is respected
- for (int j = i + 1; j < values.length; j++) {
- float f2 = values[j];
- assertTrue("Assert 2: compare() " + f1 + " should be less " + f2, Float
- .compare(f1, f2) == -1);
- assertTrue("Assert 3: compare() " + f2 + " should be greater " + f1, Float
- .compare(f2, f1) == 1);
-
- Float F2 = new Float(f2);
- assertTrue("Assert 4: compareTo() " + f1 + " should be less " + f2, objFloat
- .compareTo(F2) == -1);
- assertTrue("Assert 5: compareTo() " + f2 + " should be greater " + f1, F2
- .compareTo(objFloat) == 1);
- }
- }
- }
-
- /**
- * @tests java.lang.Float#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- Float f1 = new Float(8765.4321f);
- Float f2 = new Float(8765.4321f);
- Float f3 = new Float(-1.0f);
- assertTrue("Assert 0: Equality test failed", f1.equals(f2) && !(f1.equals(f3)));
-
- assertTrue("Assert 1: NaN should not be == Nan", Float.NaN != Float.NaN);
- assertTrue("Assert 2: NaN should not be == Nan", new Float(Float.NaN).equals(new Float(
- Float.NaN)));
- assertTrue("Assert 3: -0f should be == 0f", 0f == -0f);
- assertTrue("Assert 4: -0f should not be equals() 0f", !new Float(0f).equals(new Float(
- -0f)));
-
- f1 = new Float(1098.576f);
- f2 = new Float(1098.576f);
- f3 = new Float(1.0f);
- assertTrue("Equality test failed", f1.equals(f2) && !(f1.equals(f3)));
-
- assertTrue("NaN should not be == Nan", Float.NaN != Float.NaN);
- assertTrue("NaN should not be == Nan", new Float(Float.NaN)
- .equals(new Float(Float.NaN)));
- assertTrue("-0f should be == 0f", 0f == -0f);
- assertTrue("-0f should not be equals() 0f", !new Float(0f).equals(new Float(-0f)));
- }
-
- /**
- * @tests java.lang.Float#toHexString(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toHexString",
- args = {float.class}
- )
- public void test_toHexStringF() {
- // the follow values comes from the Float Javadoc/Spec
- assertEquals("0x0.0p0", Float.toHexString(0.0F));
- assertEquals("-0x0.0p0", Float.toHexString(-0.0F));
- assertEquals("0x1.0p0", Float.toHexString(1.0F));
- assertEquals("-0x1.0p0", Float.toHexString(-1.0F));
- assertEquals("0x1.0p1", Float.toHexString(2.0F));
- assertEquals("0x1.8p1", Float.toHexString(3.0F));
- assertEquals("0x1.0p-1", Float.toHexString(0.5F));
- assertEquals("0x1.0p-2", Float.toHexString(0.25F));
- assertEquals("0x1.fffffep127", Float.toHexString(Float.MAX_VALUE));
- assertEquals("0x0.000002p-126", Float.toHexString(Float.MIN_VALUE));
-
- // test edge cases
- assertEquals("NaN", Float.toHexString(Float.NaN));
- assertEquals("-Infinity", Float.toHexString(Float.NEGATIVE_INFINITY));
- assertEquals("Infinity", Float.toHexString(Float.POSITIVE_INFINITY));
-
- // test various numbers
- assertEquals("-0x1.da8p6", Float.toHexString(-118.625F));
- assertEquals("0x1.295788p23", Float.toHexString(9743299.65F));
- assertEquals("0x1.295788p23", Float.toHexString(9743299.65000F));
- assertEquals("0x1.295788p23", Float.toHexString(9743299.650001234F));
- assertEquals("0x1.700d1p33", Float.toHexString(12349743299.65000F));
-
- // test HARMONY-2132
- assertEquals("0x1.01p10", Float.toHexString(0x1.01p10f));
- }
-
- /**
- * @tests java.lang.Float#valueOf(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {float.class}
- )
- public void test_valueOfF() {
- assertEquals(new Float(Float.MIN_VALUE), Float.valueOf(Float.MIN_VALUE));
- assertEquals(new Float(Float.MAX_VALUE), Float.valueOf(Float.MAX_VALUE));
- assertEquals(new Float(0), Float.valueOf(0));
-
- int s = -128;
- while (s < 128) {
- assertEquals(new Float(s), Float.valueOf(s));
- assertEquals(new Float(s + 0.1F), Float.valueOf(s + 0.1F));
- assertEquals(Float.valueOf(s + 0.1F), Float.valueOf(s + 0.1F));
- s++;
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalAccessErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalAccessErrorTest.java
deleted file mode 100644
index caec351..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalAccessErrorTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(IllegalAccessError.class)
-public class IllegalAccessErrorTest extends TestCase {
-
- /**
- * @tests java.lang.IllegalAccessError#IllegalAccessError()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalAccessError",
- args = {}
- )
- public void test_Constructor() {
- IllegalAccessError e = new IllegalAccessError();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.IllegalAccessError#IllegalAccessError(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalAccessError",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- IllegalAccessError e = new IllegalAccessError("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalAccessExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalAccessExceptionTest.java
deleted file mode 100644
index a14ae66..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalAccessExceptionTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(IllegalAccessException.class)
-public class IllegalAccessExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.IllegalAccessException#IllegalAccessException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalAccessException",
- args = {}
- )
- public void test_Constructor() {
- IllegalAccessException e = new IllegalAccessException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.IllegalAccessException#IllegalAccessException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalAccessException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- IllegalAccessException e = new IllegalAccessException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalArgumentExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalArgumentExceptionTest.java
deleted file mode 100644
index 3acc8e4..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalArgumentExceptionTest.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-@TestTargetClass(IllegalArgumentException.class)
-public class IllegalArgumentExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.IllegalArgumentException#IllegalArgumentException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalArgumentException",
- args = {}
- )
- public void test_Constructor() {
- IllegalArgumentException e = new IllegalArgumentException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.IllegalArgumentException#IllegalArgumentException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalArgumentException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- IllegalArgumentException e = new IllegalArgumentException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.IllegalArgumentException#IllegalArgumentException(String,Throwable)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalArgumentException",
- args = {java.lang.String.class, java.lang.Throwable.class}
- )
- @SuppressWarnings("nls")
- public void test_ConstructorLjava_lang_StringLjava_lang_Throwable() {
- NullPointerException npe = new NullPointerException();
- IllegalArgumentException e = new IllegalArgumentException("fixture",
- npe);
- assertSame("fixture", e.getMessage());
- assertSame(npe, e.getCause());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalArgumentException",
- args = {java.lang.Throwable.class}
- )
- public void test_ConstructorLjava_lang_Throwable() {
- NullPointerException npe = new NullPointerException();
- IllegalArgumentException e = new IllegalArgumentException(npe);
- assertSame(npe, e.getCause());
- }
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
- SerializationTest.verifySelf(new IllegalArgumentException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
- SerializationTest.verifyGolden(this, new IllegalArgumentException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalMonitorStateExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalMonitorStateExceptionTest.java
deleted file mode 100644
index adc155f..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalMonitorStateExceptionTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(IllegalMonitorStateException.class)
-public class IllegalMonitorStateExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.IllegalMonitorStateException#IllegalMonitorStateException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalMonitorStateException",
- args = {}
- )
- public void test_Constructor() {
- IllegalMonitorStateException e = new IllegalMonitorStateException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.IllegalMonitorStateException#IllegalMonitorStateException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalMonitorStateException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- IllegalMonitorStateException e = new IllegalMonitorStateException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalStateExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalStateExceptionTest.java
deleted file mode 100644
index 03acac6..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalStateExceptionTest.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-@TestTargetClass(IllegalStateException.class)
-public class IllegalStateExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.IllegalStateException#IllegalStateException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalStateException",
- args = {}
- )
- public void test_Constructor() {
- IllegalStateException e = new IllegalStateException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.IllegalStateException#IllegalStateException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalStateException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- IllegalStateException e = new IllegalStateException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalStateException",
- args = {java.lang.String.class, java.lang.Throwable.class}
- )
- public void test_ConstructorLjava_lang_StringLThrowable() {
- String message = "Test message";
- NullPointerException npe = new NullPointerException();
- IllegalStateException e = new IllegalStateException(message, npe);
- assertEquals(message, e.getMessage());
- assertEquals(npe, e.getCause());
-
- e = new IllegalStateException(message, null);
- assertEquals(message, e.getMessage());
- assertNull(e.getCause());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalStateException",
- args = {java.lang.Throwable.class}
- )
- public void test_ConstructorLThrowable() {
- NullPointerException npe = new NullPointerException();
- IllegalStateException e = new IllegalStateException(npe);
- assertEquals(npe, e.getCause());
-
- e = new IllegalStateException((Throwable)null);
- assertNull(e.getCause());
- }
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization.",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new IllegalStateException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization.",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new IllegalStateException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalThreadStateExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalThreadStateExceptionTest.java
deleted file mode 100644
index 1b3a03d..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalThreadStateExceptionTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(IllegalThreadStateException.class)
-public class IllegalThreadStateExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.IllegalThreadStateException#IllegalThreadStateException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalThreadStateException",
- args = {}
- )
- public void test_Constructor() {
- IllegalThreadStateException e = new IllegalThreadStateException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.IllegalThreadStateException#IllegalThreadStateException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalThreadStateException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- IllegalThreadStateException e = new IllegalThreadStateException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IncompatibleClassChangeErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IncompatibleClassChangeErrorTest.java
deleted file mode 100644
index 7893b29..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IncompatibleClassChangeErrorTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(IncompatibleClassChangeError.class)
-public class IncompatibleClassChangeErrorTest extends TestCase {
-
- /**
- * @tests java.lang.IncompatibleClassChangeError#IncompatibleClassChangeError()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IncompatibleClassChangeError",
- args = {}
- )
- public void test_Constructor() {
- IncompatibleClassChangeError e = new IncompatibleClassChangeError();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.IncompatibleClassChangeError#IncompatibleClassChangeError(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IncompatibleClassChangeError",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- IncompatibleClassChangeError e = new IncompatibleClassChangeError("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IndexOutOfBoundsExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IndexOutOfBoundsExceptionTest.java
deleted file mode 100644
index d897e47..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IndexOutOfBoundsExceptionTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(IndexOutOfBoundsException.class)
-public class IndexOutOfBoundsExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.IndexOutOfBoundsException#IndexOutOfBoundsException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IndexOutOfBoundsException",
- args = {}
- )
- public void test_Constructor() {
- IndexOutOfBoundsException e = new IndexOutOfBoundsException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.IndexOutOfBoundsException#IndexOutOfBoundsException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IndexOutOfBoundsException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- IndexOutOfBoundsException e = new IndexOutOfBoundsException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InheritableThreadLocalTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InheritableThreadLocalTest.java
deleted file mode 100644
index 9697d30..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InheritableThreadLocalTest.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(InheritableThreadLocal.class)
-public class InheritableThreadLocalTest extends TestCase {
-
- /**
- * @tests java.lang.InheritableThreadLocal#InheritableThreadLocal()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InheritableThreadLocal",
- args = {}
- )
- public void test_Constructor() {
- InheritableThreadLocal<String> itl = new InheritableThreadLocal<String>();
- assertNull(itl.get());
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "initialValue",
- args = {}
- )
- public void test_initialValue() {
- InheritableThreadLocal<String> itl = new InheritableThreadLocal<String>() {
- @Override
- protected String initialValue() {
- return "initial";
- }
- };
- assertEquals("initial", itl.get());
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "childValue",
- args = {java.lang.Object.class}
- )
- public void test_childValue() {
- InheritableThreadLocal<String> itl = new InheritableThreadLocal<String>() {
- @Override
- protected String initialValue() {
- return "initial";
- }
- @Override
- protected String childValue(String parentValue) {
- return "childValue";
- }
- };
- assertEquals("initial", itl.get());
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InstantiationErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InstantiationErrorTest.java
deleted file mode 100644
index 5601755..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InstantiationErrorTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(InstantiationError.class)
-public class InstantiationErrorTest extends TestCase {
-
- /**
- * @tests java.lang.InstantiationError#InstantiationError()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InstantiationError",
- args = {}
- )
- public void test_Constructor() {
- InstantiationError e = new InstantiationError();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.InstantiationError#InstantiationError(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InstantiationError",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- InstantiationError e = new InstantiationError("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InstantiationExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InstantiationExceptionTest.java
deleted file mode 100644
index febeee2..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InstantiationExceptionTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(InstantiationException.class)
-public class InstantiationExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.InstantiationException#InstantiationException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InstantiationException",
- args = {}
- )
- public void test_Constructor() {
- InstantiationException e = new InstantiationException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.InstantiationException#InstantiationException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InstantiationException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- InstantiationException e = new InstantiationException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IntegerTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IntegerTest.java
deleted file mode 100644
index 9151068..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IntegerTest.java
+++ /dev/null
@@ -1,1472 +0,0 @@
-/* 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.Properties;
-
-@TestTargetClass(Integer.class)
-public class IntegerTest extends TestCase {
- private Properties orgProps;
-
- @Override
- protected void setUp() {
- orgProps = System.getProperties();
- }
-
- @Override
- protected void tearDown() {
- System.setProperties(orgProps);
- }
-
- /**
- * @tests java.lang.Integer#byteValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "byteValue",
- args = {}
- )
- public void test_byteValue() {
- // Test for method byte java.lang.Integer.byteValue()
- assertEquals("Returned incorrect byte value", -1, new Integer(65535)
- .byteValue());
- assertEquals("Returned incorrect byte value", 127, new Integer(127)
- .byteValue());
- }
-
- /**
- * @tests java.lang.Integer#compareTo(java.lang.Integer)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.lang.Integer.class}
- )
- public void test_compareToLjava_lang_Integer() {
- // Test for method int java.lang.Integer.compareTo(java.lang.Integer)
- assertTrue("-2 compared to 1 gave non-negative answer", new Integer(-2)
- .compareTo(new Integer(1)) < 0);
- assertEquals("-2 compared to -2 gave non-zero answer", 0, new Integer(-2)
- .compareTo(new Integer(-2)));
- assertTrue("3 compared to 2 gave non-positive answer", new Integer(3)
- .compareTo(new Integer(2)) > 0);
-
- try {
- new Integer(0).compareTo(null);
- fail("No NPE");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @tests java.lang.Integer#decode(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "decode",
- args = {java.lang.String.class}
- )
- public void test_decodeLjava_lang_String2() {
- // Test for method java.lang.Integer
- // java.lang.Integer.decode(java.lang.String)
- assertEquals("Failed for 132233",
- 132233, Integer.decode("132233").intValue());
- assertEquals("Failed for 07654321",
- 07654321, Integer.decode("07654321").intValue());
- assertTrue("Failed for #1234567",
- Integer.decode("#1234567").intValue() == 0x1234567);
- assertTrue("Failed for 0xdAd",
- Integer.decode("0xdAd").intValue() == 0xdad);
- assertEquals("Failed for -23", -23, Integer.decode("-23").intValue());
- assertEquals("Returned incorrect value for 0 decimal", 0, Integer
- .decode("0").intValue());
- assertEquals("Returned incorrect value for 0 hex", 0, Integer.decode("0x0")
- .intValue());
- assertTrue("Returned incorrect value for most negative value decimal",
- Integer.decode("-2147483648").intValue() == 0x80000000);
- assertTrue("Returned incorrect value for most negative value hex",
- Integer.decode("-0x80000000").intValue() == 0x80000000);
- assertTrue("Returned incorrect value for most positive value decimal",
- Integer.decode("2147483647").intValue() == 0x7fffffff);
- assertTrue("Returned incorrect value for most positive value hex",
- Integer.decode("0x7fffffff").intValue() == 0x7fffffff);
-
- boolean exception = false;
- try {
- Integer.decode("0a");
- } catch (NumberFormatException e) {
- // correct
- exception = true;
- }
- assertTrue("Failed to throw NumberFormatException for \"Oa\"",
- exception);
-
- exception = false;
- try {
- Integer.decode("2147483648");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
-
- exception = false;
- try {
- Integer.decode("-2147483649");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
-
- exception = false;
- try {
- Integer.decode("0x80000000");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for hex MAX_VALUE + 1", exception);
-
- exception = false;
- try {
- Integer.decode("-0x80000001");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for hex MIN_VALUE - 1", exception);
-
- exception = false;
- try {
- Integer.decode("9999999999");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for 9999999999", exception);
- }
-
- /**
- * @tests java.lang.Integer#doubleValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks integer's boundary values.",
- method = "doubleValue",
- args = {}
- )
- public void test_doubleValue2() {
- // Test for method double java.lang.Integer.doubleValue()
- assertEquals("Returned incorrect double value", 2147483647.0, new Integer(2147483647)
- .doubleValue(), 0.0D);
- assertEquals("Returned incorrect double value", -2147483647.0, new Integer(-2147483647)
- .doubleValue(), 0.0D);
- }
-
- /**
- * @tests java.lang.Integer#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object2() {
- // Test for method boolean java.lang.Integer.equals(java.lang.Object)
- Integer i1 = new Integer(1000);
- Integer i2 = new Integer(1000);
- Integer i3 = new Integer(-1000);
- assertTrue("Equality test failed", i1.equals(i2) && !(i1.equals(i3)));
- }
-
- /**
- * @tests java.lang.Integer#floatValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "floatValue",
- args = {}
- )
- public void test_floatValue2() {
- // Test for method float java.lang.Integer.floatValue()
- assertTrue("Returned incorrect float value", new Integer(65535)
- .floatValue() == 65535.0f);
- assertTrue("Returned incorrect float value", new Integer(-65535)
- .floatValue() == -65535.0f);
- }
-
- /**
- * @tests java.lang.Integer#getInteger(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInteger",
- args = {java.lang.String.class}
- )
- public void test_getIntegerLjava_lang_String() {
- // Test for method java.lang.Integer
- // java.lang.Integer.getInteger(java.lang.String)
- Properties tProps = new Properties();
- tProps.put("testInt", "99");
- System.setProperties(tProps);
- assertTrue("returned incorrect Integer", Integer.getInteger("testInt")
- .equals(new Integer(99)));
- assertNull("returned incorrect default Integer", Integer
- .getInteger("ff"));
- }
-
- /**
- * @tests java.lang.Integer#getInteger(java.lang.String, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInteger",
- args = {java.lang.String.class, int.class}
- )
- public void test_getIntegerLjava_lang_StringI() {
- // Test for method java.lang.Integer
- // java.lang.Integer.getInteger(java.lang.String, int)
- Properties tProps = new Properties();
- tProps.put("testInt", "99");
- tProps.put("testIncInt", "notInt");
- System.setProperties(tProps);
- assertTrue("returned incorrect Integer", Integer.getInteger("testInt",
- 4).equals(new Integer(99)));
- assertTrue("returned incorrect default Integer", Integer.getInteger(
- "ff", 4).equals(new Integer(4)));
- assertTrue("returned incorrect default Integer", Integer.getInteger(
- "testIncInt", 4).equals(new Integer(4)));
- }
-
- /**
- * @tests java.lang.Integer#getInteger(java.lang.String, java.lang.Integer)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInteger",
- args = {java.lang.String.class, java.lang.Integer.class}
- )
- public void test_getIntegerLjava_lang_StringLjava_lang_Integer() {
- // Test for method java.lang.Integer
- // java.lang.Integer.getInteger(java.lang.String, java.lang.Integer)
- Properties tProps = new Properties();
- tProps.put("testInt", "99");
- tProps.put("testIncInt", "notInt");
- System.setProperties(tProps);
- assertTrue("returned incorrect Integer", Integer.getInteger("testInt",
- new Integer(4)).equals(new Integer(99)));
- assertTrue("returned incorrect default Integer", Integer.getInteger(
- "ff", new Integer(4)).equals(new Integer(4)));
- assertTrue("returned incorrect default Integer", Integer.getInteger(
- "testIncInt", new Integer(4)).equals(new Integer(4)));
- }
-
- /**
- * @tests java.lang.Integer#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode2() {
- // Test for method int java.lang.Integer.hashCode()
-
- Integer i1 = new Integer(1000);
- Integer i2 = new Integer(-1000);
- assertTrue("Returned incorrect hashcode", i1.hashCode() == 1000
- && (i2.hashCode() == -1000));
- }
-
- /**
- * @tests java.lang.Integer#intValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Checks one value.",
- method = "intValue",
- args = {}
- )
- public void test_intValue2() {
- // Test for method int java.lang.Integer.intValue()
-
- Integer i = new Integer(8900);
- assertEquals("Returned incorrect int value", 8900, i.intValue());
- }
-
- /**
- * @tests java.lang.Integer#longValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Checks one value.",
- method = "longValue",
- args = {}
- )
- public void test_longValue2() {
- // Test for method long java.lang.Integer.longValue()
- Integer i = new Integer(8900);
- assertEquals("Returned incorrect long value", 8900L, i.longValue());
- }
-
- /**
- * @tests java.lang.Integer#parseInt(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "parseInt",
- args = {java.lang.String.class}
- )
- public void test_parseIntLjava_lang_String2() {
- // Test for method int java.lang.Integer.parseInt(java.lang.String)
-
- int i = Integer.parseInt("-8900");
- assertEquals("Returned incorrect int", -8900, i);
- assertEquals("Returned incorrect value for 0", 0, Integer.parseInt("0"));
- assertTrue("Returned incorrect value for most negative value", Integer
- .parseInt("-2147483648") == 0x80000000);
- assertTrue("Returned incorrect value for most positive value", Integer
- .parseInt("2147483647") == 0x7fffffff);
-
- boolean exception = false;
- try {
- Integer.parseInt("999999999999");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for value > int", exception);
-
- exception = false;
- try {
- Integer.parseInt("2147483648");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
-
- exception = false;
- try {
- Integer.parseInt("-2147483649");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
- }
-
- /**
- * @tests java.lang.Integer#parseInt(java.lang.String, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "parseInt",
- args = {java.lang.String.class, int.class}
- )
- public void test_parseIntLjava_lang_StringI2() {
- // Test for method int java.lang.Integer.parseInt(java.lang.String, int)
- assertEquals("Parsed dec val incorrectly",
- -8000, Integer.parseInt("-8000", 10));
- assertEquals("Parsed hex val incorrectly",
- 255, Integer.parseInt("FF", 16));
- assertEquals("Parsed oct val incorrectly",
- 16, Integer.parseInt("20", 8));
- assertEquals("Returned incorrect value for 0 hex", 0, Integer.parseInt("0",
- 16));
- assertTrue("Returned incorrect value for most negative value hex",
- Integer.parseInt("-80000000", 16) == 0x80000000);
- assertTrue("Returned incorrect value for most positive value hex",
- Integer.parseInt("7fffffff", 16) == 0x7fffffff);
- assertEquals("Returned incorrect value for 0 decimal", 0, Integer.parseInt(
- "0", 10));
- assertTrue("Returned incorrect value for most negative value decimal",
- Integer.parseInt("-2147483648", 10) == 0x80000000);
- assertTrue("Returned incorrect value for most positive value decimal",
- Integer.parseInt("2147483647", 10) == 0x7fffffff);
-
- boolean exception = false;
- try {
- Integer.parseInt("FFFF", 10);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue(
- "Failed to throw exception when passes hex string and dec parm",
- exception);
-
- exception = false;
- try {
- Integer.parseInt("2147483648", 10);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
-
- exception = false;
- try {
- Integer.parseInt("-2147483649", 10);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
-
- exception = false;
- try {
- Integer.parseInt("80000000", 16);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for hex MAX_VALUE + 1", exception);
-
- exception = false;
- try {
- Integer.parseInt("-80000001", 16);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for hex MIN_VALUE + 1", exception);
-
- exception = false;
- try {
- Integer.parseInt("9999999999", 10);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for 9999999999", exception);
- }
-
- /**
- * @tests java.lang.Integer#shortValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Checks one value.",
- method = "shortValue",
- args = {}
- )
- public void test_shortValue2() {
- // Test for method short java.lang.Integer.shortValue()
- Integer i = new Integer(2147450880);
- assertEquals("Returned incorrect long value", -32768, i.shortValue());
- }
-
- /**
- * @tests java.lang.Integer#toBinaryString(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toBinaryString",
- args = {int.class}
- )
- public void test_toBinaryStringI() {
- // Test for method java.lang.String
- // java.lang.Integer.toBinaryString(int)
- assertEquals("Incorrect string returned", "1111111111111111111111111111111", Integer.toBinaryString(
- Integer.MAX_VALUE));
- assertEquals("Incorrect string returned", "10000000000000000000000000000000", Integer.toBinaryString(
- Integer.MIN_VALUE));
- }
-
- /**
- * @tests java.lang.Integer#toHexString(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toHexString",
- args = {int.class}
- )
- public void test_toHexStringI() {
- // Test for method java.lang.String java.lang.Integer.toHexString(int)
-
- String[] hexvals = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
- "a", "b", "c", "d", "e", "f" };
-
- for (int i = 0; i < 16; i++) {
- assertTrue("Incorrect string returned " + hexvals[i], Integer
- .toHexString(i).equals(hexvals[i]));
- }
-
- assertTrue("Returned incorrect hex string: "
- + Integer.toHexString(Integer.MAX_VALUE), Integer.toHexString(
- Integer.MAX_VALUE).equals("7fffffff"));
- assertTrue("Returned incorrect hex string: "
- + Integer.toHexString(Integer.MIN_VALUE), Integer.toHexString(
- Integer.MIN_VALUE).equals("80000000"));
- }
-
- /**
- * @tests java.lang.Integer#toOctalString(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toOctalString",
- args = {int.class}
- )
- public void test_toOctalStringI() {
- // Test for method java.lang.String java.lang.Integer.toOctalString(int)
- // Spec states that the int arg is treated as unsigned
- assertEquals("Returned incorrect octal string", "17777777777", Integer.toOctalString(
- Integer.MAX_VALUE));
- assertEquals("Returned incorrect octal string", "20000000000", Integer.toOctalString(
- Integer.MIN_VALUE));
- }
-
- /**
- * @tests java.lang.Integer#toString()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Checks one value.",
- method = "toString",
- args = {}
- )
- public void test_toString2() {
- // Test for method java.lang.String java.lang.Integer.toString()
-
- Integer i = new Integer(-80001);
-
- assertEquals("Returned incorrect String", "-80001", i.toString());
- }
-
- /**
- * @tests java.lang.Integer#toString(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {int.class}
- )
- public void test_toStringI2() {
- // Test for method java.lang.String java.lang.Integer.toString(int)
-
- assertEquals("Returned incorrect String", "-80765", Integer.toString(-80765)
- );
- assertEquals("Returned incorrect octal string", "2147483647", Integer.toString(
- Integer.MAX_VALUE));
- assertEquals("Returned incorrect octal string", "-2147483647", Integer.toString(
- -Integer.MAX_VALUE));
- assertEquals("Returned incorrect octal string", "-2147483648", Integer.toString(
- Integer.MIN_VALUE));
- }
-
- /**
- * @tests java.lang.Integer#toString(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {int.class, int.class}
- )
- public void test_toStringII() {
- // Test for method java.lang.String java.lang.Integer.toString(int, int)
- assertEquals("Returned incorrect octal string", "17777777777", Integer.toString(
- 2147483647, 8));
- assertTrue("Returned incorrect hex string--wanted 7fffffff but got: "
- + Integer.toString(2147483647, 16), Integer.toString(
- 2147483647, 16).equals("7fffffff"));
- assertEquals("Incorrect string returned", "1111111111111111111111111111111", Integer.toString(2147483647, 2)
- );
- assertEquals("Incorrect string returned", "2147483647", Integer
- .toString(2147483647, 10));
-
- assertEquals("Returned incorrect octal string", "-17777777777", Integer.toString(
- -2147483647, 8));
- assertTrue("Returned incorrect hex string--wanted -7fffffff but got: "
- + Integer.toString(-2147483647, 16), Integer.toString(
- -2147483647, 16).equals("-7fffffff"));
- assertEquals("Incorrect string returned",
- "-1111111111111111111111111111111", Integer
- .toString(-2147483647, 2));
- assertEquals("Incorrect string returned", "-2147483647", Integer.toString(-2147483647,
- 10));
-
- assertEquals("Returned incorrect octal string", "-20000000000", Integer.toString(
- -2147483648, 8));
- assertTrue("Returned incorrect hex string--wanted -80000000 but got: "
- + Integer.toString(-2147483648, 16), Integer.toString(
- -2147483648, 16).equals("-80000000"));
- assertEquals("Incorrect string returned",
- "-10000000000000000000000000000000", Integer
- .toString(-2147483648, 2));
- assertEquals("Incorrect string returned", "-2147483648", Integer.toString(-2147483648,
- 10));
- }
-
- /**
- * @tests java.lang.Integer#valueOf(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies boundary values.",
- method = "valueOf",
- args = {java.lang.String.class}
- )
- public void test_valueOfLjava_lang_String2() {
- // Test for method java.lang.Integer
- // java.lang.Integer.valueOf(java.lang.String)
- assertEquals("Returned incorrect int", 8888888, Integer.valueOf("8888888")
- .intValue());
- assertTrue("Returned incorrect int", Integer.valueOf("2147483647")
- .intValue() == Integer.MAX_VALUE);
- assertTrue("Returned incorrect int", Integer.valueOf("-2147483648")
- .intValue() == Integer.MIN_VALUE);
-
- boolean exception = false;
- try {
- Integer.valueOf("2147483648");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception with MAX_VALUE + 1", exception);
-
- exception = false;
- try {
- Integer.valueOf("-2147483649");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception with MIN_VALUE - 1", exception);
- }
-
- /**
- * @tests java.lang.Integer#valueOf(java.lang.String, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks boundary values.",
- method = "valueOf",
- args = {java.lang.String.class, int.class}
- )
- public void test_valueOfLjava_lang_StringI2() {
- // Test for method java.lang.Integer
- // java.lang.Integer.valueOf(java.lang.String, int)
- assertEquals("Returned incorrect int for hex string", 255, Integer.valueOf(
- "FF", 16).intValue());
- assertEquals("Returned incorrect int for oct string", 16, Integer.valueOf(
- "20", 8).intValue());
- assertEquals("Returned incorrect int for bin string", 4, Integer.valueOf(
- "100", 2).intValue());
-
- assertEquals("Returned incorrect int for - hex string", -255, Integer.valueOf(
- "-FF", 16).intValue());
- assertEquals("Returned incorrect int for - oct string", -16, Integer.valueOf(
- "-20", 8).intValue());
- assertEquals("Returned incorrect int for - bin string", -4, Integer.valueOf(
- "-100", 2).intValue());
- assertTrue("Returned incorrect int", Integer.valueOf("2147483647", 10)
- .intValue() == Integer.MAX_VALUE);
- assertTrue("Returned incorrect int", Integer.valueOf("-2147483648", 10)
- .intValue() == Integer.MIN_VALUE);
- assertTrue("Returned incorrect int", Integer.valueOf("7fffffff", 16)
- .intValue() == Integer.MAX_VALUE);
- assertTrue("Returned incorrect int", Integer.valueOf("-80000000", 16)
- .intValue() == Integer.MIN_VALUE);
-
- boolean exception = false;
- try {
- Integer.valueOf("FF", 2);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue(
- "Failed to throw exception with hex string and base 2 radix",
- exception);
-
- exception = false;
- try {
- Integer.valueOf("2147483648", 10);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception with MAX_VALUE + 1", exception);
-
- exception = false;
- try {
- Integer.valueOf("-2147483649", 10);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception with MIN_VALUE - 1", exception);
-
- exception = false;
- try {
- Integer.valueOf("80000000", 16);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception with hex MAX_VALUE + 1",
- exception);
-
- exception = false;
- try {
- Integer.valueOf("-80000001", 16);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception with hex MIN_VALUE - 1",
- exception);
- }
-
- /**
- * @tests java.lang.Integer#valueOf(byte)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {int.class}
- )
- public void test_valueOfI() {
- assertEquals(new Integer(Integer.MIN_VALUE), Integer.valueOf(Integer.MIN_VALUE));
- assertEquals(new Integer(Integer.MAX_VALUE), Integer.valueOf(Integer.MAX_VALUE));
- assertEquals(new Integer(0), Integer.valueOf(0));
-
- short s = -128;
- while (s < 128) {
- assertEquals(new Integer(s), Integer.valueOf(s));
- assertSame(Integer.valueOf(s), Integer.valueOf(s));
- s++;
- }
- }
-
- /**
- * @tests java.lang.Integer#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- assertEquals(1, new Integer(1).hashCode());
- assertEquals(2, new Integer(2).hashCode());
- assertEquals(0, new Integer(0).hashCode());
- assertEquals(-1, new Integer(-1).hashCode());
- }
-
- /**
- * @tests java.lang.Integer#Integer(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Integer",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- assertEquals(new Integer(0), new Integer("0"));
- assertEquals(new Integer(1), new Integer("1"));
- assertEquals(new Integer(-1), new Integer("-1"));
-
- try {
- new Integer("0x1");
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {}
-
- try {
- new Integer("9.2");
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {}
-
- try {
- new Integer("");
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {}
-
- try {
- new Integer(null);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {}
- }
-
- /**
- * @tests java.lang.Integer#Integer
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Integer",
- args = {int.class}
- )
- public void test_ConstructorI() {
- assertEquals(1, new Integer(1).intValue());
- assertEquals(2, new Integer(2).intValue());
- assertEquals(0, new Integer(0).intValue());
- assertEquals(-1, new Integer(-1).intValue());
-
- Integer i = new Integer(-89000);
- assertEquals("Incorrect Integer created", -89000, i.intValue());
- }
-
- /**
- * @tests java.lang.Integer#byteValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "byteValue",
- args = {}
- )
- public void test_booleanValue() {
- assertEquals(1, new Integer(1).byteValue());
- assertEquals(2, new Integer(2).byteValue());
- assertEquals(0, new Integer(0).byteValue());
- assertEquals(-1, new Integer(-1).byteValue());
- }
-
- /**
- * @tests java.lang.Integer#equals(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- assertEquals(new Integer(0), Integer.valueOf(0));
- assertEquals(new Integer(1), Integer.valueOf(1));
- assertEquals(new Integer(-1), Integer.valueOf(-1));
-
- Integer fixture = new Integer(25);
- assertEquals(fixture, fixture);
- assertFalse(fixture.equals(null));
- assertFalse(fixture.equals("Not a Integer"));
- }
-
- /**
- * @tests java.lang.Integer#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- assertEquals("-1", new Integer(-1).toString());
- assertEquals("0", new Integer(0).toString());
- assertEquals("1", new Integer(1).toString());
- assertEquals("-1", new Integer(0xFFFFFFFF).toString());
- }
-
- /**
- * @tests java.lang.Integer#toString
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {int.class}
- )
- public void test_toStringI() {
- assertEquals("-1", Integer.toString(-1));
- assertEquals("0", Integer.toString(0));
- assertEquals("1", Integer.toString(1));
- assertEquals("-1", Integer.toString(0xFFFFFFFF));
- }
-
- /**
- * @tests java.lang.Integer#valueOf(String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't check boundary values.",
- method = "valueOf",
- args = {java.lang.String.class}
- )
- public void test_valueOfLjava_lang_String() {
- assertEquals(new Integer(0), Integer.valueOf("0"));
- assertEquals(new Integer(1), Integer.valueOf("1"));
- assertEquals(new Integer(-1), Integer.valueOf("-1"));
-
- try {
- Integer.valueOf("0x1");
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {}
-
- try {
- Integer.valueOf("9.2");
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {}
-
- try {
- Integer.valueOf("");
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {}
-
- try {
- Integer.valueOf(null);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {}
- }
-
- /**
- * @tests java.lang.Integer#valueOf(String,int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't check boundary values.",
- method = "valueOf",
- args = {java.lang.String.class, int.class}
- )
- public void test_valueOfLjava_lang_StringI() {
- assertEquals(new Integer(0), Integer.valueOf("0", 10));
- assertEquals(new Integer(1), Integer.valueOf("1", 10));
- assertEquals(new Integer(-1), Integer.valueOf("-1", 10));
-
- //must be consistent with Character.digit()
- assertEquals(Character.digit('1', 2), Integer.valueOf("1", 2).byteValue());
- assertEquals(Character.digit('F', 16), Integer.valueOf("F", 16).byteValue());
-
- try {
- Integer.valueOf("0x1", 10);
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {}
-
- try {
- Integer.valueOf("9.2", 10);
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {}
-
- try {
- Integer.valueOf("", 10);
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {}
-
- try {
- Integer.valueOf(null, 10);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {}
- }
-
- /**
- * @tests java.lang.Integer#parseInt(String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't check boundary values.",
- method = "parseInt",
- args = {java.lang.String.class}
- )
- public void test_parseIntLjava_lang_String() {
- assertEquals(0, Integer.parseInt("0"));
- assertEquals(1, Integer.parseInt("1"));
- assertEquals(-1, Integer.parseInt("-1"));
-
- try {
- Integer.parseInt("0x1");
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {}
-
- try {
- Integer.parseInt("9.2");
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {}
-
- try {
- Integer.parseInt("");
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {}
-
- try {
- Integer.parseInt(null);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {}
- }
-
- /**
- * @tests java.lang.Integer#parseInt(String,int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "parseInt",
- args = {java.lang.String.class, int.class}
- )
- public void test_parseIntLjava_lang_StringI() {
- assertEquals(0, Integer.parseInt("0", 10));
- assertEquals(1, Integer.parseInt("1", 10));
- assertEquals(-1, Integer.parseInt("-1", 10));
-
- //must be consistent with Character.digit()
- assertEquals(Character.digit('1', 2), Integer.parseInt("1", 2));
- assertEquals(Character.digit('F', 16), Integer.parseInt("F", 16));
-
- try {
- Integer.parseInt("0x1", 10);
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {}
-
- try {
- Integer.parseInt("9.2", 10);
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {}
-
- try {
- Integer.parseInt("", 10);
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {}
-
- try {
- Integer.parseInt(null, 10);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {}
- }
-
- /**
- * @tests java.lang.Integer#decode(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "decode",
- args = {java.lang.String.class}
- )
- public void test_decodeLjava_lang_String() {
- assertEquals(new Integer(0), Integer.decode("0"));
- assertEquals(new Integer(1), Integer.decode("1"));
- assertEquals(new Integer(-1), Integer.decode("-1"));
- assertEquals(new Integer(0xF), Integer.decode("0xF"));
- assertEquals(new Integer(0xF), Integer.decode("#F"));
- assertEquals(new Integer(0xF), Integer.decode("0XF"));
- assertEquals(new Integer(07), Integer.decode("07"));
-
- try {
- Integer.decode("9.2");
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {}
-
- try {
- Integer.decode("");
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {}
-
- try {
- Integer.decode(null);
- //undocumented NPE, but seems consistent across JREs
- fail("Expected NullPointerException with null string.");
- } catch (NullPointerException e) {}
- }
-
- /**
- * @tests java.lang.Integer#doubleValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't check boundaries.",
- method = "doubleValue",
- args = {}
- )
- public void test_doubleValue() {
- assertEquals(-1D, new Integer(-1).doubleValue(), 0D);
- assertEquals(0D, new Integer(0).doubleValue(), 0D);
- assertEquals(1D, new Integer(1).doubleValue(), 0D);
- }
-
- /**
- * @tests java.lang.Integer#floatValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "floatValue",
- args = {}
- )
- public void test_floatValue() {
- assertEquals(-1F, new Integer(-1).floatValue(), 0F);
- assertEquals(0F, new Integer(0).floatValue(), 0F);
- assertEquals(1F, new Integer(1).floatValue(), 0F);
- }
-
- /**
- * @tests java.lang.Integer#intValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "intValue",
- args = {}
- )
- public void test_intValue() {
- assertEquals(-1, new Integer(-1).intValue());
- assertEquals(0, new Integer(0).intValue());
- assertEquals(1, new Integer(1).intValue());
- assertEquals(Integer.MAX_VALUE, new Integer(Integer.MAX_VALUE).intValue());
- assertEquals(Integer.MIN_VALUE, new Integer(Integer.MIN_VALUE).intValue());
- }
-
- /**
- * @tests java.lang.Integer#longValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "longValue",
- args = {}
- )
- public void test_longValue() {
- assertEquals(-1L, new Integer(-1).longValue());
- assertEquals(0L, new Integer(0).longValue());
- assertEquals(1L, new Integer(1).longValue());
- assertEquals(Integer.MAX_VALUE, new Integer(Integer.MAX_VALUE).longValue());
- assertEquals(Integer.MIN_VALUE, new Integer(Integer.MIN_VALUE).longValue());
- }
-
- /**
- * @tests java.lang.Integer#shortValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "shortValue",
- args = {}
- )
- public void test_shortValue() {
- assertEquals(-1, new Integer(-1).shortValue());
- assertEquals(0, new Integer(0).shortValue());
- assertEquals(1, new Integer(1).shortValue());
- assertEquals(-1, new Integer(Integer.MAX_VALUE).shortValue());
- assertEquals(0, new Integer(Integer.MIN_VALUE).shortValue());
- }
- /**
- * @tests java.lang.Integer#highestOneBit(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "highestOneBit",
- args = {int.class}
- )
- public void test_highestOneBitI() {
- assertEquals(0x08, Integer.highestOneBit(0x0A));
- assertEquals(0x08, Integer.highestOneBit(0x0B));
- assertEquals(0x08, Integer.highestOneBit(0x0C));
- assertEquals(0x08, Integer.highestOneBit(0x0F));
- assertEquals(0x80, Integer.highestOneBit(0xFF));
-
- assertEquals(0x080000, Integer.highestOneBit(0x0F1234));
- assertEquals(0x800000, Integer.highestOneBit(0xFF9977));
-
- assertEquals(0x80000000, Integer.highestOneBit(0xFFFFFFFF));
-
- assertEquals(0, Integer.highestOneBit(0));
- assertEquals(1, Integer.highestOneBit(1));
- assertEquals(0x80000000, Integer.highestOneBit(-1));
- }
-
- /**
- * @tests java.lang.Integer#lowestOneBit(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lowestOneBit",
- args = {int.class}
- )
- public void test_lowestOneBitI() {
- assertEquals(0x10, Integer.lowestOneBit(0xF0));
-
- assertEquals(0x10, Integer.lowestOneBit(0x90));
- assertEquals(0x10, Integer.lowestOneBit(0xD0));
-
- assertEquals(0x10, Integer.lowestOneBit(0x123490));
- assertEquals(0x10, Integer.lowestOneBit(0x1234D0));
-
- assertEquals(0x100000, Integer.lowestOneBit(0x900000));
- assertEquals(0x100000, Integer.lowestOneBit(0xD00000));
-
- assertEquals(0x40, Integer.lowestOneBit(0x40));
- assertEquals(0x40, Integer.lowestOneBit(0xC0));
-
- assertEquals(0x4000, Integer.lowestOneBit(0x4000));
- assertEquals(0x4000, Integer.lowestOneBit(0xC000));
-
- assertEquals(0x4000, Integer.lowestOneBit(0x99994000));
- assertEquals(0x4000, Integer.lowestOneBit(0x9999C000));
-
- assertEquals(0, Integer.lowestOneBit(0));
- assertEquals(1, Integer.lowestOneBit(1));
- assertEquals(1, Integer.lowestOneBit(-1));
- }
- /**
- * @tests java.lang.Integer#numberOfLeadingZeros(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "numberOfLeadingZeros",
- args = {int.class}
- )
- public void test_numberOfLeadingZerosI() {
- assertEquals(32, Integer.numberOfLeadingZeros(0x0));
- assertEquals(31, Integer.numberOfLeadingZeros(0x1));
- assertEquals(30, Integer.numberOfLeadingZeros(0x2));
- assertEquals(30, Integer.numberOfLeadingZeros(0x3));
- assertEquals(29, Integer.numberOfLeadingZeros(0x4));
- assertEquals(29, Integer.numberOfLeadingZeros(0x5));
- assertEquals(29, Integer.numberOfLeadingZeros(0x6));
- assertEquals(29, Integer.numberOfLeadingZeros(0x7));
- assertEquals(28, Integer.numberOfLeadingZeros(0x8));
- assertEquals(28, Integer.numberOfLeadingZeros(0x9));
- assertEquals(28, Integer.numberOfLeadingZeros(0xA));
- assertEquals(28, Integer.numberOfLeadingZeros(0xB));
- assertEquals(28, Integer.numberOfLeadingZeros(0xC));
- assertEquals(28, Integer.numberOfLeadingZeros(0xD));
- assertEquals(28, Integer.numberOfLeadingZeros(0xE));
- assertEquals(28, Integer.numberOfLeadingZeros(0xF));
- assertEquals(27, Integer.numberOfLeadingZeros(0x10));
- assertEquals(24, Integer.numberOfLeadingZeros(0x80));
- assertEquals(24, Integer.numberOfLeadingZeros(0xF0));
- assertEquals(23, Integer.numberOfLeadingZeros(0x100));
- assertEquals(20, Integer.numberOfLeadingZeros(0x800));
- assertEquals(20, Integer.numberOfLeadingZeros(0xF00));
- assertEquals(19, Integer.numberOfLeadingZeros(0x1000));
- assertEquals(16, Integer.numberOfLeadingZeros(0x8000));
- assertEquals(16, Integer.numberOfLeadingZeros(0xF000));
- assertEquals(15, Integer.numberOfLeadingZeros(0x10000));
- assertEquals(12, Integer.numberOfLeadingZeros(0x80000));
- assertEquals(12, Integer.numberOfLeadingZeros(0xF0000));
- assertEquals(11, Integer.numberOfLeadingZeros(0x100000));
- assertEquals(8, Integer.numberOfLeadingZeros(0x800000));
- assertEquals(8, Integer.numberOfLeadingZeros(0xF00000));
- assertEquals(7, Integer.numberOfLeadingZeros(0x1000000));
- assertEquals(4, Integer.numberOfLeadingZeros(0x8000000));
- assertEquals(4, Integer.numberOfLeadingZeros(0xF000000));
- assertEquals(3, Integer.numberOfLeadingZeros(0x10000000));
- assertEquals(0, Integer.numberOfLeadingZeros(0x80000000));
- assertEquals(0, Integer.numberOfLeadingZeros(0xF0000000));
-
- assertEquals(1, Integer.numberOfLeadingZeros(Integer.MAX_VALUE));
- assertEquals(0, Integer.numberOfLeadingZeros(Integer.MIN_VALUE));
- }
-
- /**
- * @tests
- * java.lang.Integer#numberOfTrailingZeros(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "numberOfTrailingZeros",
- args = {int.class}
- )
- public void test_numberOfTrailingZerosI() {
- assertEquals(32, Integer.numberOfTrailingZeros(0x0));
- assertEquals(31, Integer.numberOfTrailingZeros(Integer.MIN_VALUE));
- assertEquals(0, Integer.numberOfTrailingZeros(Integer.MAX_VALUE));
-
- assertEquals(0, Integer.numberOfTrailingZeros(0x1));
- assertEquals(3, Integer.numberOfTrailingZeros(0x8));
- assertEquals(0, Integer.numberOfTrailingZeros(0xF));
-
- assertEquals(4, Integer.numberOfTrailingZeros(0x10));
- assertEquals(7, Integer.numberOfTrailingZeros(0x80));
- assertEquals(4, Integer.numberOfTrailingZeros(0xF0));
-
- assertEquals(8, Integer.numberOfTrailingZeros(0x100));
- assertEquals(11, Integer.numberOfTrailingZeros(0x800));
- assertEquals(8, Integer.numberOfTrailingZeros(0xF00));
-
- assertEquals(12, Integer.numberOfTrailingZeros(0x1000));
- assertEquals(15, Integer.numberOfTrailingZeros(0x8000));
- assertEquals(12, Integer.numberOfTrailingZeros(0xF000));
-
- assertEquals(16, Integer.numberOfTrailingZeros(0x10000));
- assertEquals(19, Integer.numberOfTrailingZeros(0x80000));
- assertEquals(16, Integer.numberOfTrailingZeros(0xF0000));
-
- assertEquals(20, Integer.numberOfTrailingZeros(0x100000));
- assertEquals(23, Integer.numberOfTrailingZeros(0x800000));
- assertEquals(20, Integer.numberOfTrailingZeros(0xF00000));
-
- assertEquals(24, Integer.numberOfTrailingZeros(0x1000000));
- assertEquals(27, Integer.numberOfTrailingZeros(0x8000000));
- assertEquals(24, Integer.numberOfTrailingZeros(0xF000000));
-
- assertEquals(28, Integer.numberOfTrailingZeros(0x10000000));
- assertEquals(31, Integer.numberOfTrailingZeros(0x80000000));
- assertEquals(28, Integer.numberOfTrailingZeros(0xF0000000));
- }
-
- /**
- * @tests java.lang.Integer#bitCount(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "bitCount",
- args = {int.class}
- )
- public void test_bitCountI() {
- assertEquals(0, Integer.bitCount(0x0));
- assertEquals(1, Integer.bitCount(0x1));
- assertEquals(1, Integer.bitCount(0x2));
- assertEquals(2, Integer.bitCount(0x3));
- assertEquals(1, Integer.bitCount(0x4));
- assertEquals(2, Integer.bitCount(0x5));
- assertEquals(2, Integer.bitCount(0x6));
- assertEquals(3, Integer.bitCount(0x7));
- assertEquals(1, Integer.bitCount(0x8));
- assertEquals(2, Integer.bitCount(0x9));
- assertEquals(2, Integer.bitCount(0xA));
- assertEquals(3, Integer.bitCount(0xB));
- assertEquals(2, Integer.bitCount(0xC));
- assertEquals(3, Integer.bitCount(0xD));
- assertEquals(3, Integer.bitCount(0xE));
- assertEquals(4, Integer.bitCount(0xF));
-
- assertEquals(8, Integer.bitCount(0xFF));
- assertEquals(12, Integer.bitCount(0xFFF));
- assertEquals(16, Integer.bitCount(0xFFFF));
- assertEquals(20, Integer.bitCount(0xFFFFF));
- assertEquals(24, Integer.bitCount(0xFFFFFF));
- assertEquals(28, Integer.bitCount(0xFFFFFFF));
- assertEquals(32, Integer.bitCount(0xFFFFFFFF));
- }
-
- /**
- * @tests java.lang.Integer#rotateLeft(int,int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "rotateLeft",
- args = {int.class, int.class}
- )
- public void test_rotateLeftII() {
- assertEquals(0xF, Integer.rotateLeft(0xF, 0));
- assertEquals(0xF0, Integer.rotateLeft(0xF, 4));
- assertEquals(0xF00, Integer.rotateLeft(0xF, 8));
- assertEquals(0xF000, Integer.rotateLeft(0xF, 12));
- assertEquals(0xF0000, Integer.rotateLeft(0xF, 16));
- assertEquals(0xF00000, Integer.rotateLeft(0xF, 20));
- assertEquals(0xF000000, Integer.rotateLeft(0xF, 24));
- assertEquals(0xF0000000, Integer.rotateLeft(0xF, 28));
- assertEquals(0xF0000000, Integer.rotateLeft(0xF0000000, 32));
- }
-
- /**
- * @tests java.lang.Integer#rotateRight(int,int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "rotateRight",
- args = {int.class, int.class}
- )
- public void test_rotateRightII() {
- assertEquals(0xF, Integer.rotateRight(0xF0, 4));
- assertEquals(0xF, Integer.rotateRight(0xF00, 8));
- assertEquals(0xF, Integer.rotateRight(0xF000, 12));
- assertEquals(0xF, Integer.rotateRight(0xF0000, 16));
- assertEquals(0xF, Integer.rotateRight(0xF00000, 20));
- assertEquals(0xF, Integer.rotateRight(0xF000000, 24));
- assertEquals(0xF, Integer.rotateRight(0xF0000000, 28));
- assertEquals(0xF0000000, Integer.rotateRight(0xF0000000, 32));
- assertEquals(0xF0000000, Integer.rotateRight(0xF0000000, 0));
-
- }
-
- /**
- * @tests java.lang.Integer#reverseBytes(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reverseBytes",
- args = {int.class}
- )
- public void test_reverseBytesI() {
- assertEquals(0xAABBCCDD, Integer.reverseBytes(0xDDCCBBAA));
- assertEquals(0x11223344, Integer.reverseBytes(0x44332211));
- assertEquals(0x00112233, Integer.reverseBytes(0x33221100));
- assertEquals(0x20000002, Integer.reverseBytes(0x02000020));
- }
-
- /**
- * @tests java.lang.Integer#reverse(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reverse",
- args = {int.class}
- )
- public void test_reverseI() {
- assertEquals(-1, Integer.reverse(-1));
- assertEquals(0x80000000,Integer.reverse(1));
- }
-
- /**
- * @tests java.lang.Integer#signum(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "signum",
- args = {int.class}
- )
- public void test_signumI() {
- for (int i = -128; i<0; i++) {
- assertEquals(-1, Integer.signum(i));
- }
- assertEquals(0, Integer.signum(0));
- for (int i = 1; i<=127; i++) {
- assertEquals(1, Integer.signum(i));
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InternalErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InternalErrorTest.java
deleted file mode 100644
index 4b93777..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InternalErrorTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(InternalError.class)
-public class InternalErrorTest extends TestCase {
-
- /**
- * @tests java.lang.InternalError#InternalError()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InternalError",
- args = {}
- )
- public void test_Constructor() {
- InternalError e = new InternalError();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.InternalError#InternalError(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InternalError",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- InternalError e = new InternalError("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InterruptedExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InterruptedExceptionTest.java
deleted file mode 100644
index 4faa301..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InterruptedExceptionTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(InterruptedException.class)
-public class InterruptedExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.InterruptedException#InterruptedException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InterruptedException",
- args = {}
- )
- public void test_Constructor() {
- InterruptedException e = new InterruptedException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.InterruptedException#InterruptedException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InterruptedException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- InterruptedException e = new InterruptedException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/LinkageErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/LinkageErrorTest.java
deleted file mode 100644
index c856705..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/LinkageErrorTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(LinkageError.class)
-public class LinkageErrorTest extends TestCase {
-
- /**
- * @tests java.lang.LinkageError#LinkageError()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "LinkageError",
- args = {}
- )
- public void test_Constructor() {
- LinkageError e = new LinkageError();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.LinkageError#LinkageError(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "LinkageError",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- LinkageError e = new LinkageError("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/LongTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/LongTest.java
deleted file mode 100644
index 9d0ee75..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/LongTest.java
+++ /dev/null
@@ -1,1332 +0,0 @@
-/* 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.Properties;
-
-@TestTargetClass(Long.class)
-public class LongTest extends TestCase {
- private Properties orgProps;
-
- @Override
- protected void setUp() {
- orgProps = System.getProperties();
- }
-
- @Override
- protected void tearDown() {
- System.setProperties(orgProps);
- }
-
- /**
- * @tests java.lang.Long#byteValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks bounary values.",
- method = "byteValue",
- args = {}
- )
- public void test_byteValue() {
- // Test for method byte java.lang.Long.byteValue()
- Long l = new Long(127);
- assertEquals("Returned incorrect byte value", 127, l.byteValue());
- assertEquals("Returned incorrect byte value", -1, new Long(Long.MAX_VALUE)
- .byteValue());
- }
-
- /**
- * @tests java.lang.Long#compareTo(java.lang.Long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.lang.Long.class}
- )
- public void test_compareToLjava_lang_Long() {
- // Test for method int java.lang.Long.compareTo(java.lang.Long)
- assertTrue("-2 compared to 1 gave non-negative answer", new Long(-2L)
- .compareTo(new Long(1L)) < 0);
- assertEquals("-2 compared to -2 gave non-zero answer", 0, new Long(-2L)
- .compareTo(new Long(-2L)));
- assertTrue("3 compared to 2 gave non-positive answer", new Long(3L)
- .compareTo(new Long(2L)) > 0);
-
- try {
- new Long(0).compareTo(null);
- fail("No NPE");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @tests java.lang.Long#decode(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "decode",
- args = {java.lang.String.class}
- )
- public void test_decodeLjava_lang_String2() {
- // Test for method java.lang.Long
- // java.lang.Long.decode(java.lang.String)
- assertEquals("Returned incorrect value for hex string", 255L, Long.decode(
- "0xFF").longValue());
- assertEquals("Returned incorrect value for dec string", -89000L, Long.decode(
- "-89000").longValue());
- assertEquals("Returned incorrect value for 0 decimal", 0, Long.decode("0")
- .longValue());
- assertEquals("Returned incorrect value for 0 hex", 0, Long.decode("0x0")
- .longValue());
- assertTrue(
- "Returned incorrect value for most negative value decimal",
- Long.decode("-9223372036854775808").longValue() == 0x8000000000000000L);
- assertTrue(
- "Returned incorrect value for most negative value hex",
- Long.decode("-0x8000000000000000").longValue() == 0x8000000000000000L);
- assertTrue(
- "Returned incorrect value for most positive value decimal",
- Long.decode("9223372036854775807").longValue() == 0x7fffffffffffffffL);
- assertTrue(
- "Returned incorrect value for most positive value hex",
- Long.decode("0x7fffffffffffffff").longValue() == 0x7fffffffffffffffL);
- assertTrue("Failed for 07654321765432", Long.decode("07654321765432")
- .longValue() == 07654321765432l);
-
- boolean exception = false;
- try {
- Long
- .decode("999999999999999999999999999999999999999999999999999999");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for value > ilong", exception);
-
- exception = false;
- try {
- Long.decode("9223372036854775808");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
-
- exception = false;
- try {
- Long.decode("-9223372036854775809");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
-
- exception = false;
- try {
- Long.decode("0x8000000000000000");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for hex MAX_VALUE + 1", exception);
-
- exception = false;
- try {
- Long.decode("-0x8000000000000001");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for hex MIN_VALUE - 1", exception);
-
- exception = false;
- try {
- Long.decode("42325917317067571199");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for 42325917317067571199",
- exception);
- }
-
- /**
- * @tests java.lang.Long#getLong(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLong",
- args = {java.lang.String.class}
- )
- public void test_getLongLjava_lang_String() {
- // Test for method java.lang.Long
- // java.lang.Long.getLong(java.lang.String)
- Properties tProps = new Properties();
- tProps.put("testLong", "99");
- tProps.put("testIncLong", "string");
- System.setProperties(tProps);
- assertTrue("returned incorrect Long", Long.getLong("testLong").equals(
- new Long(99)));
- assertNull("returned incorrect default Long",
- Long.getLong("ff"));
- assertNull("returned incorrect default Long",
- Long.getLong("testIncLong"));
- }
-
- /**
- * @tests java.lang.Long#getLong(java.lang.String, long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLong",
- args = {java.lang.String.class, long.class}
- )
- public void test_getLongLjava_lang_StringJ() {
- // Test for method java.lang.Long
- // java.lang.Long.getLong(java.lang.String, long)
- Properties tProps = new Properties();
- tProps.put("testLong", "99");
- tProps.put("testIncLong", "string");
- System.setProperties(tProps);
- assertTrue("returned incorrect Long", Long.getLong("testLong", 4L)
- .equals(new Long(99)));
- assertTrue("returned incorrect default Long", Long.getLong("ff", 4L)
- .equals(new Long(4)));
- assertTrue("returned incorrect default Long", Long.getLong("testIncLong", 4L)
- .equals(new Long(4)));
- }
-
- /**
- * @tests java.lang.Long#getLong(java.lang.String, java.lang.Long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLong",
- args = {java.lang.String.class, java.lang.Long.class}
- )
- public void test_getLongLjava_lang_StringLjava_lang_Long() {
- // Test for method java.lang.Long
- // java.lang.Long.getLong(java.lang.String, java.lang.Long)
- Properties tProps = new Properties();
- tProps.put("testLong", "99");
- tProps.put("testIncLong", "string");
- System.setProperties(tProps);
- assertTrue("returned incorrect Long", Long.getLong("testLong",
- new Long(4)).equals(new Long(99)));
- assertTrue("returned incorrect default Long", Long.getLong("ff",
- new Long(4)).equals(new Long(4)));
- assertTrue("returned incorrect default Long", Long.getLong("testIncLong",
- new Long(4)).equals(new Long(4)));
- }
-
- /**
- * @tests java.lang.Long#parseLong(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks boundary values and exceptions.",
- method = "parseLong",
- args = {java.lang.String.class}
- )
- public void test_parseLongLjava_lang_String2() {
- // Test for method long java.lang.Long.parseLong(java.lang.String)
-
- long l = Long.parseLong("89000000005");
- assertEquals("Parsed to incorrect long value", 89000000005L, l);
- assertEquals("Returned incorrect value for 0", 0, Long.parseLong("0"));
- assertTrue("Returned incorrect value for most negative value", Long
- .parseLong("-9223372036854775808") == 0x8000000000000000L);
- assertTrue("Returned incorrect value for most positive value", Long
- .parseLong("9223372036854775807") == 0x7fffffffffffffffL);
-
- boolean exception = false;
- try {
- Long.parseLong("9223372036854775808");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
-
- exception = false;
- try {
- Long.parseLong("-9223372036854775809");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
- }
-
- /**
- * @tests java.lang.Long#parseLong(java.lang.String, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "parseLong",
- args = {java.lang.String.class, int.class}
- )
- public void test_parseLongLjava_lang_StringI() {
- // Test for method long java.lang.Long.parseLong(java.lang.String, int)
- assertEquals("Returned incorrect value",
- 100000000L, Long.parseLong("100000000", 10));
- assertEquals("Returned incorrect value from hex string", 68719476735L, Long.parseLong(
- "FFFFFFFFF", 16));
- assertTrue("Returned incorrect value from octal string: "
- + Long.parseLong("77777777777"), Long.parseLong("77777777777",
- 8) == 8589934591L);
- assertEquals("Returned incorrect value for 0 hex", 0, Long
- .parseLong("0", 16));
- assertTrue("Returned incorrect value for most negative value hex", Long
- .parseLong("-8000000000000000", 16) == 0x8000000000000000L);
- assertTrue("Returned incorrect value for most positive value hex", Long
- .parseLong("7fffffffffffffff", 16) == 0x7fffffffffffffffL);
- assertEquals("Returned incorrect value for 0 decimal", 0, Long.parseLong(
- "0", 10));
- assertTrue(
- "Returned incorrect value for most negative value decimal",
- Long.parseLong("-9223372036854775808", 10) == 0x8000000000000000L);
- assertTrue(
- "Returned incorrect value for most positive value decimal",
- Long.parseLong("9223372036854775807", 10) == 0x7fffffffffffffffL);
-
- boolean exception = false;
- try {
- Long.parseLong("999999999999", 8);
- } catch (NumberFormatException e) {
- // correct
- exception = true;
- }
- assertTrue("Failed to throw exception when passed invalid string",
- exception);
-
- exception = false;
- try {
- Long.parseLong("9223372036854775808", 10);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
-
- exception = false;
- try {
- Long.parseLong("-9223372036854775809", 10);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
-
- exception = false;
- try {
- Long.parseLong("8000000000000000", 16);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for hex MAX_VALUE + 1", exception);
-
- exception = false;
- try {
- Long.parseLong("-8000000000000001", 16);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for hex MIN_VALUE + 1", exception);
-
- exception = false;
- try {
- Long.parseLong("42325917317067571199", 10);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for 42325917317067571199",
- exception);
- }
-
- /**
- * @tests java.lang.Long#toBinaryString(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toBinaryString",
- args = {long.class}
- )
- public void test_toBinaryStringJ() {
- // Test for method java.lang.String java.lang.Long.toBinaryString(long)
- assertEquals("Incorrect binary string returned", "11011001010010010000", Long.toBinaryString(
- 890000L));
- assertEquals("Incorrect binary string returned",
-
- "1000000000000000000000000000000000000000000000000000000000000000", Long
- .toBinaryString(Long.MIN_VALUE)
- );
- assertEquals("Incorrect binary string returned",
-
- "111111111111111111111111111111111111111111111111111111111111111", Long
- .toBinaryString(Long.MAX_VALUE)
- );
- }
-
- /**
- * @tests java.lang.Long#toHexString(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toHexString",
- args = {long.class}
- )
- public void test_toHexStringJ() {
- // Test for method java.lang.String java.lang.Long.toHexString(long)
- assertEquals("Incorrect hex string returned", "54e0845", Long.toHexString(89000005L)
- );
- assertEquals("Incorrect hex string returned", "8000000000000000", Long.toHexString(
- Long.MIN_VALUE));
- assertEquals("Incorrect hex string returned", "7fffffffffffffff", Long.toHexString(
- Long.MAX_VALUE));
- }
-
- /**
- * @tests java.lang.Long#toOctalString(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toOctalString",
- args = {long.class}
- )
- public void test_toOctalStringJ() {
- // Test for method java.lang.String java.lang.Long.toOctalString(long)
- assertEquals("Returned incorrect oct string", "77777777777", Long.toOctalString(
- 8589934591L));
- assertEquals("Returned incorrect oct string", "1000000000000000000000", Long.toOctalString(
- Long.MIN_VALUE));
- assertEquals("Returned incorrect oct string", "777777777777777777777", Long.toOctalString(
- Long.MAX_VALUE));
- }
-
- /**
- * @tests java.lang.Long#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString2() {
- // Test for method java.lang.String java.lang.Long.toString()
- Long l = new Long(89000000005L);
- assertEquals("Returned incorrect String",
- "89000000005", l.toString());
- assertEquals("Returned incorrect String", "-9223372036854775808", new Long(Long.MIN_VALUE)
- .toString());
- assertEquals("Returned incorrect String", "9223372036854775807", new Long(Long.MAX_VALUE)
- .toString());
- }
-
- /**
- * @tests java.lang.Long#toString(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {long.class}
- )
- public void test_toStringJ2() {
- // Test for method java.lang.String java.lang.Long.toString(long)
-
- assertEquals("Returned incorrect String", "89000000005", Long.toString(89000000005L)
- );
- assertEquals("Returned incorrect String", "-9223372036854775808", Long.toString(Long.MIN_VALUE)
- );
- assertEquals("Returned incorrect String", "9223372036854775807", Long.toString(Long.MAX_VALUE)
- );
- }
-
- /**
- * @tests java.lang.Long#toString(long, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {long.class, int.class}
- )
- public void test_toStringJI() {
- // Test for method java.lang.String java.lang.Long.toString(long, int)
- assertEquals("Returned incorrect dec string", "100000000", Long.toString(100000000L,
- 10));
- assertEquals("Returned incorrect hex string", "fffffffff", Long.toString(68719476735L,
- 16));
- assertEquals("Returned incorrect oct string", "77777777777", Long.toString(8589934591L,
- 8));
- assertEquals("Returned incorrect bin string",
- "1111111111111111111111111111111111111111111", Long.toString(
- 8796093022207L, 2));
- assertEquals("Returned incorrect min string", "-9223372036854775808", Long.toString(
- 0x8000000000000000L, 10));
- assertEquals("Returned incorrect max string", "9223372036854775807", Long.toString(
- 0x7fffffffffffffffL, 10));
- assertEquals("Returned incorrect min string", "-8000000000000000", Long.toString(
- 0x8000000000000000L, 16));
- assertEquals("Returned incorrect max string", "7fffffffffffffff", Long.toString(
- 0x7fffffffffffffffL, 16));
- }
-
- /**
- * @tests java.lang.Long#valueOf(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {java.lang.String.class}
- )
- public void test_valueOfLjava_lang_String2() {
- // Test for method java.lang.Long
- // java.lang.Long.valueOf(java.lang.String)
- assertEquals("Returned incorrect value", 100000000L, Long.valueOf("100000000")
- .longValue());
- assertTrue("Returned incorrect value", Long.valueOf(
- "9223372036854775807").longValue() == Long.MAX_VALUE);
- assertTrue("Returned incorrect value", Long.valueOf(
- "-9223372036854775808").longValue() == Long.MIN_VALUE);
-
- boolean exception = false;
- try {
- Long
- .valueOf("999999999999999999999999999999999999999999999999999999999999");
- } catch (NumberFormatException e) {
- // correct
- exception = true;
- }
- assertTrue("Failed to throw exception when passed invalid string",
- exception);
-
- exception = false;
- try {
- Long.valueOf("9223372036854775808");
- } catch (NumberFormatException e) {
- // correct
- exception = true;
- }
- assertTrue("Failed to throw exception when passed invalid string",
- exception);
-
- exception = false;
- try {
- Long.valueOf("-9223372036854775809");
- } catch (NumberFormatException e) {
- // correct
- exception = true;
- }
- assertTrue("Failed to throw exception when passed invalid string",
- exception);
- }
-
- /**
- * @tests java.lang.Long#valueOf(java.lang.String, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {java.lang.String.class, int.class}
- )
- public void test_valueOfLjava_lang_StringI() {
- // Test for method java.lang.Long
- // java.lang.Long.valueOf(java.lang.String, int)
- assertEquals("Returned incorrect value", 100000000L, Long.valueOf("100000000", 10)
- .longValue());
- assertEquals("Returned incorrect value from hex string", 68719476735L, Long.valueOf(
- "FFFFFFFFF", 16).longValue());
- assertTrue("Returned incorrect value from octal string: "
- + Long.valueOf("77777777777", 8).toString(), Long.valueOf(
- "77777777777", 8).longValue() == 8589934591L);
- assertTrue("Returned incorrect value", Long.valueOf(
- "9223372036854775807", 10).longValue() == Long.MAX_VALUE);
- assertTrue("Returned incorrect value", Long.valueOf(
- "-9223372036854775808", 10).longValue() == Long.MIN_VALUE);
- assertTrue("Returned incorrect value", Long.valueOf("7fffffffffffffff",
- 16).longValue() == Long.MAX_VALUE);
- assertTrue("Returned incorrect value", Long.valueOf(
- "-8000000000000000", 16).longValue() == Long.MIN_VALUE);
-
- boolean exception = false;
- try {
- Long.valueOf("999999999999", 8);
- } catch (NumberFormatException e) {
- // correct
- exception = true;
- }
- assertTrue("Failed to throw exception when passed invalid string",
- exception);
-
- exception = false;
- try {
- Long.valueOf("9223372036854775808", 10);
- } catch (NumberFormatException e) {
- // correct
- exception = true;
- }
- assertTrue("Failed to throw exception when passed invalid string",
- exception);
-
- exception = false;
- try {
- Long.valueOf("-9223372036854775809", 10);
- } catch (NumberFormatException e) {
- // correct
- exception = true;
- }
- assertTrue("Failed to throw exception when passed invalid string",
- exception);
- }
- /**
- * @tests java.lang.Long#valueOf(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {long.class}
- )
- public void test_valueOfJ() {
- assertEquals(new Long(Long.MIN_VALUE), Long.valueOf(Long.MIN_VALUE));
- assertEquals(new Long(Long.MAX_VALUE), Long.valueOf(Long.MAX_VALUE));
- assertEquals(new Long( 0), Long.valueOf( 0));
-
- long lng = -128;
- while (lng < 128) {
- assertEquals(new Long(lng), Long.valueOf(lng));
- assertSame(Long.valueOf(lng), Long.valueOf(lng));
- lng++;
- }
- }
-
- /**
- * @tests java.lang.Long#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- assertEquals((int)(1L ^ (1L >>> 32)), new Long(1).hashCode());
- assertEquals((int)(2L ^ (2L >>> 32)), new Long(2).hashCode());
- assertEquals((int)(0L ^ (0L >>> 32)), new Long(0).hashCode());
- assertEquals((int)(-1L ^ (-1L >>> 32)), new Long(-1).hashCode());
- }
-
- /**
- * @tests java.lang.Long#Long(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Long",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- assertEquals(new Long(0), new Long("0"));
- assertEquals(new Long(1), new Long("1"));
- assertEquals(new Long(-1), new Long("-1"));
-
- try {
- new Long("0x1");
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {}
-
- try {
- new Long("9.2");
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {}
-
- try {
- new Long("");
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {}
-
- try {
- new Long(null);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {}
- }
-
- /**
- * @tests java.lang.Long#Long
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Long",
- args = {long.class}
- )
- public void test_ConstructorJ() {
- assertEquals(1, new Long(1).intValue());
- assertEquals(2, new Long(2).intValue());
- assertEquals(0, new Long(0).intValue());
- assertEquals(-1, new Long(-1).intValue());
- }
-
- /**
- * @tests java.lang.Long#byteValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't check boundary values.",
- method = "byteValue",
- args = {}
- )
- public void test_byteValue2() {
- assertEquals(1, new Long(1).byteValue());
- assertEquals(2, new Long(2).byteValue());
- assertEquals(0, new Long(0).byteValue());
- assertEquals(-1, new Long(-1).byteValue());
- }
-
- /**
- * @tests java.lang.Long#equals(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- assertEquals(new Long(0), Long.valueOf(0));
- assertEquals(new Long(1), Long.valueOf(1));
- assertEquals(new Long(-1), Long.valueOf(-1));
-
- Long fixture = new Long(25);
- assertEquals(fixture, fixture);
- assertFalse(fixture.equals(null));
- assertFalse(fixture.equals("Not a Long"));
- }
-
- /**
- * @tests java.lang.Long#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- assertEquals("-1", new Long(-1).toString());
- assertEquals("0", new Long(0).toString());
- assertEquals("1", new Long(1).toString());
- assertEquals("-1", new Long(0xFFFFFFFF).toString());
- }
-
- /**
- * @tests java.lang.Long#toString
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {long.class}
- )
- public void test_toStringJ() {
- assertEquals("-1", Long.toString(-1));
- assertEquals("0", Long.toString(0));
- assertEquals("1", Long.toString(1));
- assertEquals("-1", Long.toString(0xFFFFFFFF));
- }
-
- /**
- * @tests java.lang.Long#valueOf(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {java.lang.String.class}
- )
- public void test_valueOfLjava_lang_String() {
- assertEquals(new Long(0), Long.valueOf("0"));
- assertEquals(new Long(1), Long.valueOf("1"));
- assertEquals(new Long(-1), Long.valueOf("-1"));
-
- try {
- Long.valueOf("0x1");
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {}
-
- try {
- Long.valueOf("9.2");
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {}
-
- try {
- Long.valueOf("");
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {}
-
- try {
- Long.valueOf(null);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {}
- }
-
- /**
- * @tests java.lang.Long#valueOf(String,long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {java.lang.String.class, int.class}
- )
- public void test_valueOfLjava_lang_StringJ() {
- assertEquals(new Long(0), Long.valueOf("0", 10));
- assertEquals(new Long(1), Long.valueOf("1", 10));
- assertEquals(new Long(-1), Long.valueOf("-1", 10));
-
- //must be consistent with Character.digit()
- assertEquals(Character.digit('1', 2), Long.valueOf("1", 2).byteValue());
- assertEquals(Character.digit('F', 16), Long.valueOf("F", 16).byteValue());
-
- try {
- Long.valueOf("0x1", 10);
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {}
-
- try {
- Long.valueOf("9.2", 10);
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {}
-
- try {
- Long.valueOf("", 10);
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {}
-
- try {
- Long.valueOf(null, 10);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {}
- }
-
- /**
- * @tests java.lang.Long#parseLong(String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't check boundary values.",
- method = "parseLong",
- args = {java.lang.String.class}
- )
- public void test_parseLongLjava_lang_String() {
- assertEquals(0, Long.parseLong("0"));
- assertEquals(1, Long.parseLong("1"));
- assertEquals(-1, Long.parseLong("-1"));
-
- try {
- Long.parseLong("0x1");
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {}
-
- try {
- Long.parseLong("9.2");
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {}
-
- try {
- Long.parseLong("");
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {}
-
- try {
- Long.parseLong(null);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {}
- }
-
- /**
- * @tests java.lang.Long#parseLong(String,long)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Doesn't check boundary values.",
- method = "parseLong",
- args = {java.lang.String.class, int.class}
- )
- public void test_parseLongLjava_lang_StringJ() {
- assertEquals(0, Long.parseLong("0", 10));
- assertEquals(1, Long.parseLong("1", 10));
- assertEquals(-1, Long.parseLong("-1", 10));
-
- //must be consistent with Character.digit()
- assertEquals(Character.digit('1', 2), Long.parseLong("1", 2));
- assertEquals(Character.digit('F', 16), Long.parseLong("F", 16));
-
- try {
- Long.parseLong("0x1", 10);
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {}
-
- try {
- Long.parseLong("9.2", 10);
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {}
-
- try {
- Long.parseLong("", 10);
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {}
-
- try {
- Long.parseLong(null, 10);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {}
- }
-
- /**
- * @tests java.lang.Long#decode(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "decode",
- args = {java.lang.String.class}
- )
- public void test_decodeLjava_lang_String() {
- assertEquals(new Long(0), Long.decode("0"));
- assertEquals(new Long(1), Long.decode("1"));
- assertEquals(new Long(-1), Long.decode("-1"));
- assertEquals(new Long(0xF), Long.decode("0xF"));
- assertEquals(new Long(0xF), Long.decode("#F"));
- assertEquals(new Long(0xF), Long.decode("0XF"));
- assertEquals(new Long(07), Long.decode("07"));
-
- try {
- Long.decode("9.2");
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {}
-
- try {
- Long.decode("");
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {}
-
- try {
- Long.decode(null);
- //undocumented NPE, but seems consistent across JREs
- fail("Expected NullPointerException with null string.");
- } catch (NullPointerException e) {}
- }
-
- /**
- * @tests java.lang.Long#doubleValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "doubleValue",
- args = {}
- )
- public void test_doubleValue() {
- assertEquals(-1D, new Long(-1).doubleValue(), 0D);
- assertEquals(0D, new Long(0).doubleValue(), 0D);
- assertEquals(1D, new Long(1).doubleValue(), 0D);
- }
-
- /**
- * @tests java.lang.Long#floatValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "floatValue",
- args = {}
- )
- public void test_floatValue() {
- assertEquals(-1F, new Long(-1).floatValue(), 0F);
- assertEquals(0F, new Long(0).floatValue(), 0F);
- assertEquals(1F, new Long(1).floatValue(), 0F);
-
- assertEquals(Long.MAX_VALUE, new Long(Long.MAX_VALUE).floatValue(), 0F);
- assertEquals(Long.MIN_VALUE, new Long(Long.MIN_VALUE).floatValue(), 0F);
- }
-
- /**
- * @tests java.lang.Long#intValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "intValue",
- args = {}
- )
- public void test_intValue() {
- assertEquals(-1, new Long(-1).intValue());
- assertEquals(0, new Long(0).intValue());
- assertEquals(1, new Long(1).intValue());
-
- assertEquals(-1, new Long(Long.MAX_VALUE).intValue());
- assertEquals(0, new Long(Long.MIN_VALUE).intValue());
- }
-
- /**
- * @tests java.lang.Long#longValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "longValue",
- args = {}
- )
- public void test_longValue() {
- assertEquals(-1L, new Long(-1).longValue());
- assertEquals(0L, new Long(0).longValue());
- assertEquals(1L, new Long(1).longValue());
-
- assertEquals(Long.MAX_VALUE, new Long(Long.MAX_VALUE).longValue());
- assertEquals(Long.MIN_VALUE, new Long(Long.MIN_VALUE).longValue());
- }
-
- /**
- * @tests java.lang.Long#shortValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "shortValue",
- args = {}
- )
- public void test_shortValue() {
- assertEquals(-1, new Long(-1).shortValue());
- assertEquals(0, new Long(0).shortValue());
- assertEquals(1, new Long(1).shortValue());
-
- assertEquals(-1, new Long(Long.MAX_VALUE).shortValue());
- assertEquals(0, new Long(Long.MIN_VALUE).shortValue());
- }
- /**
- * @tests java.lang.Long#highestOneBit(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "highestOneBit",
- args = {long.class}
- )
- public void test_highestOneBitJ() {
- assertEquals(0x08, Long.highestOneBit(0x0A));
- assertEquals(0x08, Long.highestOneBit(0x0B));
- assertEquals(0x08, Long.highestOneBit(0x0C));
- assertEquals(0x08, Long.highestOneBit(0x0F));
- assertEquals(0x80, Long.highestOneBit(0xFF));
-
- assertEquals(0x080000, Long.highestOneBit(0x0F1234));
- assertEquals(0x800000, Long.highestOneBit(0xFF9977));
-
- assertEquals(0x8000000000000000L, Long.highestOneBit(0xFFFFFFFFFFFFFFFFL));
-
- assertEquals(0, Long.highestOneBit(0));
- assertEquals(1, Long.highestOneBit(1));
- assertEquals(0x8000000000000000L, Long.highestOneBit(-1));
- }
-
- /**
- * @tests java.lang.Long#lowestOneBit(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lowestOneBit",
- args = {long.class}
- )
- public void test_lowestOneBitJ() {
- assertEquals(0x10, Long.lowestOneBit(0xF0));
-
- assertEquals(0x10, Long.lowestOneBit(0x90));
- assertEquals(0x10, Long.lowestOneBit(0xD0));
-
- assertEquals(0x10, Long.lowestOneBit(0x123490));
- assertEquals(0x10, Long.lowestOneBit(0x1234D0));
-
- assertEquals(0x100000, Long.lowestOneBit(0x900000));
- assertEquals(0x100000, Long.lowestOneBit(0xD00000));
-
- assertEquals(0x40, Long.lowestOneBit(0x40));
- assertEquals(0x40, Long.lowestOneBit(0xC0));
-
- assertEquals(0x4000, Long.lowestOneBit(0x4000));
- assertEquals(0x4000, Long.lowestOneBit(0xC000));
-
- assertEquals(0x4000, Long.lowestOneBit(0x99994000));
- assertEquals(0x4000, Long.lowestOneBit(0x9999C000));
-
- assertEquals(0, Long.lowestOneBit(0));
- assertEquals(1, Long.lowestOneBit(1));
- assertEquals(1, Long.lowestOneBit(-1));
- }
- /**
- * @tests java.lang.Long#numberOfLeadingZeros(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "numberOfLeadingZeros",
- args = {long.class}
- )
- public void test_numberOfLeadingZerosJ() {
- assertEquals(64, Long.numberOfLeadingZeros(0x0L));
- assertEquals(63, Long.numberOfLeadingZeros(0x1));
- assertEquals(62, Long.numberOfLeadingZeros(0x2));
- assertEquals(62, Long.numberOfLeadingZeros(0x3));
- assertEquals(61, Long.numberOfLeadingZeros(0x4));
- assertEquals(61, Long.numberOfLeadingZeros(0x5));
- assertEquals(61, Long.numberOfLeadingZeros(0x6));
- assertEquals(61, Long.numberOfLeadingZeros(0x7));
- assertEquals(60, Long.numberOfLeadingZeros(0x8));
- assertEquals(60, Long.numberOfLeadingZeros(0x9));
- assertEquals(60, Long.numberOfLeadingZeros(0xA));
- assertEquals(60, Long.numberOfLeadingZeros(0xB));
- assertEquals(60, Long.numberOfLeadingZeros(0xC));
- assertEquals(60, Long.numberOfLeadingZeros(0xD));
- assertEquals(60, Long.numberOfLeadingZeros(0xE));
- assertEquals(60, Long.numberOfLeadingZeros(0xF));
- assertEquals(59, Long.numberOfLeadingZeros(0x10));
- assertEquals(56, Long.numberOfLeadingZeros(0x80));
- assertEquals(56, Long.numberOfLeadingZeros(0xF0));
- assertEquals(55, Long.numberOfLeadingZeros(0x100));
- assertEquals(52, Long.numberOfLeadingZeros(0x800));
- assertEquals(52, Long.numberOfLeadingZeros(0xF00));
- assertEquals(51, Long.numberOfLeadingZeros(0x1000));
- assertEquals(48, Long.numberOfLeadingZeros(0x8000));
- assertEquals(48, Long.numberOfLeadingZeros(0xF000));
- assertEquals(47, Long.numberOfLeadingZeros(0x10000));
- assertEquals(44, Long.numberOfLeadingZeros(0x80000));
- assertEquals(44, Long.numberOfLeadingZeros(0xF0000));
- assertEquals(43, Long.numberOfLeadingZeros(0x100000));
- assertEquals(40, Long.numberOfLeadingZeros(0x800000));
- assertEquals(40, Long.numberOfLeadingZeros(0xF00000));
- assertEquals(39, Long.numberOfLeadingZeros(0x1000000));
- assertEquals(36, Long.numberOfLeadingZeros(0x8000000));
- assertEquals(36, Long.numberOfLeadingZeros(0xF000000));
- assertEquals(35, Long.numberOfLeadingZeros(0x10000000));
- assertEquals(0, Long.numberOfLeadingZeros(0x80000000));
- assertEquals(0, Long.numberOfLeadingZeros(0xF0000000));
-
- assertEquals(1, Long.numberOfLeadingZeros(Long.MAX_VALUE));
- assertEquals(0, Long.numberOfLeadingZeros(Long.MIN_VALUE));
- }
-
- /**
- * @tests java.lang.Long#numberOfTrailingZeros(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "numberOfTrailingZeros",
- args = {long.class}
- )
- public void test_numberOfTrailingZerosJ() {
- assertEquals(64, Long.numberOfTrailingZeros(0x0));
- assertEquals(63, Long.numberOfTrailingZeros(Long.MIN_VALUE));
- assertEquals(0, Long.numberOfTrailingZeros(Long.MAX_VALUE));
-
- assertEquals(0, Long.numberOfTrailingZeros(0x1));
- assertEquals(3, Long.numberOfTrailingZeros(0x8));
- assertEquals(0, Long.numberOfTrailingZeros(0xF));
-
- assertEquals(4, Long.numberOfTrailingZeros(0x10));
- assertEquals(7, Long.numberOfTrailingZeros(0x80));
- assertEquals(4, Long.numberOfTrailingZeros(0xF0));
-
- assertEquals(8, Long.numberOfTrailingZeros(0x100));
- assertEquals(11, Long.numberOfTrailingZeros(0x800));
- assertEquals(8, Long.numberOfTrailingZeros(0xF00));
-
- assertEquals(12, Long.numberOfTrailingZeros(0x1000));
- assertEquals(15, Long.numberOfTrailingZeros(0x8000));
- assertEquals(12, Long.numberOfTrailingZeros(0xF000));
-
- assertEquals(16, Long.numberOfTrailingZeros(0x10000));
- assertEquals(19, Long.numberOfTrailingZeros(0x80000));
- assertEquals(16, Long.numberOfTrailingZeros(0xF0000));
-
- assertEquals(20, Long.numberOfTrailingZeros(0x100000));
- assertEquals(23, Long.numberOfTrailingZeros(0x800000));
- assertEquals(20, Long.numberOfTrailingZeros(0xF00000));
-
- assertEquals(24, Long.numberOfTrailingZeros(0x1000000));
- assertEquals(27, Long.numberOfTrailingZeros(0x8000000));
- assertEquals(24, Long.numberOfTrailingZeros(0xF000000));
-
- assertEquals(28, Long.numberOfTrailingZeros(0x10000000));
- assertEquals(31, Long.numberOfTrailingZeros(0x80000000));
- assertEquals(28, Long.numberOfTrailingZeros(0xF0000000));
- }
-
- /**
- * @tests java.lang.Long#bitCount(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "bitCount",
- args = {long.class}
- )
- public void test_bitCountJ() {
- assertEquals(0, Long.bitCount(0x0));
- assertEquals(1, Long.bitCount(0x1));
- assertEquals(1, Long.bitCount(0x2));
- assertEquals(2, Long.bitCount(0x3));
- assertEquals(1, Long.bitCount(0x4));
- assertEquals(2, Long.bitCount(0x5));
- assertEquals(2, Long.bitCount(0x6));
- assertEquals(3, Long.bitCount(0x7));
- assertEquals(1, Long.bitCount(0x8));
- assertEquals(2, Long.bitCount(0x9));
- assertEquals(2, Long.bitCount(0xA));
- assertEquals(3, Long.bitCount(0xB));
- assertEquals(2, Long.bitCount(0xC));
- assertEquals(3, Long.bitCount(0xD));
- assertEquals(3, Long.bitCount(0xE));
- assertEquals(4, Long.bitCount(0xF));
-
- assertEquals(8, Long.bitCount(0xFF));
- assertEquals(12, Long.bitCount(0xFFF));
- assertEquals(16, Long.bitCount(0xFFFF));
- assertEquals(20, Long.bitCount(0xFFFFF));
- assertEquals(24, Long.bitCount(0xFFFFFF));
- assertEquals(28, Long.bitCount(0xFFFFFFF));
- assertEquals(64, Long.bitCount(0xFFFFFFFFFFFFFFFFL));
- }
-
- /**
- * @tests java.lang.Long#rotateLeft(long,long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "rotateLeft",
- args = {long.class, int.class}
- )
- public void test_rotateLeftJI() {
- assertEquals(0xF, Long.rotateLeft(0xF, 0));
- assertEquals(0xF0, Long.rotateLeft(0xF, 4));
- assertEquals(0xF00, Long.rotateLeft(0xF, 8));
- assertEquals(0xF000, Long.rotateLeft(0xF, 12));
- assertEquals(0xF0000, Long.rotateLeft(0xF, 16));
- assertEquals(0xF00000, Long.rotateLeft(0xF, 20));
- assertEquals(0xF000000, Long.rotateLeft(0xF, 24));
- assertEquals(0xF0000000L, Long.rotateLeft(0xF, 28));
- assertEquals(0xF000000000000000L, Long.rotateLeft(0xF000000000000000L, 64));
- }
-
- /**
- * @tests java.lang.Long#rotateRight(long,long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "rotateRight",
- args = {long.class, int.class}
- )
- public void test_rotateRightJI() {
- assertEquals(0xF, Long.rotateRight(0xF0, 4));
- assertEquals(0xF, Long.rotateRight(0xF00, 8));
- assertEquals(0xF, Long.rotateRight(0xF000, 12));
- assertEquals(0xF, Long.rotateRight(0xF0000, 16));
- assertEquals(0xF, Long.rotateRight(0xF00000, 20));
- assertEquals(0xF, Long.rotateRight(0xF000000, 24));
- assertEquals(0xF, Long.rotateRight(0xF0000000L, 28));
- assertEquals(0xF000000000000000L, Long.rotateRight(0xF000000000000000L, 64));
- assertEquals(0xF000000000000000L, Long.rotateRight(0xF000000000000000L, 0));
-
- }
-
- /**
- * @tests java.lang.Long#reverseBytes(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reverseBytes",
- args = {long.class}
- )
- public void test_reverseBytesJ() {
- assertEquals(0xAABBCCDD00112233L, Long.reverseBytes(0x33221100DDCCBBAAL));
- assertEquals(0x1122334455667788L, Long.reverseBytes(0x8877665544332211L));
- assertEquals(0x0011223344556677L, Long.reverseBytes(0x7766554433221100L));
- assertEquals(0x2000000000000002L, Long.reverseBytes(0x0200000000000020L));
- }
-
- /**
- * @tests java.lang.Long#reverse(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reverse",
- args = {long.class}
- )
- public void test_reverseJ() {
- assertEquals(0, Long.reverse(0));
- assertEquals(-1, Long.reverse(-1));
- assertEquals(0x8000000000000000L,Long.reverse(1));
- }
-
- /**
- * @tests java.lang.Long#signum(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "signum",
- args = {long.class}
- )
- public void test_signumJ() {
- for (int i = -128; i<0; i++) {
- assertEquals(-1, Long.signum(i));
- }
- assertEquals(0, Long.signum(0));
- for (int i = 1; i<=127; i++) {
- assertEquals(1, Long.signum(i));
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MathTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MathTest.java
deleted file mode 100644
index 4d5f04d..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MathTest.java
+++ /dev/null
@@ -1,1276 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(Math.class)
-public class MathTest extends junit.framework.TestCase {
-
- double HYP = Math.sqrt(2.0);
-
- double OPP = 1.0;
-
- double ADJ = 1.0;
-
- /* Required to make previous preprocessor flags work - do not remove */
- int unused = 0;
-
- public static void assertEquals(String message, double expected, double actual, double delta) {
- if (delta == 0D)
- junit.framework.Assert.assertEquals(message, expected, actual, Math.ulp(expected));
- else
- junit.framework.Assert.assertEquals(message, expected, actual, delta);
- }
-
- public static void assertEquals(String message, float expected, float actual, float delta) {
- if (delta == 0F)
- junit.framework.Assert.assertEquals(message, expected, actual, Math.ulp(expected));
- else
- junit.framework.Assert.assertEquals(message, expected, actual, delta);
- }
-
- /**
- * @tests java.lang.Math#abs(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "abs",
- args = {double.class}
- )
- public void test_absD() {
- // Test for method double java.lang.Math.abs(double)
- assertTrue("Incorrect double abs value",
- (Math.abs(-1908.8976) == 1908.8976));
- assertTrue("Incorrect double abs value",
- (Math.abs(1908.8976) == 1908.8976));
- assertEquals(0.0, Math.abs(0.0));
- assertEquals(0.0, Math.abs(-0.0));
- assertEquals(Double.POSITIVE_INFINITY,
- Math.abs(Double.POSITIVE_INFINITY));
- assertEquals(Double.POSITIVE_INFINITY,
- Math.abs(Double.NEGATIVE_INFINITY));
-
- assertEquals(Double.NaN, Math.abs(Double.NaN));
- }
-
- /**
- * @tests java.lang.Math#abs(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "abs",
- args = {float.class}
- )
- public void test_absF() {
- // Test for method float java.lang.Math.abs(float)
- assertTrue("Incorrect float abs value",
- (Math.abs(-1908.8976f) == 1908.8976f));
- assertTrue("Incorrect float abs value",
- (Math.abs(1908.8976f) == 1908.8976f));
-
- assertEquals(0.0f, Math.abs(0.0f));
- assertEquals(0.0f, Math.abs(-0.0f));
- assertEquals(Float.POSITIVE_INFINITY,
- Math.abs(Float.POSITIVE_INFINITY));
- assertEquals(Float.POSITIVE_INFINITY,
- Math.abs(Float.NEGATIVE_INFINITY));
-
- assertEquals(Float.NaN, Math.abs(Float.NaN));
- }
-
- /**
- * @tests java.lang.Math#abs(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "abs",
- args = {int.class}
- )
- public void test_absI() {
- // Test for method int java.lang.Math.abs(int)
- assertTrue("Incorrect int abs value", (Math.abs(-1908897) == 1908897));
- assertTrue("Incorrect int abs value", (Math.abs(1908897) == 1908897));
-
- assertEquals(Integer.MIN_VALUE, Math.abs(Integer.MIN_VALUE));
- }
-
- /**
- * @tests java.lang.Math#abs(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "abs",
- args = {long.class}
- )
- public void test_absJ() {
- // Test for method long java.lang.Math.abs(long)
- assertTrue("Incorrect long abs value",
- (Math.abs(-19088976000089L) == 19088976000089L));
- assertTrue("Incorrect long abs value",
- (Math.abs(19088976000089L) == 19088976000089L));
-
- assertEquals(Long.MIN_VALUE, Math.abs(Long.MIN_VALUE));
- }
-
- /**
- * @tests java.lang.Math#acos(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "acos",
- args = {double.class}
- )
- public void test_acosD() {
- // Test for method double java.lang.Math.acos(double)
- double r = Math.cos(Math.acos(ADJ / HYP));
- long lr = Double.doubleToLongBits(r);
- long t = Double.doubleToLongBits(ADJ / HYP);
- assertTrue("Returned incorrect arc cosine", lr == t || (lr + 1) == t
- || (lr - 1) == t);
-
- assertEquals(Double.NaN, Math.acos(Double.MAX_VALUE));
- assertEquals(Double.NaN, Math.acos(Double.NaN));
- }
-
- /**
- * @tests java.lang.Math#asin(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "asin",
- args = {double.class}
- )
- public void test_asinD() {
- // Test for method double java.lang.Math.asin(double)
- double r = Math.sin(Math.asin(OPP / HYP));
- long lr = Double.doubleToLongBits(r);
- long t = Double.doubleToLongBits(OPP / HYP);
- assertTrue("Returned incorrect arc sine", lr == t || (lr + 1) == t
- || (lr - 1) == t);
-
- assertEquals(Double.NaN, Math.asin(Double.MAX_VALUE));
- assertEquals(Double.NaN, Math.asin(Double.NaN));
- assertEquals(0, Math.asin(0), 0);
- assertEquals(-0, Math.asin(-0), 0);
- }
-
- /**
- * @tests java.lang.Math#atan(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "atan",
- args = {double.class}
- )
- public void test_atanD() {
- // Test for method double java.lang.Math.atan(double)
- double answer = Math.tan(Math.atan(1.0));
- assertTrue("Returned incorrect arc tangent: " + answer, answer <= 1.0
- && answer >= 9.9999999999999983E-1);
-
- assertEquals(Double.NaN, Math.atan(Double.NaN));
- assertEquals(0.0, Math.atan(0.0), 0.0);
- assertEquals(-0.0, Math.atan(-0.0), 0.0);
- }
-
- /**
- * @tests java.lang.Math#atan2(double, double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "atan2",
- args = {double.class, double.class}
- )
- public void test_atan2DD() {
- double pi = 3.141592653589793;
- // Test for method double java.lang.Math.atan2(double, double)
- double answer = Math.atan(Math.tan(1.0));
- assertTrue("Returned incorrect arc tangent: " + answer, answer <= 1.0
- && answer >= 9.9999999999999983E-1);
-
- assertEquals(Double.NaN, Math.atan2(Double.NaN, 1.0));
- assertEquals(Double.NaN, Math.atan2(1.0, Double.NaN));
-
- assertEquals(0.0, Math.atan2(0, 1));
- assertEquals(0.0, Math.atan2(1, Double.POSITIVE_INFINITY));
-
- assertEquals(-0.0, Math.atan2(-0.0, 1.0));
- assertEquals(-0.0, Math.atan2(-1.0, Double.POSITIVE_INFINITY));
-
- assertEquals(pi, Math.atan2(0.0, -1.0));
- assertEquals(pi, Math.atan2(1.0, Double.NEGATIVE_INFINITY));
-
- assertEquals(-pi, Math.atan2(-0.0, -1.0));
- assertEquals(-pi, Math.atan2(-1.0, Double.NEGATIVE_INFINITY));
-
- assertEquals(pi/2, Math.atan2(1.0, 0.0));
- assertEquals(pi/2, Math.atan2(1.0, -0.0));
-
- assertEquals(pi/2, Math.atan2(Double.POSITIVE_INFINITY, 1));
- assertEquals(pi/2, Math.atan2(Double.POSITIVE_INFINITY, -1));
-
- assertEquals(-pi/2, Math.atan2(-1, 0));
- assertEquals(-pi/2, Math.atan2(-1, -0));
- assertEquals(-pi/2, Math.atan2(Double.NEGATIVE_INFINITY, 1));
-
- assertEquals(pi/4, Math.atan2(Double.POSITIVE_INFINITY,
- Double.POSITIVE_INFINITY));
- assertEquals(3*pi/4, Math.atan2(Double.POSITIVE_INFINITY,
- Double.NEGATIVE_INFINITY));
- assertEquals(-pi/4, Math.atan2(Double.NEGATIVE_INFINITY,
- Double.POSITIVE_INFINITY));
- assertEquals(-3*pi/4, Math.atan2(Double.NEGATIVE_INFINITY,
- Double.NEGATIVE_INFINITY));
- }
-
- /**
- * @tests java.lang.Math#cbrt(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "cbrt",
- args = {double.class}
- )
- public void test_cbrt_D() {
- //Test for special situations
- assertTrue("Should return Double.NaN", Double.isNaN(Math
- .cbrt(Double.NaN)));
- assertEquals("Should return Double.POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, Math
- .cbrt(Double.POSITIVE_INFINITY), 0D);
- assertEquals("Should return Double.NEGATIVE_INFINITY",
- Double.NEGATIVE_INFINITY, Math
- .cbrt(Double.NEGATIVE_INFINITY), 0D);
- assertEquals(Double.doubleToLongBits(0.0), Double.doubleToLongBits(Math
- .cbrt(0.0)));
- assertEquals(Double.doubleToLongBits(+0.0), Double.doubleToLongBits(Math
- .cbrt(+0.0)));
- assertEquals(Double.doubleToLongBits(-0.0), Double.doubleToLongBits(Math
- .cbrt(-0.0)));
-
- assertEquals("Should return 3.0", 3.0, Math.cbrt(27.0), 0D);
- assertEquals("Should return 23.111993172558684", 23.111993172558684,
- Math.cbrt(12345.6), 0D);
- assertEquals("Should return 5.643803094122362E102",
- 5.643803094122362E102, Math.cbrt(Double.MAX_VALUE), 0D);
- assertEquals("Should return 0.01", 0.01, Math.cbrt(0.000001), 0D);
-
- assertEquals("Should return -3.0", -3.0, Math.cbrt(-27.0), 0D);
- assertEquals("Should return -23.111993172558684", -23.111993172558684,
- Math.cbrt(-12345.6), 0D);
- assertEquals("Should return 1.7031839360032603E-108",
- 1.7031839360032603E-108, Math.cbrt(Double.MIN_VALUE), 0D);
- assertEquals("Should return -0.01", -0.01, Math.cbrt(-0.000001), 0D);
- }
-
- /**
- * @tests java.lang.Math#ceil(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ceil",
- args = {double.class}
- )
- public void test_ceilD() {
- // Test for method double java.lang.Math.ceil(double)
- assertEquals("Incorrect ceiling for double",
- 79, Math.ceil(78.89), 0);
- assertEquals("Incorrect ceiling for double",
- -78, Math.ceil(-78.89), 0);
-
- assertEquals("Incorrect ceiling for double",
- -78, Math.ceil(-78), 0);
-
- double [] args = {0.0, -0.0, Double.NaN, Double.POSITIVE_INFINITY,
- Double.NEGATIVE_INFINITY};
- for(int i = 0; i < args.length; i++) {
- assertEquals(args[i], Math.ceil(args[i]));
- }
- assertEquals(-0.0, Math.ceil(-0.5));
- }
-
- /**
- * @tests java.lang.Math#cos(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "cos",
- args = {double.class}
- )
- public void test_cosD() {
- // Test for method double java.lang.Math.cos(double)
- assertEquals("Incorrect answer", 1.0, Math.cos(0), 0D);
- assertEquals("Incorrect answer", 0.5403023058681398, Math.cos(1), 0D);
- double [] args = {Double.NaN, Double.POSITIVE_INFINITY,
- Double.NEGATIVE_INFINITY};
- for(int i = 0; i < args.length; i++) {
- assertEquals(args[i], Math.ceil(args[i]));
- }
- }
-
- /**
- * @tests java.lang.Math#cosh(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "cosh",
- args = {double.class}
- )
- public void test_cosh_D() {
- // Test for special situations
- assertTrue(Double.isNaN(Math.cosh(Double.NaN)));
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, Math.cosh(Double.POSITIVE_INFINITY), 0D);
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, Math.cosh(Double.NEGATIVE_INFINITY), 0D);
- assertEquals("Should return 1.0", 1.0, Math.cosh(+0.0), 0D);
- assertEquals("Should return 1.0", 1.0, Math.cosh(-0.0), 0D);
-
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, Math.cosh(1234.56), 0D);
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, Math.cosh(-1234.56), 0D);
- assertEquals("Should return 1.0000000000005", 1.0000000000005, Math
- .cosh(0.000001), 0D);
- assertEquals("Should return 1.0000000000005", 1.0000000000005, Math
- .cosh(-0.000001), 0D);
- assertEquals("Should return 5.212214351945598", 5.212214351945598, Math
- .cosh(2.33482), 0D);
-
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, Math.cosh(Double.MAX_VALUE), 0D);
- assertEquals("Should return 1.0", 1.0, Math.cosh(Double.MIN_VALUE), 0D);
- }
-
- /**
- * @tests java.lang.Math#exp(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "exp",
- args = {double.class}
- )
- public void test_expD() {
- // Test for method double java.lang.Math.exp(double)
- assertTrue("Incorrect answer returned for simple power", Math.abs(Math
- .exp(4D)
- - Math.E * Math.E * Math.E * Math.E) < 0.1D);
- assertTrue("Incorrect answer returned for larger power", Math.log(Math
- .abs(Math.exp(5.5D)) - 5.5D) < 10.0D);
-
- assertEquals("Incorrect returned value for NaN",
- Double.NaN, Math.exp(Double.NaN));
- assertEquals("Incorrect returned value for positive infinity",
- Double.POSITIVE_INFINITY, Math.exp(Double.POSITIVE_INFINITY));
- assertEquals("Incorrect returned value for negative infinity",
- 0, Math.exp(Double.NEGATIVE_INFINITY), 0);
- }
-
- /**
- * @tests java.lang.Math#expm1(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "expm1",
- args = {double.class}
- )
- public void test_expm1_D() {
- // Test for special cases
- assertTrue("Should return NaN", Double.isNaN(Math.expm1(Double.NaN)));
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, Math.expm1(Double.POSITIVE_INFINITY), 0D);
- assertEquals("Should return -1.0", -1.0, Math
- .expm1(Double.NEGATIVE_INFINITY), 0D);
- assertEquals(Double.doubleToLongBits(0.0), Double.doubleToLongBits(Math
- .expm1(0.0)));
- assertEquals(Double.doubleToLongBits(+0.0), Double
- .doubleToLongBits(Math.expm1(+0.0)));
- assertEquals(Double.doubleToLongBits(-0.0), Double
- .doubleToLongBits(Math.expm1(-0.0)));
-
- assertEquals("Should return -9.999950000166666E-6",
- -9.999950000166666E-6, Math.expm1(-0.00001), 0D);
- assertEquals("Should return 1.0145103074469635E60",
- 1.0145103074469635E60, Math.expm1(138.16951162), 0D);
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, Math
- .expm1(123456789123456789123456789.4521584223), 0D);
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, Math.expm1(Double.MAX_VALUE), 0D);
- assertEquals("Should return MIN_VALUE", Double.MIN_VALUE, Math
- .expm1(Double.MIN_VALUE), 0D);
- }
-
- /**
- * @tests java.lang.Math#floor(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "floor",
- args = {double.class}
- )
- public void test_floorD() {
- // Test for method double java.lang.Math.floor(double)
- assertEquals("Incorrect floor for double",
- 78, Math.floor(78.89), 0);
- assertEquals("Incorrect floor for double",
- -79, Math.floor(-78.89), 0);
- assertEquals("Incorrect floor for integer",
- -78, Math.floor(-78), 0);
- double [] args = {0, -0, Double.NaN, Double.POSITIVE_INFINITY,
- Double.NEGATIVE_INFINITY};
- for(int i = 0; i < args.length; i++) {
- assertEquals(args[i], Math.floor(args[i]));
- }
- }
-
- /**
- * @tests java.lang.Math#hypot(double, double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hypot",
- args = {double.class, double.class}
- )
- public void test_hypot_DD() {
- // Test for special cases
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, Math.hypot(Double.POSITIVE_INFINITY,
- 1.0), 0D);
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, Math.hypot(Double.NEGATIVE_INFINITY,
- 123.324), 0D);
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, Math.hypot(-758.2587,
- Double.POSITIVE_INFINITY), 0D);
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, Math.hypot(5687.21,
- Double.NEGATIVE_INFINITY), 0D);
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, Math.hypot(Double.POSITIVE_INFINITY,
- Double.NEGATIVE_INFINITY), 0D);
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, Math.hypot(Double.NEGATIVE_INFINITY,
- Double.POSITIVE_INFINITY), 0D);
- assertTrue("Should be NaN", Double.isNaN(Math.hypot(Double.NaN,
- 2342301.89843)));
- assertTrue("Should be NaN", Double.isNaN(Math.hypot(-345.2680,
- Double.NaN)));
-
- assertEquals("Should return 2396424.905416697", 2396424.905416697, Math
- .hypot(12322.12, -2396393.2258), 0D);
- assertEquals("Should return 138.16958070558556", 138.16958070558556,
- Math.hypot(-138.16951162, 0.13817035864), 0D);
- assertEquals("Should return 1.7976931348623157E308",
- 1.7976931348623157E308, Math.hypot(Double.MAX_VALUE, 211370.35), 0D);
- assertEquals("Should return 5413.7185", 5413.7185, Math.hypot(
- -5413.7185, Double.MIN_VALUE), 0D);
- }
-
- /**
- * @tests java.lang.Math#IEEEremainder(double, double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IEEEremainder",
- args = {double.class, double.class}
- )
- public void test_IEEEremainderDD() {
- // Test for method double java.lang.Math.IEEEremainder(double, double)
- assertEquals("Incorrect remainder returned",
- 0.0, Math.IEEEremainder(1.0, 1.0), 0D);
- assertTrue("Incorrect remainder returned", Math.IEEEremainder(1.32,
- 89.765) >= 1.4705063220631647E-2
- || Math.IEEEremainder(1.32, 89.765) >= 1.4705063220631649E-2);
-
- assertEquals(Double.NaN, Math.IEEEremainder(Double.NaN, Double.NaN));
- assertEquals(Double.NaN, Math.IEEEremainder(Double.NaN, 1.0));
- assertEquals(Double.NaN, Math.IEEEremainder(1.0, Double.NaN));
-
- assertEquals(Double.NaN, Math.IEEEremainder(Double.POSITIVE_INFINITY, 1.0));
- assertEquals(Double.NaN, Math.IEEEremainder(Double.NEGATIVE_INFINITY, 1.0));
- assertEquals(1.0, Math.IEEEremainder(1.0, Double.POSITIVE_INFINITY));
- assertEquals(1.0, Math.IEEEremainder(1.0, Double.NEGATIVE_INFINITY));
- assertEquals(Double.NaN, Math.IEEEremainder(1.0, 0.0));
- assertEquals(Double.NaN, Math.IEEEremainder(1.0, -0.0));
- }
-
- /**
- * @tests java.lang.Math#log(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "log",
- args = {double.class}
- )
- public void test_logD() {
- // Test for method double java.lang.Math.log(double)
- for (double d = 10; d >= -10; d -= 0.5) {
- double answer = Math.log(Math.exp(d));
- assertTrue("Answer does not equal expected answer for d = " + d
- + " answer = " + answer, Math.abs(answer - d) <= Math
- .abs(d * 0.00000001));
- }
- }
-
- /**
- * @tests java.lang.Math#log10(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "log10",
- args = {double.class}
- )
- @SuppressWarnings("boxing")
- public void test_log10_D() {
- // Test for special cases
- assertTrue(Double.isNaN(Math.log10(Double.NaN)));
- assertTrue(Double.isNaN(Math.log10(-2541.05745687234187532)));
- assertTrue(Double.isNaN(Math.log10(-0.1)));
- assertEquals(Double.POSITIVE_INFINITY, Math.log10(Double.POSITIVE_INFINITY));
- assertEquals(Double.NEGATIVE_INFINITY, Math.log10(0.0));
- assertEquals(Double.NEGATIVE_INFINITY, Math.log10(+0.0));
- assertEquals(Double.NEGATIVE_INFINITY, Math.log10(-0.0));
-
- assertEquals(3.0, Math.log10(1000.0));
- assertEquals(14.0, Math.log10(Math.pow(10, 14)));
- assertEquals(3.7389561269540406, Math.log10(5482.2158));
- assertEquals(14.661551142893833, Math.log10(458723662312872.125782332587));
- assertEquals(-0.9083828622192334, Math.log10(0.12348583358871));
- assertEquals(308.25471555991675, Math.log10(Double.MAX_VALUE));
- assertEquals(-323.3062153431158, Math.log10(Double.MIN_VALUE));
- }
-
- /**
- * @tests java.lang.Math#log1p(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "log1p",
- args = {double.class}
- )
- public void test_log1p_D() {
- // Test for special cases
- assertTrue("Should return NaN", Double.isNaN(Math.log1p(Double.NaN)));
- assertTrue("Should return NaN", Double.isNaN(Math.log1p(-32.0482175)));
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, Math.log1p(Double.POSITIVE_INFINITY), 0D);
- assertEquals(Double.doubleToLongBits(0.0), Double.doubleToLongBits(Math
- .log1p(0.0)));
- assertEquals(Double.doubleToLongBits(+0.0), Double
- .doubleToLongBits(Math.log1p(+0.0)));
- assertEquals(Double.doubleToLongBits(-0.0), Double
- .doubleToLongBits(Math.log1p(-0.0)));
-
- assertEquals("Should return -0.2941782295312541", -0.2941782295312541,
- Math.log1p(-0.254856327), 0D);
- assertEquals("Should return 7.368050685564151", 7.368050685564151, Math
- .log1p(1583.542), 0D);
- assertEquals("Should return 0.4633708685409921", 0.4633708685409921,
- Math.log1p(0.5894227), 0D);
- assertEquals("Should return 709.782712893384", 709.782712893384, Math
- .log1p(Double.MAX_VALUE), 0D);
- assertEquals("Should return Double.MIN_VALUE", Double.MIN_VALUE, Math
- .log1p(Double.MIN_VALUE), 0D);
- }
-
- /**
- * @tests java.lang.Math#max(double, double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "max",
- args = {double.class, double.class}
- )
- public void test_maxDD() {
- // Test for method double java.lang.Math.max(double, double)
- assertEquals("Incorrect double max value", 1908897.6000089,
- Math.max(-1908897.6000089,
- 1908897.6000089), 0D);
- assertEquals("Incorrect double max value",
- 1908897.6000089, Math.max(2.0, 1908897.6000089), 0D);
- assertEquals("Incorrect double max value", -2.0, Math.max(-2.0,
- -1908897.6000089), 0D);
-
- assertEquals("Incorrect returned value", Double.NaN,
- Math.max(-1.0, Double.NaN));
- assertEquals("Incorrect returned value", Double.NaN,
- Math.max(Double.NaN, -1.0));
- assertEquals("Incorrect returned value", 0, Math.max(0, -0), 0D);
- }
-
- /**
- * @tests java.lang.Math#max(float, float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "max",
- args = {float.class, float.class}
- )
- public void test_maxFF() {
- // Test for method float java.lang.Math.max(float, float)
- assertTrue("Incorrect float max value", Math.max(-1908897.600f,
- 1908897.600f) == 1908897.600f);
- assertTrue("Incorrect float max value",
- Math.max(2.0f, 1908897.600f) == 1908897.600f);
- assertTrue("Incorrect float max value",
- Math.max(-2.0f, -1908897.600f) == -2.0f);
- assertEquals("Incorrect returned value", Float.NaN,
- Math.max(-1.0f, Float.NaN));
- assertEquals("Incorrect returned value", Float.NaN,
- Math.max(Float.NaN, -1.0f));
- assertEquals("Incorrect returned value", 0f, Math.max(0f, -0f));
- }
-
- /**
- * @tests java.lang.Math#max(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "max",
- args = {int.class, int.class}
- )
- public void test_maxII() {
- // Test for method int java.lang.Math.max(int, int)
- assertEquals("Incorrect int max value",
- 19088976, Math.max(-19088976, 19088976));
- assertEquals("Incorrect int max value",
- 19088976, Math.max(20, 19088976));
- assertEquals("Incorrect int max value", -20, Math.max(-20, -19088976));
- }
-
- /**
- * @tests java.lang.Math#max(long, long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "max",
- args = {long.class, long.class}
- )
- public void test_maxJJ() {
- // Test for method long java.lang.Math.max(long, long)
- assertEquals("Incorrect long max value", 19088976000089L, Math.max(-19088976000089L,
- 19088976000089L));
- assertEquals("Incorrect long max value",
- 19088976000089L, Math.max(20, 19088976000089L));
- assertEquals("Incorrect long max value",
- -20, Math.max(-20, -19088976000089L));
- }
-
- /**
- * @tests java.lang.Math#min(double, double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "min",
- args = {double.class, double.class}
- )
- public void test_minDD() {
- // Test for method double java.lang.Math.min(double, double)
- assertEquals("Incorrect double min value", -1908897.6000089, Math.min(-1908897.6000089,
- 1908897.6000089), 0D);
- assertEquals("Incorrect double min value",
- 2.0, Math.min(2.0, 1908897.6000089), 0D);
- assertEquals("Incorrect double min value", -1908897.6000089, Math.min(-2.0,
- -1908897.6000089), 0D);
- assertEquals("Incorrect returned value", Double.NaN,
- Math.min(-1.0, Double.NaN));
- assertEquals("Incorrect returned value", Double.NaN,
- Math.min(Double.NaN, -1.0));
- assertEquals("Incorrect returned value", -0.0, Math.min(0.0, -0.0));
- }
-
- /**
- * @tests java.lang.Math#min(float, float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "min",
- args = {float.class, float.class}
- )
- public void test_minFF() {
- // Test for method float java.lang.Math.min(float, float)
- assertTrue("Incorrect float min value", Math.min(-1908897.600f,
- 1908897.600f) == -1908897.600f);
- assertTrue("Incorrect float min value",
- Math.min(2.0f, 1908897.600f) == 2.0f);
- assertTrue("Incorrect float min value",
- Math.min(-2.0f, -1908897.600f) == -1908897.600f);
- assertEquals("Incorrect returned value", Float.NaN,
- Math.min(-1.0f, Float.NaN));
- assertEquals("Incorrect returned value", Float.NaN,
- Math.min(Float.NaN, -1.0f));
- assertEquals("Incorrect returned value", -0f, Math.min(0f, -0f));
- }
-
- /**
- * @tests java.lang.Math#min(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "min",
- args = {int.class, int.class}
- )
- public void test_minII() {
- // Test for method int java.lang.Math.min(int, int)
- assertEquals("Incorrect int min value",
- -19088976, Math.min(-19088976, 19088976));
- assertEquals("Incorrect int min value", 20, Math.min(20, 19088976));
- assertEquals("Incorrect int min value",
- -19088976, Math.min(-20, -19088976));
-
- }
-
- /**
- * @tests java.lang.Math#min(long, long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "min",
- args = {long.class, long.class}
- )
- public void test_minJJ() {
- // Test for method long java.lang.Math.min(long, long)
- assertEquals("Incorrect long min value", -19088976000089L, Math.min(-19088976000089L,
- 19088976000089L));
- assertEquals("Incorrect long min value",
- 20, Math.min(20, 19088976000089L));
- assertEquals("Incorrect long min value",
- -19088976000089L, Math.min(-20, -19088976000089L));
- }
-
- /**
- * @tests java.lang.Math#pow(double, double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "pow",
- args = {double.class, double.class}
- )
- @KnownFailure("Math.pow(double a, double b) returns 1.0 if " +
- "the absolute value of the first argument equals 1 and " +
- "the second argument is infinite. It should return NaN.")
- public void test_powDD() {
- // Test for method double java.lang.Math.pow(double, double)
- assertTrue("pow returned incorrect value",
- (long) Math.pow(2, 8) == 256l);
- assertTrue("pow returned incorrect value",
- Math.pow(2, -8) == 0.00390625d);
- assertEquals("Incorrect root returned1",
- 2, Math.sqrt(Math.pow(Math.sqrt(2), 4)), 0);
-
- assertEquals("pow returned incorrect value", 1.0, Math.pow(1, 0));
- assertEquals("pow returned incorrect value", 2.0, Math.pow(2, 1));
- assertEquals("pow returned incorrect value", Double.NaN,
- Math.pow(Double.MAX_VALUE, Double.NaN));
- assertEquals("pow returned incorrect value", Double.NaN,
- Math.pow(Double.NaN, Double.MAX_VALUE));
- assertEquals("pow returned incorrect value", Double.POSITIVE_INFINITY,
- Math.pow(1.1, Double.POSITIVE_INFINITY));
- assertEquals("pow returned incorrect value", Double.POSITIVE_INFINITY,
- Math.pow(0.9, Double.NEGATIVE_INFINITY));
-
- assertEquals("pow returned incorrect value", 0.0,
- Math.pow(1.1, Double.NEGATIVE_INFINITY));
- assertEquals("pow returned incorrect value", 0.0,
- Math.pow(0.9, Double.POSITIVE_INFINITY));
-
- assertEquals("pow returned incorrect value", Double.NaN,
- Math.pow(1.0, Double.NEGATIVE_INFINITY));
- assertEquals("pow returned incorrect value", Double.NaN,
- Math.pow(1.0, Double.POSITIVE_INFINITY));
-
- assertEquals("pow returned incorrect value", 0.0, Math.pow(0, 1));
- assertEquals("pow returned incorrect value", 0.0,
- Math.pow(Double.POSITIVE_INFINITY, -0.1));
-
- assertEquals("pow returned incorrect value", Double.POSITIVE_INFINITY,
- Math.pow(0, -1));
- assertEquals("pow returned incorrect value", Double.POSITIVE_INFINITY,
- Math.pow(Double.POSITIVE_INFINITY, 1));
-
- assertEquals("pow returned incorrect value", 0.0,
- Math.pow(-0.0, 0.9));
- assertEquals("pow returned incorrect value", 0.0,
- Math.pow(Double.NEGATIVE_INFINITY, -0.9));
-
- assertEquals("pow returned incorrect value", -0.0,
- Math.pow(-0.0, 1));
- assertEquals("pow returned incorrect value", -0.0,
- Math.pow(Double.NEGATIVE_INFINITY, -1));
-
- assertEquals("pow returned incorrect value", Double.POSITIVE_INFINITY,
- Math.pow(-0.0, -0.9));
- assertEquals("pow returned incorrect value", Double.POSITIVE_INFINITY,
- Math.pow(Double.NEGATIVE_INFINITY, 0.9));
-
- assertEquals("pow returned incorrect value", Double.NEGATIVE_INFINITY,
- Math.pow(-0.0, -1));
- assertEquals("pow returned incorrect value", Double.NEGATIVE_INFINITY,
- Math.pow(Double.NEGATIVE_INFINITY, 1));
-
- assertEquals("pow returned incorrect value", 0.81, Math.pow(-0.9, 2));
- assertEquals("pow returned incorrect value", -0.9, Math.pow(-0.9, 1));
- assertEquals("pow returned incorrect value", Double.NaN,
- Math.pow(-0.9, 0.1));
- }
-
- /**
- * @tests java.lang.Math#rint(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "rint",
- args = {double.class}
- )
- public void test_rintD() {
- // Test for method double java.lang.Math.rint(double)
- assertEquals("Failed to round properly - up to odd",
- 3.0, Math.rint(2.9), 0D);
- assertTrue("Failed to round properly - NaN", Double.isNaN(Math
- .rint(Double.NaN)));
- assertEquals("Failed to round properly down to even",
- 2.0, Math.rint(2.1), 0D);
- assertTrue("Failed to round properly " + 2.5 + " to even", Math
- .rint(2.5) == 2.0);
- }
-
- /**
- * @tests java.lang.Math#round(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "round",
- args = {double.class}
- )
- public void test_roundD() {
- // Test for method long java.lang.Math.round(double)
- assertEquals("Incorrect rounding of a float", -91, Math.round(-90.89d));
- assertEquals("Incorrect rounding of a float", 0,
- Math.round(Double.NaN));
- assertEquals("Incorrect rounding of a float", Long.MIN_VALUE,
- Math.round(Double.NEGATIVE_INFINITY));
- assertEquals("Incorrect rounding of a float", Long.MAX_VALUE,
- Math.round(Double.POSITIVE_INFINITY));
- }
-
- /**
- * @tests java.lang.Math#round(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "round",
- args = {float.class}
- )
- public void test_roundF() {
- // Test for method int java.lang.Math.round(float)
- assertEquals("Incorrect rounding of a float", -91, Math.round(-90.89f));
- assertEquals("Incorrect rounding of a float", 0,
- Math.round(Float.NaN));
- assertEquals("Incorrect rounding of a float", Integer.MIN_VALUE,
- Math.round(Float.NEGATIVE_INFINITY));
- assertEquals("Incorrect rounding of a float", Integer.MAX_VALUE,
- Math.round(Float.POSITIVE_INFINITY));
- }
-
- /**
- * @tests java.lang.Math#signum(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "signum",
- args = {double.class}
- )
- public void test_signum_D() {
- assertTrue(Double.isNaN(Math.signum(Double.NaN)));
- assertTrue(Double.isNaN(Math.signum(Double.NaN)));
- assertEquals(Double.doubleToLongBits(0.0), Double.doubleToLongBits(Math
- .signum(0.0)));
- assertEquals(Double.doubleToLongBits(+0.0), Double
- .doubleToLongBits(Math.signum(+0.0)));
- assertEquals(Double.doubleToLongBits(-0.0), Double
- .doubleToLongBits(Math.signum(-0.0)));
-
- assertEquals(1.0, Math.signum(253681.2187962), 0D);
- assertEquals(-1.0, Math.signum(-125874693.56), 0D);
- assertEquals(1.0, Math.signum(1.2587E-308), 0D);
- assertEquals(-1.0, Math.signum(-1.2587E-308), 0D);
-
- assertEquals(1.0, Math.signum(Double.MAX_VALUE), 0D);
- assertEquals(1.0, Math.signum(Double.MIN_VALUE), 0D);
- assertEquals(-1.0, Math.signum(-Double.MAX_VALUE), 0D);
- assertEquals(-1.0, Math.signum(-Double.MIN_VALUE), 0D);
- assertEquals(1.0, Math.signum(Double.POSITIVE_INFINITY), 0D);
- assertEquals(-1.0, Math.signum(Double.NEGATIVE_INFINITY), 0D);
- }
-
- /**
- * @tests java.lang.Math#signum(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "signum",
- args = {float.class}
- )
- public void test_signum_F() {
- assertTrue(Float.isNaN(Math.signum(Float.NaN)));
- assertEquals(Float.floatToIntBits(0.0f), Float
- .floatToIntBits(Math.signum(0.0f)));
- assertEquals(Float.floatToIntBits(+0.0f), Float
- .floatToIntBits(Math.signum(+0.0f)));
- assertEquals(Float.floatToIntBits(-0.0f), Float
- .floatToIntBits(Math.signum(-0.0f)));
-
- assertEquals(1.0f, Math.signum(253681.2187962f), 0f);
- assertEquals(-1.0f, Math.signum(-125874693.56f), 0f);
- assertEquals(1.0f, Math.signum(1.2587E-11f), 0f);
- assertEquals(-1.0f, Math.signum(-1.2587E-11f), 0f);
-
- assertEquals(1.0f, Math.signum(Float.MAX_VALUE), 0f);
- assertEquals(1.0f, Math.signum(Float.MIN_VALUE), 0f);
- assertEquals(-1.0f, Math.signum(-Float.MAX_VALUE), 0f);
- assertEquals(-1.0f, Math.signum(-Float.MIN_VALUE), 0f);
- assertEquals(1.0f, Math.signum(Float.POSITIVE_INFINITY), 0f);
- assertEquals(-1.0f, Math.signum(Float.NEGATIVE_INFINITY), 0f);
- }
-
- /**
- * @tests java.lang.Math#sin(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sin",
- args = {double.class}
- )
- public void test_sinD() {
- // Test for method double java.lang.Math.sin(double)
- assertEquals("Incorrect answer", 0.0, Math.sin(0), 0D);
- assertEquals("Incorrect answer", 0.8414709848078965, Math.sin(1), 0D);
-
- double [] args = {Double.NaN, Double.POSITIVE_INFINITY,
- Double.NEGATIVE_INFINITY};
- for(int i = 0; i < args.length; i++) {
- assertEquals("Incorrest returned value.", Double.NaN,
- Math.sin(args[i]));
- }
-
- assertEquals("Incorrest returned value.", 0.0, Math.sin(0.0));
- assertEquals("Incorrest returned value.", -0.0, Math.sin(-0.0));
- }
-
- /**
- * @tests java.lang.Math#sinh(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sinh",
- args = {double.class}
- )
- public void test_sinh_D() {
- // Test for special situations
- assertTrue("Should return NaN", Double.isNaN(Math.sinh(Double.NaN)));
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, Math.sinh(Double.POSITIVE_INFINITY), 0D);
- assertEquals("Should return NEGATIVE_INFINITY",
- Double.NEGATIVE_INFINITY, Math.sinh(Double.NEGATIVE_INFINITY), 0D);
- assertEquals(Double.doubleToLongBits(0.0), Double.doubleToLongBits(Math
- .sinh(0.0)));
- assertEquals(Double.doubleToLongBits(+0.0), Double
- .doubleToLongBits(Math.sinh(+0.0)));
- assertEquals(Double.doubleToLongBits(-0.0), Double
- .doubleToLongBits(Math.sinh(-0.0)));
-
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, Math.sinh(1234.56), 0D);
- assertEquals("Should return NEGATIVE_INFINITY",
- Double.NEGATIVE_INFINITY, Math.sinh(-1234.56), 0D);
- assertEquals("Should return 1.0000000000001666E-6",
- 1.0000000000001666E-6, Math.sinh(0.000001), 0D);
- assertEquals("Should return -1.0000000000001666E-6",
- -1.0000000000001666E-6, Math.sinh(-0.000001), 0D);
- assertEquals("Should return 5.115386441963859", 5.115386441963859, Math
- .sinh(2.33482), 0D);
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, Math.sinh(Double.MAX_VALUE), 0D);
- assertEquals("Should return 4.9E-324", 4.9E-324, Math
- .sinh(Double.MIN_VALUE), 0D);
- }
-
- /**
- * @tests java.lang.Math#sqrt(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sqrt",
- args = {double.class}
- )
- public void test_sqrtD() {
- // Test for method double java.lang.Math.sqrt(double)
- assertEquals("Incorrect root returned2", 7, Math.sqrt(49), 0);
- assertEquals("Incorrect value is returned", Double.NaN,
- Math.sqrt(Double.NaN));
- assertEquals("Incorrect value is returned", Double.NaN,
- Math.sqrt(-1));
- assertEquals("Incorrect value is returned", Double.POSITIVE_INFINITY,
- Math.sqrt(Double.POSITIVE_INFINITY));
- assertEquals("Incorrect value is returned", 0.0, Math.sqrt(0.0));
- assertEquals("Incorrect value is returned", -0.0, Math.sqrt(-0.0));
- }
-
- /**
- * @tests java.lang.Math#tan(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "tan",
- args = {double.class}
- )
- public void test_tanD() {
- // Test for method double java.lang.Math.tan(double)
- assertEquals("Incorrect answer", 0.0, Math.tan(0), 0D);
- assertEquals("Incorrect answer", 1.5574077246549023, Math.tan(1), 0D);
-
- double [] args = {Double.NaN, Double.POSITIVE_INFINITY,
- Double.NEGATIVE_INFINITY};
- for(int i = 0; i < args.length; i++) {
- assertEquals("Incorrest returned value.", Double.NaN,
- Math.tan(args[i]));
- }
-
- assertEquals("Incorrest returned value.", 0.0, Math.tan(0.0));
- assertEquals("Incorrest returned value.", -0.0, Math.tan(-0.0));
- }
-
- /**
- * @tests java.lang.Math#tanh(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "tanh",
- args = {double.class}
- )
- public void test_tanh_D() {
- // Test for special situations
- assertTrue("Should return NaN", Double.isNaN(Math.tanh(Double.NaN)));
- assertEquals("Should return +1.0", +1.0, Math
- .tanh(Double.POSITIVE_INFINITY), 0D);
- assertEquals("Should return -1.0", -1.0, Math
- .tanh(Double.NEGATIVE_INFINITY), 0D);
- assertEquals(Double.doubleToLongBits(0.0), Double.doubleToLongBits(Math
- .tanh(0.0)));
- assertEquals(Double.doubleToLongBits(+0.0), Double
- .doubleToLongBits(Math.tanh(+0.0)));
- assertEquals(Double.doubleToLongBits(-0.0), Double
- .doubleToLongBits(Math.tanh(-0.0)));
-
- assertEquals("Should return 1.0", 1.0, Math.tanh(1234.56), 0D);
- assertEquals("Should return -1.0", -1.0, Math.tanh(-1234.56), 0D);
- assertEquals("Should return 9.999999999996666E-7",
- 9.999999999996666E-7, Math.tanh(0.000001), 0D);
- assertEquals("Should return 0.981422884124941", 0.981422884124941, Math
- .tanh(2.33482), 0D);
- assertEquals("Should return 1.0", 1.0, Math.tanh(Double.MAX_VALUE), 0D);
- assertEquals("Should return 4.9E-324", 4.9E-324, Math
- .tanh(Double.MIN_VALUE), 0D);
- }
-
- /**
- * @tests java.lang.Math#random()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "random",
- args = {}
- )
- public void test_random() {
- // There isn't a place for these tests so just stick them here
- assertEquals("Wrong value E",
- 4613303445314885481L, Double.doubleToLongBits(Math.E));
- assertEquals("Wrong value PI",
- 4614256656552045848L, Double.doubleToLongBits(Math.PI));
-
- for (int i = 500; i >= 0; i--) {
- double d = Math.random();
- assertTrue("Generated number is out of range: " + d, d >= 0.0
- && d < 1.0);
- }
- }
-
- /**
- * @tests java.lang.Math#toRadians(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toRadians",
- args = {double.class}
- )
- public void test_toRadiansD() {
- for (double d = 500; d >= 0; d -= 1.0) {
- double converted = Math.toDegrees(Math.toRadians(d));
- assertTrue("Converted number not equal to original. d = " + d,
- converted >= d * 0.99999999 && converted <= d * 1.00000001);
- }
- }
-
- /**
- * @tests java.lang.Math#toDegrees(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toDegrees",
- args = {double.class}
- )
- public void test_toDegreesD() {
- for (double d = 500; d >= 0; d -= 1.0) {
- double converted = Math.toRadians(Math.toDegrees(d));
- assertTrue("Converted number not equal to original. d = " + d,
- converted >= d * 0.99999999 && converted <= d * 1.00000001);
- }
- }
-
- /**
- * @tests java.lang.Math#ulp(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ulp",
- args = {double.class}
- )
- @SuppressWarnings("boxing")
- public void test_ulp_D() {
- // Test for special cases
- assertTrue("Should return NaN", Double.isNaN(Math.ulp(Double.NaN)));
- assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, Math
- .ulp(Double.POSITIVE_INFINITY), 0D);
- assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY, Math
- .ulp(Double.NEGATIVE_INFINITY), 0D);
- assertEquals("Returned incorrect value", Double.MIN_VALUE, Math
- .ulp(0.0), 0D);
- assertEquals("Returned incorrect value", Double.MIN_VALUE, Math
- .ulp(+0.0), 0D);
- assertEquals("Returned incorrect value", Double.MIN_VALUE, Math
- .ulp(-0.0), 0D);
- assertEquals("Returned incorrect value", Math.pow(2, 971), Math
- .ulp(Double.MAX_VALUE), 0D);
- assertEquals("Returned incorrect value", Math.pow(2, 971), Math
- .ulp(-Double.MAX_VALUE), 0D);
-
- assertEquals("Returned incorrect value", Double.MIN_VALUE, Math
- .ulp(Double.MIN_VALUE), 0D);
- assertEquals("Returned incorrect value", Double.MIN_VALUE, Math
- .ulp(-Double.MIN_VALUE), 0D);
-
- assertEquals("Returned incorrect value", 2.220446049250313E-16, Math
- .ulp(1.0), 0D);
- assertEquals("Returned incorrect value", 2.220446049250313E-16, Math
- .ulp(-1.0), 0D);
- assertEquals("Returned incorrect value", 2.2737367544323206E-13, Math
- .ulp(1153.0), 0D);
- }
-
- /**
- * @tests java.lang.Math#ulp(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ulp",
- args = {float.class}
- )
- @SuppressWarnings("boxing")
- public void test_ulp_f() {
- // Test for special cases
- assertTrue("Should return NaN", Float.isNaN(Math.ulp(Float.NaN)));
- assertEquals("Returned incorrect value", Float.POSITIVE_INFINITY, Math
- .ulp(Float.POSITIVE_INFINITY), 0f);
- assertEquals("Returned incorrect value", Float.POSITIVE_INFINITY, Math
- .ulp(Float.NEGATIVE_INFINITY), 0f);
- assertEquals("Returned incorrect value", Float.MIN_VALUE, Math
- .ulp(0.0f), 0f);
- assertEquals("Returned incorrect value", Float.MIN_VALUE, Math
- .ulp(+0.0f), 0f);
- assertEquals("Returned incorrect value", Float.MIN_VALUE, Math
- .ulp(-0.0f), 0f);
- assertEquals("Returned incorrect value", 2.028241E31f, Math
- .ulp(Float.MAX_VALUE), 0f);
- assertEquals("Returned incorrect value", 2.028241E31f, Math
- .ulp(-Float.MAX_VALUE), 0f);
-
- assertEquals("Returned incorrect value", 1.4E-45f, Math
- .ulp(Float.MIN_VALUE), 0f);
- assertEquals("Returned incorrect value", 1.4E-45f, Math
- .ulp(-Float.MIN_VALUE), 0f);
-
- assertEquals("Returned incorrect value", 1.1920929E-7f, Math.ulp(1.0f),
- 0f);
- assertEquals("Returned incorrect value", 1.1920929E-7f,
- Math.ulp(-1.0f), 0f);
- assertEquals("Returned incorrect value", 1.2207031E-4f, Math
- .ulp(1153.0f), 0f);
- assertEquals("Returned incorrect value", 5.6E-45f, Math
- .ulp(9.403954E-38f), 0f);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MockEnum.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MockEnum.java
deleted file mode 100644
index dac338a..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MockEnum.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/* 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.harmony.luni.tests.java.lang;
-
-import java.io.Serializable;
-
-class MockEnum implements Serializable {
- private static final long serialVersionUID = -1678507713086705252L;
-
- enum Sample {
- LARRY, MOE, CURLY
- }
-
- enum Sample2 {
- RED, BLUE, YELLO
- }
-
- String str;
-
- int i;
-
- Sample2 samEnum;
-
- Sample larry = Sample.LARRY;
-
- MockEnum() {
- str = "test";
- i = 99;
- samEnum = Sample2.BLUE;
- }
-
- public boolean equals(Object arg0) {
- if (!(arg0 instanceof MockEnum)) {
- return false;
- }
- MockEnum test = (MockEnum) arg0;
- if (str.equals(test.str) && i == test.i && samEnum == test.samEnum) {
- return true;
- }
- return false;
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MockEnum2.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MockEnum2.java
deleted file mode 100644
index 30134ee..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MockEnum2.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/* 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.harmony.luni.tests.java.lang;
-
-import java.io.Serializable;
-
-class MockEnum2 implements Serializable {
-
- private static final long serialVersionUID = -4812214670022262730L;
-
- enum Sample {
- LARRY, MOE, CURLY
- }
-
- enum Sample2 {
- RED, BLUE, YELLO
- }
-
- String str;
-
- int i;
-
- Sample samEnum;
-
- Sample larry = Sample.LARRY;
-
- String myStr = "LARRY";
-
- MockEnum2() {
- str = "test";
- i = 99;
- samEnum = larry;
- }
-
- public boolean equals(Object arg0) {
- if (!(arg0 instanceof MockEnum2)) {
- return false;
- }
- MockEnum2 test = (MockEnum2) arg0;
- if (str.equals(test.str) && i == test.i && samEnum == test.samEnum
- && myStr.equals(test.myStr)) {
- return true;
- }
- return false;
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MockSecurityManager.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MockSecurityManager.java
deleted file mode 100644
index 40ed14b..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MockSecurityManager.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package org.apache.harmony.luni.tests.java.lang;
-
-import java.io.FilePermission;
-import java.security.Permission;
-import java.security.SecurityPermission;
-import java.util.PropertyPermission;
-
-class MockSecurityManager extends SecurityManager {
-
- String deletedFile = "/";
- String readedFile = "/";
- String writedFile = "/";
-
- public void setInCheck(boolean inCheck) {
- super.inCheck = inCheck;
- }
-
- @Override
- public int classDepth(String name) {
- return super.classDepth(name);
- }
-
- @Override
- public int classLoaderDepth() {
- return super.classLoaderDepth();
- }
-
- @Override
- public void checkPermission(Permission perm) {
- if (perm.equals(new RuntimePermission("createSecurityManager")) ||
-// perm.equals(new AWTPermission("accessEventQueue")) ||
- perm.equals(new RuntimePermission("createClassLoader")) ||
- perm.equals(new FilePermission(deletedFile,"delete")) ||
- perm.equals(new FilePermission(readedFile,"read")) ||
- perm.equals(new PropertyPermission("*", "read,write")) ||
- perm.equals(new PropertyPermission("key", "read")) ||
- perm.equals(new SecurityPermission("getPolicy")) ||
-// perm.equals(new AWTPermission("accessClipboard")) ||
- perm.equals(new FilePermission(writedFile,"write"))) {
- throw
- new SecurityException("Unable to create Security Manager");
- }
- }
-
- @Override
- public ClassLoader currentClassLoader() {
- return super.currentClassLoader();
- }
-
- @Override
- public Class<?> currentLoadedClass() {
- return super.currentLoadedClass();
- }
-
- @Override
- public Class[] getClassContext() {
- return super.getClassContext();
- }
-
- @Override
- public boolean inClass(String name) {
- return super.inClass(name);
- }
-
- @Override
- public boolean inClassLoader() {
- return super.inClassLoader();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MutableSecurityManager.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MutableSecurityManager.java
deleted file mode 100644
index aeb1aa4..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/MutableSecurityManager.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/* 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.harmony.luni.tests.java.lang;
-
-import java.net.SocketPermission;
-import java.security.Permission;
-import java.security.PermissionCollection;
-import java.security.Permissions;
-
-class MutableSecurityManager extends SecurityManager {
-
- static final RuntimePermission SET_SECURITY_MANAGER = new RuntimePermission("setSecurityManager");
-
- private PermissionCollection enabled;
-
- private PermissionCollection denied;
-
- public boolean isCheckAcceptCalled = false;
- public boolean isCheckAccessThreadCalled = false;
- public boolean isCheckAccessThreadGroupCalled = false;
-
- public MutableSecurityManager() {
- super();
- this.enabled = new Permissions();
- }
-
- public MutableSecurityManager(Permission... permissions) {
- this();
- for (int i = 0; i < permissions.length; i++) {
- this.enabled.add(permissions[i]);
- }
- }
-
- void addPermission(Permission permission) {
- enabled.add(permission);
- }
-
- void clearPermissions() {
- enabled = new Permissions();
- }
-
- void denyPermission(Permission p) {
- if (denied == null) {
- denied = p.newPermissionCollection();
- }
- denied.add(p);
- }
-
- @Override
- public void checkPermission(Permission permission)
- {
- if (permission != null) {
- if (denied != null && denied.implies(permission)){
-
- throw new SecurityException("Denied " + permission);
- }
-
- if (enabled.implies(permission)) {
- return;
- }
- }
-
- super.checkPermission(permission);
- }
-
- @Override
- public void checkPermission(Permission permission, Object context)
- {
- if (permission != null) {
- if (denied != null && denied.implies(permission)){
-
- throw new SecurityException("Denied " + permission);
- }
-
- if (enabled.implies(permission)) {
- return;
- }
- }
-
- super.checkPermission(permission, context);
- }
-
- // @Override
- public void checkAccept(String host, int port) {
- isCheckAcceptCalled = true;
- super.checkAccept(host, port);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NegativeArraySizeExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NegativeArraySizeExceptionTest.java
deleted file mode 100644
index ef1c9a6..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NegativeArraySizeExceptionTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(NegativeArraySizeException.class)
-public class NegativeArraySizeExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.NegativeArraySizeException#NegativeArraySizeException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NegativeArraySizeException",
- args = {}
- )
- public void test_Constructor() {
- NegativeArraySizeException e = new NegativeArraySizeException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.NegativeArraySizeException#NegativeArraySizeException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NegativeArraySizeException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- NegativeArraySizeException e = new NegativeArraySizeException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoClassDefFoundErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoClassDefFoundErrorTest.java
deleted file mode 100644
index 9c76a56..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoClassDefFoundErrorTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(NoClassDefFoundError.class)
-public class NoClassDefFoundErrorTest extends TestCase {
-
- /**
- * @tests java.lang.NoClassDefFoundError#NoClassDefFoundError()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NoClassDefFoundError",
- args = {}
- )
- public void test_Constructor() {
- NoClassDefFoundError e = new NoClassDefFoundError();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.NoClassDefFoundError#NoClassDefFoundError(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NoClassDefFoundError",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- NoClassDefFoundError e = new NoClassDefFoundError("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchFieldErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchFieldErrorTest.java
deleted file mode 100644
index 0ca4f41..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchFieldErrorTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(NoSuchFieldError.class)
-public class NoSuchFieldErrorTest extends TestCase {
-
- /**
- * @tests java.lang.NoSuchFieldError#NoSuchFieldError()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NoSuchFieldError",
- args = {}
- )
- public void test_Constructor() {
- NoSuchFieldError e = new NoSuchFieldError();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.NoSuchFieldError#NoSuchFieldError(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NoSuchFieldError",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- NoSuchFieldError e = new NoSuchFieldError("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchFieldExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchFieldExceptionTest.java
deleted file mode 100644
index 135fdb5..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchFieldExceptionTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(NoSuchFieldException.class)
-public class NoSuchFieldExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.NoSuchFieldException#NoSuchFieldException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NoSuchFieldException",
- args = {}
- )
- public void test_Constructor() {
- NoSuchFieldException e = new NoSuchFieldException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.NoSuchFieldException#NoSuchFieldException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NoSuchFieldException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- NoSuchFieldException e = new NoSuchFieldException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchMethodErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchMethodErrorTest.java
deleted file mode 100644
index 5c8a462..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchMethodErrorTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(NoSuchMethodError.class)
-public class NoSuchMethodErrorTest extends TestCase {
-
- /**
- * @tests java.lang.NoSuchMethodError#NoSuchMethodError()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NoSuchMethodError",
- args = {}
- )
- public void test_Constructor() {
- NoSuchMethodError e = new NoSuchMethodError();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.NoSuchMethodError#NoSuchMethodError(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NoSuchMethodError",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- NoSuchMethodError e = new NoSuchMethodError("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchMethodExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchMethodExceptionTest.java
deleted file mode 100644
index 8e01984..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchMethodExceptionTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(NoSuchMethodException.class)
-public class NoSuchMethodExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.NoSuchMethodException#NoSuchMethodException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NoSuchMethodException",
- args = {}
- )
- public void test_Constructor() {
- NoSuchMethodException e = new NoSuchMethodException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.NoSuchMethodException#NoSuchMethodException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NoSuchMethodException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- NoSuchMethodException e = new NoSuchMethodException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NullPointerExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NullPointerExceptionTest.java
deleted file mode 100644
index f1c870d..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NullPointerExceptionTest.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(NullPointerException.class)
-public class NullPointerExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.NullPointerException#NullPointerException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NullPointerException",
- args = {}
- )
- public void test_Constructor() {
- NullPointerException e = new NullPointerException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.NullPointerException#NullPointerException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NullPointerException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- NullPointerException e = new NullPointerException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NumberFormatExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NumberFormatExceptionTest.java
deleted file mode 100644
index 579b0b9..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NumberFormatExceptionTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(NumberFormatException.class)
-public class NumberFormatExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.NumberFormatException#NumberFormatException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NumberFormatException",
- args = {}
- )
- public void test_Constructor() {
- NumberFormatException e = new NumberFormatException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.NumberFormatException#NumberFormatException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NumberFormatException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- NumberFormatException e = new NumberFormatException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NumberTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NumberTest.java
deleted file mode 100644
index d1caf92..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NumberTest.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(Number.class)
-public class NumberTest extends junit.framework.TestCase {
-
- class MockNumber extends Number {
-
- @Override
- public double doubleValue() {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- public float floatValue() {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- public int intValue() {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- public long longValue() {
- // TODO Auto-generated method stub
- return 0;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Number",
- args = {}
- )
- public void test_Number() {
- MockNumber number = new MockNumber();
- assertEquals(0, number.longValue());
- assertEquals(0, number.shortValue());
- }
-
- /**
- * @tests java.lang.Number#byteValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "byteValue",
- args = {}
- )
- public void test_byteValue() {
- int number = 1231243;
- assertTrue("Incorrect byte returned for: " + number,
- ((byte) new Integer(number).intValue()) == new Integer(number)
- .byteValue());
- number = 0;
- assertTrue("Incorrect byte returned for: " + number,
- ((byte) new Integer(number).intValue()) == new Integer(number)
- .byteValue());
- number = -1;
- assertTrue("Incorrect byte returned for: " + number,
- ((byte) new Integer(number).intValue()) == new Integer(number)
- .byteValue());
- number = -84109328;
- assertTrue("Incorrect byte returned for: " + number,
- ((byte) new Integer(number).intValue()) == new Integer(number)
- .byteValue());
- }
-
- /**
- * @tests java.lang.Number#shortValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "shortValue",
- args = {}
- )
- public void test_shortValue() {
- int number = 1231243;
- assertTrue("Incorrect byte returned for: " + number,
- ((short) new Integer(number).intValue()) == new Integer(number)
- .shortValue());
- number = 0;
- assertTrue("Incorrect byte returned for: " + number,
- ((short) new Integer(number).intValue()) == new Integer(number)
- .shortValue());
- number = -1;
- assertTrue("Incorrect byte returned for: " + number,
- ((short) new Integer(number).intValue()) == new Integer(number)
- .shortValue());
- number = -84109328;
- assertTrue("Incorrect byte returned for: " + number,
- ((short) new Integer(number).intValue()) == new Integer(number)
- .shortValue());
-
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ObjectTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ObjectTest.java
deleted file mode 100644
index 7580011..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ObjectTest.java
+++ /dev/null
@@ -1,671 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import java.util.Vector;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(Object.class)
-public class ObjectTest extends junit.framework.TestCase {
-
- public boolean isCalled = false;
- /**
- * Test objects.
- */
- Object obj1 = new Object();
-
- Object obj2 = new Object();
-
- /**
- * Generic state indicator.
- */
- int status = 0;
-
- int ready = 0;
- TestThread1 thr1;
- TestThread2 thr2;
-
- /**
- * @tests java.lang.Object#Object()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Object",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.lang.Object()
- assertNotNull("Constructor failed !!!", new Object());
- }
-
- /**
- * @tests java.lang.Object#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean java.lang.Object.equals(java.lang.Object)
- assertTrue("Same object should be equal", obj1.equals(obj1));
- assertTrue("Different objects should not be equal", !obj1.equals(obj2));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "finalize",
- args = {}
- )
-
- public void test_finalize() {
- isCalled = false;
- class TestObject extends Object {
-
- Vector<StringBuffer> v = new Vector<StringBuffer>();
- public void add() {
- v.add(new StringBuffer(10000));
- }
-
- protected void finalize() throws Throwable {
- isCalled = true;
- super.finalize();
- }
- }
-
- TestObject to = new TestObject();
-
- try {
- while(true) {
- to.add();
- }
- } catch(OutOfMemoryError oome) {
- //expected
- to = null;
- }
- System.gc();
- System.runFinalization();
- assertTrue(isCalled);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- MockCloneableObject mco = new MockCloneableObject();
- try {
- assertFalse(mco.equals(mco.clone()));
- assertEquals(mco.getClass(), mco.clone().getClass());
- } catch(CloneNotSupportedException cnse) {
- fail("CloneNotSupportedException was thrown.");
- }
-
- MockObject mo = new MockObject();
- try {
- mo.clone();
- fail("CloneNotSupportedException was not thrown.");
- } catch(CloneNotSupportedException cnse) {
- //expected
- }
- }
- class MockCloneableObject extends Object implements Cloneable {
- public Object clone() throws CloneNotSupportedException {
- return super.clone();
- }
- }
-
- class MockObject extends Object {
-
- boolean isCalled = false;
-
- public void finalize() throws Throwable {
- super.finalize();
- isCalled = true;
- }
-
- public Object clone() throws CloneNotSupportedException {
- return super.clone();
- }
- }
-
- /**
- * @tests java.lang.Object#getClass()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getClass",
- args = {}
- )
- public void test_getClass() {
- // Test for method java.lang.Class java.lang.Object.getClass()
- String classNames[] = { "java.lang.Object", "java.lang.Throwable",
- "java.lang.StringBuffer" };
- Class<?> classToTest = null;
- Object instanceToTest = null;
-
- status = 0;
- for (int i = 0; i < classNames.length; ++i) {
- try {
- classToTest = Class.forName(classNames[i]);
- instanceToTest = classToTest.newInstance();
- assertTrue("Instance didn't match creator class.",
- instanceToTest.getClass() == classToTest);
- assertTrue("Instance didn't match class with matching name.",
- instanceToTest.getClass() == Class
- .forName(classNames[i]));
- } catch (Exception ex) {
- fail("Unexpected exception : " + ex.getMessage());
- }
- }
- }
-
- /**
- * @tests java.lang.Object#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- // Test for method int java.lang.Object.hashCode()
- assertTrue("Same object should have same hash.",
- obj1.hashCode() == obj1.hashCode());
- assertTrue("Same object should have same hash.",
- obj2.hashCode() == obj2.hashCode());
- }
-
- /**
- * @tests java.lang.Object#notify()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "notify",
- args = {}
- )
- public void test_notify() {
- // Test for method void java.lang.Object.notify()
-
- // Inner class to run test thread.
- class TestThread implements Runnable {
- public void run() {
- synchronized (obj1) {
- try {
- ready += 1;
- obj1.wait();// Wait for ever.
- status += 1;
- } catch (InterruptedException ex) {
- status = -1000;
- }
- }
- }
- }
- ;
-
- // Start of test code.
-
- // Warning:
- // This code relies on each thread getting serviced within
- // 200 mSec of when it is notified. Although this
- // seems reasonable, it could lead to false-failures.
-
- ready = 0;
- status = 0;
- final int readyWaitSecs = 3;
-
- final int threadCount = 20;
- for (int i = 0; i < threadCount; ++i) {
- new Thread(new TestThread()).start();
- }
- synchronized (obj1) {
- try {
-
- // Wait up to readyWaitSeconds for all threads to be waiting on
- // monitor
- for (int i = 0; i < readyWaitSecs; i++) {
- obj1.wait(1000, 0);
- if (ready == threadCount) {
- break;
- }
- }
-
- // Check pre-conditions of testing notifyAll
- assertTrue("Not all launched threads are waiting. (ready = "
- + ready + ")", ready == threadCount);
- assertTrue("Thread woke too early. (status = " + status + ")",
- status == 0);
-
- for (int i = 1; i <= threadCount; ++i) {
- obj1.notify();
- obj1.wait(200, 0);
- assertTrue("Out of sync. (expected " + i + " but got "
- + status + ")", status == i);
- }
-
- } catch (InterruptedException ex) {
- fail(
- "Unexpectedly got an InterruptedException. (status = "
- + status + ")");
- }
- }
-
- try {
- Object obj = new Object();
- obj.notify();
- fail("IllegalMonitorStateException was not thrown.");
- } catch(IllegalMonitorStateException imse) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.Object#notifyAll()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "notifyAll",
- args = {}
- )
- public void test_notifyAll() {
- // Test for method void java.lang.Object.notifyAll()
-
- // Inner class to run test thread.
- class TestThread implements Runnable {
- public void run() {
- synchronized (obj1) {
- try {
- ready += 1;
- obj1.wait();// Wait for ever.
- status += 1;
- } catch (InterruptedException ex) {
- status = -1000;
- }
- }
- }
- }
- ;
-
- // Start of test code.
-
- // Warning:
- // This code relies on all threads getting serviced within
- // 5 seconds of when they are notified. Although this
- // seems reasonable, it could lead to false-failures.
-
- status = 0;
- ready = 0;
- final int readyWaitSecs = 3;
- final int threadCount = 20;
- for (int i = 0; i < threadCount; ++i) {
- new Thread(new TestThread()).start();
- }
-
- synchronized (obj1) {
-
- try {
-
- // Wait up to readyWaitSeconds for all threads to be waiting on
- // monitor
- for (int i = 0; i < readyWaitSecs; i++) {
- obj1.wait(1000, 0);
- if (ready == threadCount) {
- break;
- }
- }
-
- // Check pre-conditions of testing notifyAll
- assertTrue("Not all launched threads are waiting. (ready = "
- + ready + ")", ready == threadCount);
- assertTrue("At least one thread woke too early. (status = "
- + status + ")", status == 0);
-
- obj1.notifyAll();
-
- obj1.wait(5000, 0);
-
- assertTrue(
- "At least one thread did not get notified. (status = "
- + status + ")", status == threadCount);
-
- } catch (InterruptedException ex) {
- fail(
- "Unexpectedly got an InterruptedException. (status = "
- + status + ")");
- }
-
- }
-
- try {
- Object obj = new Object();
- obj.notifyAll();
- fail("IllegalMonitorStateException was not thrown.");
- } catch(IllegalMonitorStateException imse) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.Object#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.lang.Object.toString()
- assertNotNull("Object toString returned null.", obj1.toString());
- }
-
- /**
- * @tests java.lang.Object#wait()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "wait",
- args = {}
- )
- public void test_wait() {
- // Test for method void java.lang.Object.wait()
-
- // Inner class to run test thread.
- class TestThread implements Runnable {
- public void run() {
- synchronized (obj1) {
- try {
- obj1.wait();// Wait for ever.
- status = 1;
- } catch (InterruptedException ex) {
- status = -1;
- }
- }
- }
- }
-
-
- // Start of test code.
-
- // Warning:
- // This code relies on threads getting serviced within
- // 1 second of when they are notified. Although this
- // seems reasonable, it could lead to false-failures.
-
- status = 0;
- new Thread(new TestThread()).start();
- synchronized (obj1) {
- try {
- obj1.wait(1000, 0);
- assertTrue("Thread woke too early. (status = " + status + ")",
- status == 0);
- obj1.notifyAll();
- obj1.wait(1000, 0);
- assertTrue("Thread did not get notified. (status = " + status
- + ")", status == 1);
- } catch (InterruptedException ex) {
- fail(
- "Unexpectedly got an InterruptedException. (status = "
- + status + ")");
- }
- }
-
- try {
- Object obj = new Object();
- obj.wait();
- fail("IllegalMonitorStateException was not thrown.");
- } catch(IllegalMonitorStateException imse) {
- //expected
- } catch(InterruptedException ex) {
- fail("InterruptedException was thrown.");
- }
-
- try {
- thr1 = new TestThread1(TestThread1.CASE_WAIT);
- thr2 = new TestThread2();
- thr1.start();
- thr2.start();
- thr2.join();
- thr1.join();
- thr1 = null;
- thr2 = null;
- } catch(InterruptedException e) {
- fail("InterruptedException was thrown.");
- }
- assertEquals(3, status);
- }
-
- class TestThread1 extends Thread {
-
- static final int CASE_WAIT = 0;
- static final int CASE_WAIT_LONG = 1;
- static final int CASE_WAIT_LONG_INT = 2;
-
- int testCase = CASE_WAIT;
-
- public TestThread1(int option) {
- testCase = option;
- }
-
- public void run() {
- synchronized (obj1) {
- try {
- switch(testCase) {
- case CASE_WAIT:
- obj1.wait();// Wait for ever.
- break;
- case CASE_WAIT_LONG:
- obj1.wait(5000L);
- break;
- case CASE_WAIT_LONG_INT:
- obj1.wait(10000L, 999999);
- break;
- }
-
- } catch (InterruptedException ex) {
- status = 3;
- }
- }
- }
- }
-
- class TestThread2 extends Thread {
- public void run() {
- thr1.interrupt();
- }
- }
-
- /**
- * @tests java.lang.Object#wait(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "wait",
- args = {long.class}
- )
- public void test_waitJ() {
- // Test for method void java.lang.Object.wait(long)
-
- // Start of test code.
-
- final int loopCount = 20;
- final int allowableError = 100; // millesconds
- final int delay = 200; // milliseconds
- synchronized (obj1) {
- try {
- int count = 0;
- long[][] toLong = new long[3][3];
- for (int i = 0; i < loopCount; ++i) {
- long before = System.currentTimeMillis();
- obj1.wait(delay, 0);
- long after = System.currentTimeMillis();
- long error = (after - before - delay);
- if (error < 0)
- error = -error;
- if (i > 0 && error > allowableError) {
- // Allow jit to warm up before testing
- if (count < toLong.length) {
- toLong[count][0] = i;
- toLong[count][1] = before;
- toLong[count][2] = after;
- count++;
- }
- if (error > (1000 + delay) || count == toLong.length) {
- StringBuffer sb = new StringBuffer();
- for (int j = 0; j < count; j++) {
- sb
- .append("wakeup time too inaccurate, iteration ");
- sb.append(toLong[j][0]);
- sb.append(", before: ");
- sb.append(toLong[j][1]);
- sb.append(" after: ");
- sb.append(toLong[j][2]);
- sb.append(" diff: ");
- sb.append(toLong[j][2] - toLong[j][1]);
- sb.append("\n");
- }
- fail(sb.toString());
- }
- }
- }
- } catch (InterruptedException ex) {
- fail(
- "Unexpectedly got an InterruptedException. (status = "
- + status + ")");
- }
- }
-
- try {
- Object obj = new Object();
- obj.wait(5000L);
- fail("IllegalMonitorStateException was not thrown.");
- } catch(IllegalMonitorStateException imse) {
- //expected
- } catch(InterruptedException ex) {
- fail("InterruptedException was thrown.");
- }
-
- try {
- thr1 = new TestThread1(TestThread1.CASE_WAIT_LONG);
- thr2 = new TestThread2();
- thr1.start();
- thr2.start();
- thr2.join();
- thr1.join();
- thr1 = null;
- thr2 = null;
- } catch(InterruptedException e) {
- fail("InterruptedException was thrown.");
- }
- assertEquals(3, status);
- }
-
- /**
- * @tests java.lang.Object#wait(long, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "wait",
- args = {long.class, int.class}
- )
- public void test_waitJI() {
- // Test for method void java.lang.Object.wait(long, int)
-
- // Inner class to run test thread.
- class TestThread implements Runnable {
- public void run() {
- synchronized (obj1) {
- try {
- obj1.wait(0, 1); // Don't wait very long.
- status = 1;
- obj1.wait(0, 0); // Wait for ever.
- status = 2;
- } catch (InterruptedException ex) {
- status = -1;
- }
- }
- }
- }
-
-
- // Start of test code.
-
- // Warning:
- // This code relies on threads getting serviced within
- // 1 second of when they are notified. Although this
- // seems reasonable, it could lead to false-failures.
-
- status = 0;
- new Thread(new TestThread()).start();
- synchronized (obj1) {
- try {
- obj1.wait(1000, 0);
- assertTrue("Thread did not wake after 1 ms. (status = "
- + status + ")", status == 1);
- obj1.notifyAll();
- obj1.wait(1000, 0);
- assertTrue("Thread did not get notified. (status = " + status
- + ")", status == 2);
- } catch (InterruptedException ex) {
- fail(
- "Unexpectedly got an InterruptedException. (status = "
- + status + ")");
- }
- }
-
- try {
- Object obj = new Object();
- obj.wait(5000L, 1);
- fail("IllegalMonitorStateException was not thrown.");
- } catch(IllegalMonitorStateException imse) {
- //expected
- } catch(InterruptedException ex) {
- fail("InterruptedException was thrown.");
- }
-
- try {
- thr1 = new TestThread1(TestThread1.CASE_WAIT_LONG_INT);
- thr2 = new TestThread2();
- thr1.start();
- thr2.start();
- thr2.join();
- thr1.join();
- thr1 = null;
- thr2 = null;
- } catch(InterruptedException e) {
- fail("InterruptedException was thrown.");
- }
- assertEquals(3, status);
-
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/OutOfMemoryErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/OutOfMemoryErrorTest.java
deleted file mode 100644
index 4782f1e..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/OutOfMemoryErrorTest.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(OutOfMemoryError.class)
-public class OutOfMemoryErrorTest extends junit.framework.TestCase {
-
- /**
- * @tests java.lang.OutOfMemoryError#OutOfMemoryError()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "OutOfMemoryError",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.lang.OutOfMemoryError()
- Error e = new OutOfMemoryError();
- assertNull(e.getCause());
- assertNull(e.getMessage());
- }
-
- /**
- * @tests java.lang.OutOfMemoryError#OutOfMemoryError(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "OutOfMemoryError",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.lang.OutOfMemoryError(java.lang.String)
- Error e = new OutOfMemoryError(null);
- assertNull(e.getMessage());
- assertNull(e.getCause());
-
- e= new OutOfMemoryError("msg");
- assertEquals("msg", e.getMessage());
- assertNull(e.getCause());
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/PackageTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/PackageTest.java
deleted file mode 100644
index e38ee63..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/PackageTest.java
+++ /dev/null
@@ -1,495 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.File;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.lang.annotation.Annotation;
-
-import java.lang.annotation.Annotation;
-
-import tests.support.resource.Support_Resources;
-
-@TestTargetClass(Package.class)
-public class PackageTest extends junit.framework.TestCase {
-
- private File resources;
-
- private String resPath;
-
- Class clazz;
-
- // URLClassLoader doesn't load classes from jar.
- // use PathClassLoader
- boolean USE_PATH_CLASS_LOADER = true;
-
- Package getTestPackage(String resourceJar, String className)
- throws Exception {
-
- if (USE_PATH_CLASS_LOADER) {
- resourceJar = resourceJar.substring(0, resourceJar.indexOf(".")) +
- "_dex.jar";
- }
- Support_Resources.copyFile(resources, "Package", resourceJar);
- URL resourceURL = new URL("file:/" + resPath + "/Package/"
- + resourceJar);
-
- ClassLoader cl = null;
- if(USE_PATH_CLASS_LOADER) {
- cl = new dalvik.system.PathClassLoader(
- resourceURL.getPath(), getClass().getClassLoader());
- } else {
- cl = new URLClassLoader(new URL[] { resourceURL },
- getClass().getClassLoader());
- }
- clazz = cl.loadClass(className);
- return clazz.getPackage();
- }
-
- @Override
- protected void setUp() {
- resources = Support_Resources.createTempFolder();
- resPath = resources.toString();
- if (resPath.charAt(0) == '/' || resPath.charAt(0) == '\\')
- resPath = resPath.substring(1);
- }
-
- /**
- * There is a newer version of this class with some actual tests but since
- * the class is not implemented they all fail. For now use the stub test
- * methods.
- */
-
- /**
- * @tests java.lang.Package#getImplementationVendor()
- * @tests java.lang.Package#getImplementationVersion()
- * @tests java.lang.Package#getSpecificationTitle()
- * @tests java.lang.Package#getSpecificationVendor()
- * @tests java.lang.Package#getSpecificationVersion()
- * @tests java.lang.Package#getImplementationTitle()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getImplementationTitle",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getImplementationVendor",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getImplementationVersion",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSpecificationTitle",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSpecificationVendor",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSpecificationVersion",
- args = {}
- )
- })
- @KnownFailure("get methods don't work.")
- public void test_helper_Attributes() throws Exception {
-
- Package p = getTestPackage("hyts_all_attributes.jar", "p.C");
- assertEquals(
- "Package getImplementationTitle returns a wrong string (1)",
- "p Implementation-Title", p.getImplementationTitle());
- assertEquals(
- "Package getImplementationVendor returns a wrong string (1)",
- "p Implementation-Vendor", p.getImplementationVendor());
- assertEquals(
- "Package getImplementationVersion returns a wrong string (1)",
- "2.2.2", p.getImplementationVersion());
- assertEquals(
- "Package getSpecificationTitle returns a wrong string (1)",
- "p Specification-Title", p.getSpecificationTitle());
- assertEquals(
- "Package getSpecificationVendor returns a wrong string (1)",
- "p Specification-Vendor", p.getSpecificationVendor());
- assertEquals(
- "Package getSpecificationVersion returns a wrong string (1)",
- "2.2.2", p.getSpecificationVersion());
-
- // No entry for the package
- Package p2 = getTestPackage("hyts_no_entry.jar", "p.C");
- assertEquals(
- "Package getImplementationTitle returns a wrong string (2)",
- "MF Implementation-Title", p2.getImplementationTitle());
- assertEquals(
- "Package getImplementationVendor returns a wrong string (2)",
- "MF Implementation-Vendor", p2.getImplementationVendor());
- assertEquals(
- "Package getImplementationVersion returns a wrong string (2)",
- "5.3.b1", p2.getImplementationVersion());
- assertEquals(
- "Package getSpecificationTitle returns a wrong string (2)",
- "MF Specification-Title", p2.getSpecificationTitle());
- assertEquals(
- "Package getSpecificationVendor returns a wrong string (2)",
- "MF Specification-Vendor", p2.getSpecificationVendor());
- assertEquals(
- "Package getSpecificationVersion returns a wrong string (2)",
- "1.2.3", p2.getSpecificationVersion());
-
- // No attributes in the package entry
- Package p3 = getTestPackage("hyts_no_attributes.jar", "p.C");
- assertEquals(
- "Package getImplementationTitle returns a wrong string (3)",
- "MF Implementation-Title", p3.getImplementationTitle());
- assertEquals(
- "Package getImplementationVendor returns a wrong string (3)",
- "MF Implementation-Vendor", p3.getImplementationVendor());
- assertEquals(
- "Package getImplementationVersion returns a wrong string (3)",
- "5.3.b1", p3.getImplementationVersion());
- assertEquals(
- "Package getSpecificationTitle returns a wrong string (3)",
- "MF Specification-Title", p3.getSpecificationTitle());
- assertEquals(
- "Package getSpecificationVendor returns a wrong string (3)",
- "MF Specification-Vendor", p3.getSpecificationVendor());
- assertEquals(
- "Package getSpecificationVersion returns a wrong string (3)",
- "1.2.3", p3.getSpecificationVersion());
-
- // Some attributes in the package entry
- Package p4 = getTestPackage("hyts_some_attributes.jar", "p.C");
- assertEquals(
- "Package getImplementationTitle returns a wrong string (4)",
- "p Implementation-Title", p4.getImplementationTitle());
- assertEquals(
- "Package getImplementationVendor returns a wrong string (4)",
- "MF Implementation-Vendor", p4.getImplementationVendor());
- assertEquals(
- "Package getImplementationVersion returns a wrong string (4)",
- "2.2.2", p4.getImplementationVersion());
- assertEquals(
- "Package getSpecificationTitle returns a wrong string (4)",
- "MF Specification-Title", p4.getSpecificationTitle());
- assertEquals(
- "Package getSpecificationVendor returns a wrong string (4)",
- "p Specification-Vendor", p4.getSpecificationVendor());
- assertEquals(
- "Package getSpecificationVersion returns a wrong string (4)",
- "2.2.2", p4.getSpecificationVersion());
-
- // subdirectory Package
- Package p5 = getTestPackage("hyts_pq.jar", "p.q.C");
- assertEquals(
- "Package getImplementationTitle returns a wrong string (5)",
- "p Implementation-Title", p5.getImplementationTitle());
- assertEquals(
- "Package getImplementationVendor returns a wrong string (5)",
- "p Implementation-Vendor", p5.getImplementationVendor());
- assertEquals(
- "Package getImplementationVersion returns a wrong string (5)",
- "1.1.3", p5.getImplementationVersion());
- assertEquals(
- "Package getSpecificationTitle returns a wrong string (5)",
- "p Specification-Title", p5.getSpecificationTitle());
- assertEquals(
- "Package getSpecificationVendor returns a wrong string (5)",
- "p Specification-Vendor", p5.getSpecificationVendor());
- assertEquals(
- "Package getSpecificationVersion returns a wrong string (5)",
- "2.2.0.0.0.0.0.0.0.0.0", p5.getSpecificationVersion());
- }
-
- /**
- * @tests java.lang.Package#getName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getName",
- args = {}
- )
- public void test_getName() throws Exception {
- Package p = getTestPackage("hyts_pq.jar", "p.q.C");
- assertEquals("Package getName returns a wrong string", "p.q", p
- .getName());
- }
-
- /**
- * @tests java.lang.Package#getPackage(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPackage",
- args = {java.lang.String.class}
- )
- @KnownFailure("Package information missing on android")
- public void test_getPackageLjava_lang_String() throws Exception {
- assertSame("Package getPackage failed for java.lang", Package
- .getPackage("java.lang"), Package.getPackage("java.lang"));
-
- assertSame("Package getPackage failed for java.lang", Package
- .getPackage("java.lang"), Object.class.getPackage());
-
- Package p = getTestPackage("hyts_package.jar", "C");
- assertNull("getPackage should return null.", p);
- }
-
- /**
- * @tests java.lang.Package#getPackages()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPackages",
- args = {}
- )
- @KnownFailure("Package information missing on android")
- public void test_getPackages() throws Exception {
- Package[] pckgs = Package.getPackages();
- boolean found = false;
- for (int i = 0; i < pckgs.length; i++) {
- if (pckgs[i].getName().equals("java.util")) {
- found = true;
- break;
- }
- }
- assertTrue("Package getPackages failed to retrieve a package", found);
- }
-
- /**
- * @tests java.lang.Package#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- @KnownFailure("Package information missing on android")
- public void test_hashCode() {
- Package p1 = Package.getPackage("java.lang");
- if (p1 != null) {
- assertEquals(p1.hashCode(), "java.lang".hashCode());
- }
- }
-
- /**
- * @tests java.lang.Package#isCompatibleWith(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isCompatibleWith",
- args = {java.lang.String.class}
- )
- @KnownFailure("isCompatibleWith returns incorrect value.")
- public void test_isCompatibleWithLjava_lang_String() throws Exception {
- Package p = getTestPackage("hyts_c.jar", "p.C");
-
- assertTrue("Package isCompatibleWith fails with lower version", p
- .isCompatibleWith("2.1.9.9"));
- assertTrue("Package isCompatibleWith fails with same version (1)", p
- .isCompatibleWith("2.2.0"));
- assertTrue("Package isCompatibleWith fails with same version (2)", p
- .isCompatibleWith("2.2"));
- assertFalse("Package isCompatibleWith fails with higher version", p
- .isCompatibleWith("2.2.0.0.1"));
- try {
- p.isCompatibleWith(null);
- fail("Null version is illegal");
- } catch (NumberFormatException ok) {
- } catch (NullPointerException compatible) {
- /*
- * RI throws NPE instead of NFE...
- */
- }
-
- try {
- p.isCompatibleWith("");
- fail("Empty version is illegal");
- } catch (NumberFormatException ok) {}
- try {
- p.isCompatibleWith(".");
- fail("'.' version is illegal");
- } catch (NumberFormatException ok) {}
- try {
- p.isCompatibleWith("1.2.");
- fail("'1.2.' version is illegal");
- } catch (NumberFormatException ok) {}
- try {
- p.isCompatibleWith(".9");
- fail("'.9' version is illegal");
- } catch (NumberFormatException ok) {}
- try {
- p.isCompatibleWith("2.4..5");
- fail("'2.4..5' version is illegal");
- } catch (NumberFormatException ok) {}
- try {
- p.isCompatibleWith("20.-4");
- fail("'20.-4' version is illegal");
- } catch (NumberFormatException ok) {}
- }
-
- /**
- * @tests java.lang.Package#isSealed()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isSealed",
- args = {}
- )
- @KnownFailure("isSealed method returns false for sealed package.")
- public void test_isSealed() throws Exception {
- Package p = getTestPackage("hyts_pq.jar", "p.q.C");
- assertTrue("Package isSealed returns wrong boolean", p.isSealed());
-
- p = String.class.getPackage();
- assertFalse("Package isSealed returns wrong boolean", p.isSealed());
- }
-
- /**
- * @tests java.lang.Package#isSealed(java.net.URL)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isSealed",
- args = {java.net.URL.class}
- )
- @KnownFailure("isSealed method returns false for sealed package.")
- public void test_isSealedLjava_net_URL() throws Exception {
- Package p = getTestPackage("hyts_c.jar", "p.C");
- assertFalse("Package isSealed returns wrong boolean (1)", p
- .isSealed(new URL("file:/" + resPath + "/")));
- assertTrue("Package isSealed returns wrong boolean (2)", p
- .isSealed(new URL("file:/" + resPath + "/Package/hyts_c.jar")));
- }
-
- /**
- * @tests java.lang.Package#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() throws Exception {
- Package p = getTestPackage("hyts_c.jar", "p.C");
- assertTrue("Package toString returns wrong string", p.toString()
- .length() > 0);
- }
-
- @SuppressWarnings("unchecked")
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAnnotation",
- args = {java.lang.Class.class}
- )
- @KnownFailure("Class loader can't retrieve information about annotations.")
- public void test_getAnnotation() throws Exception {
- String annotationName = "a.b.PackageAnnotation";
- Package p = getTestPackage("hyts_package.jar", annotationName);
- assertEquals(annotationName,
- p.getAnnotation(clazz).annotationType().getName());
- assertNull(String.class.getPackage().getAnnotation(Deprecated.class));
- assertNull(ExtendTestClass.class.getPackage().
- getAnnotation(Deprecated.class));
- }
-
- @SuppressWarnings("unchecked")
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAnnotations",
- args = {}
- )
- @KnownFailure("Class loader can't retrieve information about annotations.")
- public void test_getAnnotations() throws Exception {
- String annotationName = "a.b.PackageAnnotation";
- Package p = getTestPackage("hyts_package.jar", annotationName);
-
- Annotation [] annotations = p.getAnnotations();
- assertEquals(1, annotations.length);
-
- p = String.class.getPackage();
- assertEquals(0, p.getAnnotations().length);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaredAnnotations",
- args = {}
- )
- @KnownFailure("Class loader can't retrieve information about annotations.")
- public void test_getDeclaredAnnotations() throws Exception {
- String annotationName = "a.b.PackageAnnotation";
- Package p = getTestPackage("hyts_package.jar", annotationName);
-
- Annotation [] annotations = p.getDeclaredAnnotations();
- assertEquals(1, annotations.length);
-
- p = String.class.getPackage();
- assertEquals(0, p.getDeclaredAnnotations().length);
- }
-
- @SuppressWarnings("unchecked")
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isAnnotationPresent",
- args = {java.lang.Class.class}
- )
- @KnownFailure("Class loader can't retrieve information about annotations.")
- public void test_isAnnotationPresent() throws Exception {
- String annotationName = "a.b.PackageAnnotation";
- Package p = getTestPackage("hyts_package.jar", annotationName);
-
- assertTrue(p.isAnnotationPresent(clazz));
- assertFalse(p.isAnnotationPresent(Deprecated.class));
-
- p = String.class.getPackage();
- assertFalse(p.isAnnotationPresent(clazz));
- assertFalse(p.isAnnotationPresent(Deprecated.class));
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ProcessBuilderTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ProcessBuilderTest.java
deleted file mode 100644
index 7894578..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ProcessBuilderTest.java
+++ /dev/null
@@ -1,279 +0,0 @@
-/* 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.File;
-import java.io.FilePermission;
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.Permission;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-
-@TestTargetClass(ProcessBuilder.class)
-public class ProcessBuilderTest extends TestCase {
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ProcessBuilder",
- args = {java.lang.String[].class}
- )
- public void testProcessBuilderStringArray() {
-
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ProcessBuilder",
- args = {java.util.List.class}
- )
- public void testProcessBuilderListOfString() {
- List<String> list = Arrays.asList("command1", "command2", "command3");
- ProcessBuilder pb = new ProcessBuilder(list);
- assertEquals(list, pb.command());
-
- try {
- new ProcessBuilder((List<String>) null);
- fail("no null pointer exception");
- } catch (NullPointerException e) {
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "command",
- args = {}
- )
- public void testCommand() {
- ProcessBuilder pb = new ProcessBuilder("command");
- assertEquals(1, pb.command().size());
- assertEquals("command", pb.command().get(0));
-
- // Regression for HARMONY-2675
- pb = new ProcessBuilder("AAA");
- pb.command("BBB","CCC");
- List<String> list = pb.command();
- list.add("DDD");
- String[] command = new String[3];
- list.toArray(command);
- assertTrue(Arrays.equals(new String[]{"BBB","CCC","DDD"}, command));
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "command",
- args = {java.lang.String[].class}
- )
- public void testCommandStringArray() {
- ProcessBuilder pb = new ProcessBuilder("command");
- ProcessBuilder pbReturn = pb.command("cmd");
- assertSame(pb, pbReturn);
- assertEquals(1, pb.command().size());
- assertEquals("cmd", pb.command().get(0));
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "command",
- args = {java.util.List.class}
- )
- public void testCommandListOfString() {
- ProcessBuilder pb = new ProcessBuilder("command");
- List<String> newCmd = new ArrayList<String>();
- newCmd.add("cmd");
- ProcessBuilder pbReturn = pb.command(newCmd);
- assertSame(pb, pbReturn);
- assertEquals(1, pb.command().size());
- assertEquals("cmd", pb.command().get(0));
-
- newCmd.add("arg");
- assertEquals(2, pb.command().size());
- assertEquals("cmd", pb.command().get(0));
- assertEquals("arg", pb.command().get(1));
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "directory",
- args = {}
- )
- public void testDirectory() {
- ProcessBuilder pb = new ProcessBuilder("command");
- assertNull(pb.directory());
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "directory",
- args = {java.io.File.class}
- )
- public void testDirectoryFile() {
- ProcessBuilder pb = new ProcessBuilder("command");
- File dir = new File(System.getProperty("java.io.tmpdir"));
- ProcessBuilder pbReturn = pb.directory(dir);
- assertSame(pb, pbReturn);
- assertEquals(dir, pb.directory());
-
- pbReturn = pb.directory(null);
- assertSame(pb, pbReturn);
- assertNull(pb.directory());
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "environment",
- args = {}
- )
- @AndroidOnly("SystemEnvironment.clear() method throws UnsupportedOperationException.")
- public void testEnvironment() {
- ProcessBuilder pb = new ProcessBuilder("command");
- Map<String, String> env = pb.environment();
- assertEquals(System.getenv().size(), env.size());
- try {
- env.clear();
- env = pb.environment();
- assertTrue(env.isEmpty());
- try {
- env.put(null,"");
- fail("should throw NPE.");
- } catch (NullPointerException e) {
- // expected;
- }
- try {
- env.put("",null);
- fail("should throw NPE.");
- } catch (NullPointerException e) {
- // expected;
- }
- try {
- env.get(null);
- fail("should throw NPE.");
- } catch (NullPointerException e) {
- // expected;
- }
- try {
- env.get(new Object());
- fail("should throw ClassCastException.");
- } catch (ClassCastException e) {
- // expected;
- }
- } catch(UnsupportedOperationException e) {
- //expected: Android specific
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "redirectErrorStream",
- args = {}
- )
- public void testRedirectErrorStream() {
- ProcessBuilder pb = new ProcessBuilder("command");
- assertFalse(pb.redirectErrorStream());
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Doesn't check false.",
- method = "redirectErrorStream",
- args = {boolean.class}
- )
- public void testRedirectErrorStreamBoolean() {
- ProcessBuilder pb = new ProcessBuilder("command");
- ProcessBuilder pbReturn = pb.redirectErrorStream(true);
- assertSame(pb, pbReturn);
- assertTrue(pb.redirectErrorStream());
- }
-
- /**
- * @throws IOException
- * @tests {@link java.lang.ProcessBuilder#start()}
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException is not checked.",
- method = "start",
- args = {}
- )
- @SuppressWarnings("nls")
- public void testStart() throws IOException {
- ProcessBuilder pb = new ProcessBuilder("java", "-version");
- pb.directory(new File(System.getProperty("java.home") + File.separator
- + "bin"));
-
- // Call the test target
- Process process = pb.start();
- InputStream in = process.getInputStream();
- InputStream err = process.getErrorStream();
- byte[] buf = new byte[1024];
- if (in.available() > 0) {
- assertTrue(in.read(buf) > 0);
- } else {
- assertTrue(err.read(buf) > 0);
- }
-
- List<String> list = Arrays.asList(null, null, null);
- ProcessBuilder pbn = new ProcessBuilder(list);
- try {
- pbn.start();
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- List<String> emptyList = Arrays.asList();
- ProcessBuilder pbe = new ProcessBuilder(emptyList);
- try {
- pbe.start();
- fail("IndexOutOfBoundsException is not thrown.");
- } catch(IndexOutOfBoundsException npe) {
- //expected
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkExec(String cmd) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- pb.start();
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- pb.directory(new File(System.getProperty("java.class.path")));
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/PublicClassLoader.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/PublicClassLoader.java
deleted file mode 100644
index bdad5b9..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/PublicClassLoader.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
- class PublicClassLoader extends ClassLoader {
-
- public PublicClassLoader() {
- super();
- }
-
- public PublicClassLoader(ClassLoader cl) {
- super(cl);
- }
-
- private byte[] getBytes( String filename ) throws IOException {
-
- File file = new File( filename );
- long len = file.length();
- byte raw[] = new byte[(int)len];
- FileInputStream fin = new FileInputStream( file );
- int r = fin.read( raw );
- if (r != len)
- throw new IOException( "Can't read all, "+r+" != "+len );
- fin.close();
- return raw;
- }
-
- public Class<?> loadClass(String name, boolean resolve)
- throws ClassNotFoundException {
-
- Class clazz = findLoadedClass(name);
- String classFileName = name.replace( '.', '/' ) + ".class";
- File classFile = new File(classFileName);
- if (classFile.exists()) {
- try {
- byte raw[] = getBytes(classFileName);
- clazz = defineClass( name, raw, 0, raw.length );
- } catch(Exception ioe) {}
- }
-
- if (clazz == null) {
- Package p = getClass().getPackage();
- InputStream is = getResourceAsStream("/" + classFileName);
- byte[] buf = new byte[512];
- int len;
- try {
- len = is.read(buf);
- clazz = defineClass(name, buf, 0, len);
- } catch (IOException e) {
- }
- }
-
- if (clazz == null) {
- clazz = findSystemClass(name);
- }
-
- if(clazz == null)
- throw new ClassNotFoundException(name);
- return clazz;
- }
-
- public Class<?> defineClassTest(byte[] b, int off, int len) {
- return defineClass(b, off, len);
- }
-
- public Package getPackage(String name) {
- return super.getPackage(name);
- }
-
- public Package [] getPackages() {
- return super.getPackages();
- }
-
- public InputStream getResourceAsStream(String name) {
- return getClass().getResourceAsStream("/" + getClass().getPackage().
- getName().replace(".", "/") + "/" + name);
- }
- }
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/PublicTestClass.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/PublicTestClass.java
deleted file mode 100644
index 98fd9a6..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/PublicTestClass.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-import java.io.Serializable;
-
-interface TestInterface {
-
- public static int TEST_INTERFACE_FIELD = 0;
-
- int getCount();
- void setCount(int value);
-}
-
-@TestAnnotation("org.apache.harmony.luni.tests.java.lang.PublicTestClass")
-public class PublicTestClass implements TestInterface, Serializable, Cloneable {
-
- private static final long serialVersionUID = 1L;
-
- public static String TEST_FIELD = "test field";
-
- Object clazz;
-
- public PublicTestClass() {
- class LocalClass { }
-
- clazz = new LocalClass();
- }
-
- public Object getLocalClass() {
- class LocalClass {}
- Object returnedObject = new LocalClass();
- return returnedObject;
- }
-
- int count = 0;
-
- public int getCount() {
- return count;
- }
-
- public void setCount(int value) {
- count = value;
- }
-
- private class PrivateClass1 {
-
- public String toString() {
- return "PrivateClass0";
- }
- }
-
- public class PrivateClass2 {
-
- public String toString() {
- return "PrivateClass1";
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimeExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimeExceptionTest.java
deleted file mode 100644
index c6540bf..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimeExceptionTest.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(RuntimeException.class)
-public class RuntimeExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.RuntimeException#RuntimeException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "RuntimeException",
- args = {}
- )
- public void test_Constructor() {
- RuntimeException e = new RuntimeException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.RuntimeException#RuntimeException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "RuntimeException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- RuntimeException e = new RuntimeException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "RuntimeException",
- args = {java.lang.String.class, java.lang.Throwable.class}
- )
- public void test_ConstructorLStringLThrowable() {
- String message = "Test message";
- NullPointerException npe = new NullPointerException();
- RuntimeException re = new RuntimeException(message, npe);
- assertEquals(message, re.getMessage());
- assertEquals(npe, re.getCause());
-
- re = new RuntimeException(null, npe);
- assertNull(re.getMessage());
-
- re = new RuntimeException(message, null);
- assertNull(re.getCause());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "RuntimeException",
- args = {java.lang.Throwable.class}
- )
- public void test_ConstructorLThrowable() {
- NullPointerException npe = new NullPointerException();
- RuntimeException re = new RuntimeException(npe);
- assertEquals(npe, re.getCause());
-
- re = new RuntimeException((Throwable) null);
- assertNull(re.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimePermissionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimePermissionTest.java
deleted file mode 100644
index cc5145e..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimePermissionTest.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(RuntimePermission.class)
-public class RuntimePermissionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.lang.RuntimePermission#RuntimePermission(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "RuntimePermission",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.lang.RuntimePermission(java.lang.String)
- RuntimePermission r = new RuntimePermission("createClassLoader");
- assertEquals("Returned incorrect name",
- "createClassLoader", r.getName());
-
- }
-
- /**
- * @tests java.lang.RuntimePermission#RuntimePermission(java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "RuntimePermission",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_String() {
- // Test for method java.lang.RuntimePermission(java.lang.String,
- // java.lang.String)
- RuntimePermission r = new RuntimePermission("createClassLoader", null);
- assertEquals("Returned incorrect name",
- "createClassLoader", r.getName());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimeTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimeTest.java
deleted file mode 100644
index 2f2b823..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimeTest.java
+++ /dev/null
@@ -1,1096 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.UnsupportedEncodingException;
-import java.security.Permission;
-import java.util.Arrays;
-import java.util.Vector;
-
-import tests.support.resource.Support_Resources;
-
-@TestTargetClass(Runtime.class)
-public class RuntimeTest extends junit.framework.TestCase {
-
- Runtime r = Runtime.getRuntime();
-
- InputStream is;
-
- String s;
-
- static boolean flag = false;
-
- static boolean ranFinalize = false;
-
- int statusCode = -1;
-
- class HasFinalizer {
- String internalString;
-
- HasFinalizer(String s) {
- internalString = s;
- }
-
- @Override
- protected void finalize() {
- internalString = "hit";
- }
- }
-
- @Override
- protected void finalize() {
- if (flag)
- ranFinalize = true;
- }
-
- protected RuntimeTest createInstance() {
- return new RuntimeTest("FT");
- }
-
- /**
- * @tests java.lang.Runtime#exec(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- notes = "",
- method = "exec",
- args = {java.lang.String.class}
- )
- public void test_exec() {
- /* successful exec's are tested by java.lang.Process */
- try {
- Runtime.getRuntime().exec("AnInexistentProgram");
- fail("failed to throw IOException when exec'ed inexistent program");
- } catch (IOException e) { /* expected */ }
- }
-
- /**
- * @tests java.lang.Runtime#freeMemory()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "freeMemory",
- args = {}
- )
- public void test_freeMemory() {
- try {
- long before = r.freeMemory();
- Vector<StringBuffer> v = new Vector<StringBuffer>();
- for (int i = 1; i < 10; i++)
- v.addElement(new StringBuffer(10000));
- long after = r.freeMemory();
- v = null;
- r.gc();
- assertTrue("freeMemory should return less value after " +
- "creating an object", after < before);
- long afterGC = r.freeMemory();
- assertTrue("freeMemory should not return less value after " +
- "creating an object", afterGC > after);
- } catch (Exception e) {
- System.out.println("Out of memory during freeMemory test: "
- + e.getMessage());
- r.gc();
- } finally {
- r.gc();
- }
- }
-
- /**
- * @tests java.lang.Runtime#gc()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "gc",
- args = {}
- )
- public void test_gc() {
- // Test for method void java.lang.Runtime.gc()
- try {
- r.gc(); // ensure all garbage objects have been collected
- r.gc(); // two GCs force collection phase to complete
- long firstRead = r.totalMemory() - r.freeMemory();
- Vector<StringBuffer> v = new Vector<StringBuffer>();
- for (int i = 1; i < 10; i++)
- v.addElement(new StringBuffer(10000));
- long secondRead = r.totalMemory() - r.freeMemory();
- v = null;
- r.gc();
- r.gc();
- assertTrue("object memory did not grow", secondRead > firstRead);
- assertTrue("space was not reclaimed", (r.totalMemory() - r
- .freeMemory()) < secondRead);
- } catch (Throwable t) {
- System.out.println("Out of memory during gc test");
- r.gc();
- r.gc();
- }
- }
-
- /**
- * @tests java.lang.Runtime#getRuntime()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "getRuntime method is verified in initial setup for other tests.",
- method = "getRuntime",
- args = {}
- )
- public void test_getRuntime() {
- // Test for method java.lang.Runtime java.lang.Runtime.getRuntime()
- assertNotNull(Runtime.getRuntime());
- }
-
- /**
- * @tests java.lang.Runtime#runFinalization()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "runFinalization",
- args = {}
- )
- public void test_runFinalization() {
- // Test for method void java.lang.Runtime.runFinalization()
-
- flag = true;
- createInstance();
- int count = 10;
- // the gc below likely bogosifies the test, but will have to do for
- // the moment
- while (!ranFinalize && count-- > 0) {
- r.gc();
- r.runFinalization();
- }
- assertTrue("Failed to run finalization", ranFinalize);
- }
-
- /**
- * @tests java.lang.Runtime#totalMemory()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "totalMemory",
- args = {}
- )
- public void test_totalMemory() {
- // Test for method long java.lang.Runtime.totalMemory()
- assertTrue("totalMemory returned nonsense value", r.totalMemory() >= r
- .freeMemory());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addShutdownHook",
- args = {java.lang.Thread.class}
- )
- public void test_addShutdownHook() {
- Thread thrException = new Thread () {
- public void run() {
- try {
- Runtime.getRuntime().addShutdownHook(this);
- fail("IllegalStateException was not thrown.");
- } catch(IllegalStateException ise) {
- //expected
- }
- }
- };
-
- try {
- Runtime.getRuntime().addShutdownHook(thrException);
- } catch (Throwable t) {
- fail(t.getMessage());
- }
-
- try {
- Runtime.getRuntime().addShutdownHook(thrException);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- // expected
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals("shutdownHooks")) {
- throw new SecurityException();
- }
- }
- };
-
- // remove previously added hook so we're not depending on the priority
- // of the Exceptions to be thrown.
- Runtime.getRuntime().removeShutdownHook(thrException);
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- Runtime.getRuntime().addShutdownHook(thrException);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- try {
- Thread.currentThread().sleep(1000);
- } catch (InterruptedException ie) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "availableProcessors",
- args = {}
- )
- public void test_availableProcessors() {
- assertTrue(Runtime.getRuntime().availableProcessors() > 0);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "exec",
- args = {java.lang.String.class, java.lang.String[].class}
- )
- public void test_execLjava_lang_StringLjava_lang_StringArray() {
-
- String [] envp = getEnv();
-
- checkExec(0, envp, null);
- checkExec(0, null, null);
-
- try {
- Runtime.getRuntime().exec((String)null, null);
- fail("NullPointerException should be thrown.");
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals("checkExec")) {
- throw new SecurityException();
- }
- }
-
- public void checkExec(String cmd) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
-
- try {
- Runtime.getRuntime().exec("ls", envp);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (IOException e) {
- fail("IOException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- try {
- Runtime.getRuntime().exec("", envp);
- fail("IllegalArgumentException should be thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- } catch (IOException e) {
- fail("IOException was thrown.");
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "exec",
- args = {java.lang.String[].class, java.lang.String[].class}
- )
- public void test_execLjava_lang_StringArrayLjava_lang_StringArray() {
- String [] envp = getEnv();
-
- checkExec(4, envp, null);
- checkExec(4, null, null);
-
- try {
- Runtime.getRuntime().exec((String[])null, null);
- fail("NullPointerException should be thrown.");
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- try {
- Runtime.getRuntime().exec(new String[]{"ls", null}, null);
- fail("NullPointerException should be thrown.");
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals("checkExec")) {
- throw new SecurityException();
- }
- }
-
- public void checkExec(String cmd) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
-
- try {
- Runtime.getRuntime().exec(new String[]{"ls"}, envp);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (IOException e) {
- fail("IOException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- try {
- Runtime.getRuntime().exec(new String[]{}, envp);
- fail("IndexOutOfBoundsException should be thrown.");
- } catch(IndexOutOfBoundsException ioob) {
- //expected
- } catch (IOException e) {
- fail("IOException was thrown.");
- }
-
- try {
- Runtime.getRuntime().exec(new String[]{""}, envp);
- fail("IOException should be thrown.");
- } catch (IOException e) { /* expected */ }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "exec",
- args = {java.lang.String.class, java.lang.String[].class, java.io.File.class}
- )
- public void test_execLjava_lang_StringLjava_lang_StringArrayLjava_io_File() {
-
- String [] envp = getEnv();
-
- File workFolder = Support_Resources.createTempFolder();
-
- checkExec(2, envp, workFolder);
- checkExec(2, null, null);
-
- try {
- Runtime.getRuntime().exec((String)null, null, workFolder);
- fail("NullPointerException should be thrown.");
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals("checkExec")) {
- throw new SecurityException();
- }
- }
-
- public void checkExec(String cmd) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
-
- try {
- Runtime.getRuntime().exec("ls", envp, workFolder);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (IOException e) {
- fail("IOException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- try {
- Runtime.getRuntime().exec("", envp, workFolder);
- fail("SecurityException should be thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- } catch (IOException e) {
- fail("IOException was thrown.");
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "exec",
- args = {java.lang.String[].class, java.lang.String[].class, java.io.File.class}
- )
- public void test_execLjava_lang_StringArrayLjava_lang_StringArrayLjava_io_File() {
- String [] envp = getEnv();
-
- File workFolder = Support_Resources.createTempFolder();
-
- checkExec(5, envp, workFolder);
- checkExec(5, null, null);
-
- try {
- Runtime.getRuntime().exec((String[])null, null, workFolder);
- fail("NullPointerException should be thrown.");
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- try {
- Runtime.getRuntime().exec(new String[]{"ls", null}, null, workFolder);
- fail("NullPointerException should be thrown.");
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals("checkExec")) {
- throw new SecurityException();
- }
- }
-
- public void checkExec(String cmd) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
-
- try {
- Runtime.getRuntime().exec(new String[] {"ls"}, envp, workFolder);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (IOException e) {
- fail("IOException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- try {
- Runtime.getRuntime().exec(new String[]{""}, envp, workFolder);
- fail("IOException should be thrown.");
- } catch (IOException e) {
- //expected
- }
- }
-
- String [] getEnv() {
- Object [] valueSet = System.getenv().values().toArray();
- Object [] keySet = System.getenv().keySet().toArray();
- String [] envp = new String[valueSet.length];
- for(int i = 0; i < envp.length; i++) {
- envp[i] = keySet[i] + "=" + valueSet[i];
- }
- return envp;
- }
-
- void checkExec(int testCase, String [] envp, File file) {
- String dirName = "Test_Directory";
- String dirParentName = "Parent_Directory";
- File resources = Support_Resources.createTempFolder();
- String folder = resources.getAbsolutePath() + "/" + dirName;
- String folderWithParent = resources.getAbsolutePath() + "/" +
- dirParentName + "/" + dirName;
- String command = "mkdir " + folder;
- String [] commandArguments = {"mkdir", folder};
- try {
- Process proc = null;
- switch(testCase) {
- case 0:
- proc = Runtime.getRuntime().exec(command, envp);
- break;
- case 1:
- proc = Runtime.getRuntime().exec(command);
- break;
- case 2:
- proc = Runtime.getRuntime().exec(command, envp, file);
- break;
- case 3:
- proc = Runtime.getRuntime().exec(commandArguments);
- break;
- case 4:
- proc = Runtime.getRuntime().exec(commandArguments, envp);
- break;
- case 5:
- proc = Runtime.getRuntime().exec(commandArguments, envp, file);
- break;
- }
- assertNotNull(proc);
- try {
- Thread.sleep(3000);
- } catch(InterruptedException ie) {
- fail("InterruptedException was thrown.");
- }
- File f = new File(folder);
- assertTrue(f.exists());
- if(f.exists()) {
- f.delete();
- }
- } catch(IOException io) {
- fail("IOException was thrown.");
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "exec",
- args = {java.lang.String.class}
- )
- public void test_execLjava_lang_String() {
- checkExec(1, null, null);
-
- try {
- Runtime.getRuntime().exec((String) null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- } catch (IOException e) {
- fail("IOException was thrown.");
- }
-
- try {
- Runtime.getRuntime().exec("");
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- } catch (IOException e) {
- fail("IOException was thrown.");
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkExec(String cmd) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- Runtime.getRuntime().exec("ls");
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (IOException ioe) {
- fail("IOException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "exec",
- args = {java.lang.String[].class}
- )
- public void test_execLjava_lang_StringArray() {
-
- checkExec(3, null, null);
-
- try {
- Runtime.getRuntime().exec((String[]) null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- } catch (IOException e) {
- fail("IOException was thrown.");
- }
-
- try {
- Runtime.getRuntime().exec(new String[]{"ls", null});
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- } catch (IOException e) {
- fail("IOException was thrown.");
- }
-
- try {
- Runtime.getRuntime().exec(new String[]{});
- fail("IndexOutOfBoundsException was not thrown.");
- } catch(IndexOutOfBoundsException iobe) {
- //expected
- } catch (IOException e) {
- fail("IOException was thrown.");
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkExec(String cmd) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- Runtime.getRuntime().exec(new String[]{"ls"});
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (IOException ioe) {
- fail("IOException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- try {
- Runtime.getRuntime().exec(new String[]{""});
- fail("IOException should be thrown.");
- } catch (IOException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "runFinalizersOnExit",
- args = {boolean.class}
- )
- public void test_runFinalizersOnExit() {
- Runtime.getRuntime().runFinalizersOnExit(true);
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkExit(int status) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- Runtime.getRuntime().runFinalizersOnExit(true);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "removeShutdownHook",
- args = {java.lang.Thread.class}
- )
- public void test_removeShutdownHookLjava_lang_Thread() {
- Thread thr1 = new Thread () {
- public void run() {
- try {
- Runtime.getRuntime().addShutdownHook(this);
- } catch(IllegalStateException ise) {
- fail("IllegalStateException shouldn't be thrown.");
- }
- }
- };
-
- try {
- Runtime.getRuntime().addShutdownHook(thr1);
- Runtime.getRuntime().removeShutdownHook(thr1);
- } catch (Throwable t) {
- fail(t.getMessage());
- }
-
- Thread thr2 = new Thread () {
- public void run() {
- try {
- Runtime.getRuntime().removeShutdownHook(this);
- fail("IllegalStateException wasn't thrown.");
- } catch(IllegalStateException ise) {
- //expected
- }
- }
- };
-
- try {
- Runtime.getRuntime().addShutdownHook(thr2);
- } catch (Throwable t) {
- fail(t.getMessage());
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals("shutdownHooks")) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- Runtime.getRuntime().addShutdownHook(thr1);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- try {
- Thread.currentThread().sleep(1000);
- } catch (InterruptedException ie) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "maxMemory",
- args = {}
- )
- public void test_maxMemory() {
- assertTrue(Runtime.getRuntime().maxMemory() < Long.MAX_VALUE);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "traceInstructions",
- args = {boolean.class}
- )
- public void test_traceInstructions() {
- Runtime.getRuntime().traceInstructions(false);
- Runtime.getRuntime().traceInstructions(true);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "traceMethodCalls",
- args = {boolean.class}
- )
- public void test_traceMethodCalls() {
- Runtime.getRuntime().traceMethodCalls(false);
- Runtime.getRuntime().traceMethodCalls(true);
- Runtime.getRuntime().traceMethodCalls(false);
- // try to clean up
- //File tracefile = new File("/sdcard/dmtrace.trace");
- //if(tracefile.exists()) {
- // tracefile.delete();
- //}
- }
-
- @SuppressWarnings("deprecation")
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalizedInputStream",
- args = {java.io.InputStream.class}
- )
- public void test_getLocalizedInputStream() {
- String simpleString = "Heart \u2f3c";
- byte[] expected = {72, 0, 101, 0, 97, 0, 114, 0, 116, 0, 32, 0, 60, 47};
- byte[] returned = new byte[expected.length];
-
- String oldEncoding = System.getProperty("file.encoding");
- System.setProperty("file.encoding", "UTF-16LE");
-
- try {
- ByteArrayInputStream bais = new ByteArrayInputStream(
- simpleString.getBytes("UTF-8"));
-
- InputStream lcIn =
- Runtime.getRuntime().getLocalizedInputStream(bais);
- try {
- lcIn.read(returned);
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- }
-
- assertTrue("wrong result for String: " + simpleString,
- Arrays.equals(expected, returned));
- } catch (UnsupportedEncodingException e) {
- fail("UnsupportedEncodingException was thrown.");
- } finally {
- System.setProperty("file.encoding", oldEncoding);
- }
- }
-
- @SuppressWarnings("deprecation")
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "",
- method = "getLocalizedOutputStream",
- args = {java.io.OutputStream.class}
- )
- public void test_getLocalizedOutputStream() {
- String simpleString = "Heart \u2f3c";
- byte[] expected = {72, 0, 101, 0, 97, 0, 114, 0, 116, 0, 32, 0, 60, 47};
- byte[] returned;
-
- String oldEncoding = System.getProperty("file.encoding");
- System.setProperty("file.encoding", "UTF-16LE");
-
- try {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
-
- OutputStream lcOut =
- Runtime.getRuntime().getLocalizedOutputStream(out);
- try {
- lcOut.write(simpleString.getBytes("UTF-8"));
- lcOut.flush();
- lcOut.close();
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- }
-
- returned = out.toByteArray();
-
- assertTrue("wrong result for String: " + returned.toString() +
- " expected string: " + expected.toString(),
- Arrays.equals(expected, returned));
- } finally {
- System.setProperty("file.encoding", oldEncoding);
- }
- }
-
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "load",
- args = {java.lang.String.class}
- )
- public void test_load() {
-
- try {
- Runtime.getRuntime().load("nonExistentLibrary");
- fail("UnsatisfiedLinkError was not thrown.");
- } catch(UnsatisfiedLinkError ule) {
- //expected
- }
-
- try {
- Runtime.getRuntime().load(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
-
- }
-
- public void checkLink(String lib) {
- if (lib.endsWith("libjvm.so")) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- Runtime.getRuntime().load("libjvm.so");
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "loadLibrary",
- args = {java.lang.String.class}
- )
- public void test_loadLibrary() {
- try {
- Runtime.getRuntime().loadLibrary("nonExistentLibrary");
- fail("UnsatisfiedLinkError was not thrown.");
- } catch(UnsatisfiedLinkError ule) {
- //expected
- }
-
- try {
- Runtime.getRuntime().loadLibrary(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
-
- }
-
- public void checkLink(String lib) {
- if (lib.endsWith("libjvm.so")) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- Runtime.getRuntime().loadLibrary("libjvm.so");
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "This method never returns normally, " +
- "and can't be tested. Only SecurityException can be checked.",
- method = "exit",
- args = {int.class}
- )
- public void test_exit() {
- statusCode = -1;
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
-
- }
-
- public void checkExit(int status) {
- statusCode = status;
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- r.exit(0);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- assertTrue("Incorrect status code was received: " + statusCode,
- statusCode == 0);
- System.setSecurityManager(oldSm);
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Can't be tested. This method terminates the currently " +
- "running VM. Only SecurityException can be checked.",
- method = "halt",
- args = {int.class}
- )
- public void test_halt() {
- statusCode = -1;
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
-
- }
-
- public void checkExit(int status) {
- statusCode = status;
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- r.halt(0);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- assertTrue("Incorrect status code was received: " + statusCode,
- statusCode == 0);
- System.setSecurityManager(oldSm);
- }
- }
-
- public RuntimeTest() {
- }
-
- public RuntimeTest(String name) {
- super(name);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SecurityExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SecurityExceptionTest.java
deleted file mode 100644
index 407d6f9..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SecurityExceptionTest.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-@TestTargetClass(SecurityException.class)
-public class SecurityExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.SecurityException#SecurityException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SecurityException",
- args = {}
- )
- public void test_Constructor() {
- SecurityException e = new SecurityException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.SecurityException#SecurityException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SecurityException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- SecurityException e = new SecurityException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.SecurityException#SecurityException(String, Throwable)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SecurityException",
- args = {java.lang.String.class, java.lang.Throwable.class}
- )
- @SuppressWarnings("nls")
- public void test_ConstructorLjava_lang_StringLjava_lang_Throwable() {
- NullPointerException npe = new NullPointerException();
- SecurityException e = new SecurityException("fixture", npe);
- assertSame("fixture", e.getMessage());
- assertSame(npe, e.getCause());
- }
-
- /**
- * @tests java.lang.SecurityException#SecurityException(Throwable)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SecurityException",
- args = {java.lang.Throwable.class}
- )
- @SuppressWarnings("nls")
- public void test_ConstructorLjava_lang_Throwable() {
- NullPointerException npe = new NullPointerException();
- SecurityException e = new SecurityException(npe);
- assertSame(npe, e.getCause());
- }
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new SecurityException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new SecurityException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SecurityManagerTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SecurityManagerTest.java
deleted file mode 100644
index be5aa41..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SecurityManagerTest.java
+++ /dev/null
@@ -1,1589 +0,0 @@
-/* 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.File;
-import java.io.FileDescriptor;
-import java.io.FilePermission;
-import java.io.IOException;
-import java.lang.reflect.Member;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.SocketPermission;
-import java.net.UnknownHostException;
-import java.security.AccessControlContext;
-import java.security.AllPermission;
-import java.security.Permission;
-import java.security.ProtectionDomain;
-import java.security.Security;
-import java.security.SecurityPermission;
-
-import tests.support.Support_Exec;
-
-/**
- * Test case for java.lang.SecurityManager
- */
-@TestTargetClass(value = SecurityManager.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "AWTPermission class is not supported.",
- method = "checkSystemClipboardAccess",
- args = {}
- )
-})
-public class SecurityManagerTest extends TestCase {
- MutableSecurityManager mutableSM = null;
-
- MockSecurityManager mockSM = null;
-
- SecurityManager originalSM = null;
-
- String deletedFile = "/";
- String readedFile = "/";
- String writedFile = "/";
-
- /**
- * @tests java.lang.SecurityManager#SecurityManager()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SecurityManager",
- args = {}
- )
- public void test_Constructor() {
- SecurityManager localManager = null;
- try {
- localManager = new MockSecurityManager();
- } catch (Exception e) {
- fail("Unexpected exception " + e.toString());
- }
-
- try {
- assertNotNull("Incorrect SecurityManager", localManager);
- System.setSecurityManager(localManager);
- try {
- new MockSecurityManager();
- fail("SecurityException was not thrown");
- } catch (SecurityException se) {
- // expected
- }
- } finally {
- System.setSecurityManager(null);
- }
- }
-
- /**
- * @tests java.lang.SecurityManager#checkPackageAccess(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkPackageAccess",
- args = {java.lang.String.class}
- )
- public void test_checkPackageAccessLjava_lang_String() {
- final String old = Security.getProperty("package.access");
- Security.setProperty("package.access", "a.,bbb, c.d.");
-
- mutableSM
- .denyPermission(new RuntimePermission("accessClassInPackage.*"));
-
- try {
- mutableSM.checkPackageAccess("z.z.z");
- mutableSM.checkPackageAccess("aa");
- mutableSM.checkPackageAccess("bb");
- mutableSM.checkPackageAccess("c");
-
- try {
- mutableSM.checkPackageAccess("a");
- fail("This should throw a SecurityException.");
- } catch (SecurityException ok) {
- }
-
- try {
- mutableSM.checkPackageAccess("bbb");
- fail("This should throw a SecurityException.");
- } catch (SecurityException ok) {
- }
-
- try {
- mutableSM.checkPackageAccess("c.d.e");
- fail("This should throw a SecurityException.");
- } catch (SecurityException ok) {
- }
-
- Security.setProperty("package.access", "QWERTY");
- mutableSM.checkPackageAccess("a");
- mutableSM.checkPackageAccess("qwerty");
- try {
- mutableSM.checkPackageAccess("QWERTY");
- fail("This should throw a SecurityException.");
- } catch (SecurityException ok) {
- }
-
- } finally {
- Security.setProperty("package.access", old == null ? "" : old);
- }
- }
-
- /**
- * @tests java.lang.SecurityManager#checkPackageDefinition(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkPackageDefinition",
- args = {java.lang.String.class}
- )
- public void test_checkPackageDefinitionLjava_lang_String() {
- final String old = Security.getProperty("package.definition");
- Security.setProperty("package.definition", "a.,bbb, c.d.");
-
- mutableSM
- .denyPermission(new RuntimePermission("defineClassInPackage.*"));
-
- try {
- mutableSM.checkPackageDefinition("z.z.z");
- mutableSM.checkPackageDefinition("aa");
- mutableSM.checkPackageDefinition("bb");
- mutableSM.checkPackageDefinition("c");
-
- try {
- mutableSM.checkPackageDefinition("a");
- fail("This should throw a SecurityException.");
- } catch (SecurityException ok) {
- }
-
- try {
- mutableSM.checkPackageDefinition("bbb");
- fail("This should throw a SecurityException.");
- } catch (SecurityException ok) {
- }
-
- try {
- mutableSM.checkPackageDefinition("c.d.e");
- fail("This should throw a SecurityException.");
- } catch (SecurityException ok) {
- }
-
- Security.setProperty("package.definition", "QWERTY");
- mutableSM.checkPackageDefinition("a");
- mutableSM.checkPackageDefinition("qwerty");
- try {
- mutableSM.checkPackageDefinition("QWERTY");
- fail("This should throw a SecurityException.");
- } catch (SecurityException ok) {
- }
-
- } finally {
- Security.setProperty("package.definition", old == null ? "" : old);
- }
- }
-
- /**
- * @tests java.lang.SecurityManager#checkMemberAccess(java.lang.Class, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkMemberAccess",
- args = {java.lang.Class.class, int.class}
- )
- public void test_checkMemberAccessLjava_lang_ClassI() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- mutableSM.denyPermission(
- new RuntimePermission("accessDeclaredMembers"));
- System.setSecurityManager(mutableSM);
- try {
- getClass().getDeclaredFields();
-
- try {
- Object.class.getDeclaredFields();
- fail("This should throw a SecurityException.");
- } catch (SecurityException e) {
- }
-
- try {
- mutableSM.checkMemberAccess(Object.class, Member.DECLARED);
- fail("SecurityException was not thrown.");
- } catch(SecurityException se) {
- //expected
- }
-
- try {
- mutableSM.checkMemberAccess(null, Member.PUBLIC);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- } finally {
- System.setSecurityManager(null);
- }
- }
-
- /**
- * @tests java.lang.SecurityManager#checkPermission(java.security.Permission)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkPermission",
- args = {java.security.Permission.class}
- )
- public void test_checkPermissionLjava_security_Permission()
- throws Exception {
-
- // tmp user home to avoid presence of ${user.home}/.java.policy
- //String tmpUserHome = System.getProperty("java.io.tmpdir")
- // + File.separatorChar + "tmpUserHomeForSecurityManagerTest";
- //File dir = new File(tmpUserHome);
- //if (!dir.exists()) {
- // dir.mkdirs();
- // dir.deleteOnExit();
- //}
- //String javaPolycy = tmpUserHome + File.separatorChar + ".java.policy";
- //assertFalse("There should be no java policy file: " + javaPolycy,
- // new File(javaPolycy).exists());
- //
- //String[] arg = new String[] { "-Duser.home=" + tmpUserHome,
- // checkPermissionLjava_security_PermissionTesting.class.getName() };
- //
- //Support_Exec.execJava(arg, null, true);
-
- checkPermissionLjava_security_PermissionTesting.class.getName();
-
- try {
- mutableSM.checkPermission(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- private static class checkPermissionLjava_security_PermissionTesting {
- public static void main(String[] args) {
- MutableSecurityManager sm = new MutableSecurityManager();
- sm.addPermission(MutableSecurityManager.SET_SECURITY_MANAGER);
- System.setSecurityManager(sm);
- try {
- try {
- System.getSecurityManager().checkPermission(
- new RuntimePermission("createClassLoader"));
- fail("This should throw a SecurityException");
- } catch (SecurityException e) {
- }
-
- try {
- sm.checkPermission(new SecurityPermission("setSystemScope"));
- } catch(SecurityException se) {
- fail("SecurityException is thrown.");
- }
- } finally {
- System.setSecurityManager(null);
- }
- }
- }
-
- /**
- * @tests java.lang.SecurityManager#checkAccess(java.lang.Thread)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkAccess",
- args = {java.lang.Thread.class}
- )
- public void test_checkAccessLjava_lang_Thread() throws InterruptedException {
- // Regression for HARMONY-66
- Thread t = new Thread() {
- @Override
- public void run() {
- }
- };
- t.start();
- t.join();
- new SecurityManager().checkAccess(t);
-
- mutableSM.addPermission(new AllPermission());
- mutableSM.denyPermission( new RuntimePermission("modifyThread"));
- System.setSecurityManager(mutableSM);
-
- try {
- try {
- mutableSM.checkAccess(t);
- // should not throw SecurityException for not system thread.
- } catch(SecurityException se) {
- fail("SecurityException was thrown.");
- }
-
- try {
- ThreadGroup initialThreadGroup = Thread.currentThread().getThreadGroup();
-
- while (initialThreadGroup.getParent() != null) {
- initialThreadGroup = initialThreadGroup.getParent();
- }
- Thread [] systemThread = new Thread[1];
- initialThreadGroup.enumerate(systemThread);
- mutableSM.checkAccess(systemThread[0]);
- fail("SecurityException was not thrown.");
- } catch(SecurityException se) {
- // expected
- }
-
-
- } finally {
- System.setSecurityManager(null);
- }
-
- try {
- mutableSM.checkAccess((Thread) null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- try {
- new SecurityManager().checkAccess((Thread)null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe){
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkAccess",
- args = {java.lang.ThreadGroup.class}
- )
- public void test_checkAccessLjava_lang_ThreadGroup() {
-
- ThreadGroup tg = new ThreadGroup("name");
-
- RuntimePermission rp = new RuntimePermission("modifyThreadGroup");
- mutableSM.addPermission(new AllPermission());
-
- mutableSM.denyPermission(rp);
- SecurityManager sm = System.getSecurityManager();
- System.setSecurityManager(mutableSM);
-
- try {
- try {
- mutableSM.checkAccess(tg);
-
- } catch(SecurityException se) {
- fail("SecurityException was thrown.");
- }
-
- try {
- ThreadGroup initialThreadGroup = Thread.currentThread().getThreadGroup();
-
- while (initialThreadGroup.getParent() != null) {
- initialThreadGroup = initialThreadGroup.getParent();
- }
- mutableSM.checkAccess(initialThreadGroup);
- } catch(SecurityException se) {
-
- }
- } finally {
- System.setSecurityManager(sm);
- }
-
- try {
- mutableSM.checkAccess((ThreadGroup) null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
- /**
- * @tests {@link java.lang.SecurityManager#checkAccept(String, int)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkAccept",
- args = {java.lang.String.class, int.class}
- )
- @SuppressWarnings("nls")
- public void test_checkAcceptLjava_lang_String_int() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- System.setSecurityManager(mutableSM);
- try {
- assertFalse(startServerSocket());
- assertTrue(mutableSM.isCheckAcceptCalled);
-
- mutableSM.denyPermission(new SocketPermission("localhost:1024-",
- "accept, connect, listen"));
- assertTrue(startServerSocket());
- assertTrue(mutableSM.isCheckAcceptCalled);
-
- try {
- mutableSM.checkAccept(null, 0);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- } finally {
- System.setSecurityManager(null);
- }
- }
-
- boolean startServerSocket() {
- boolean isSecurityExceptionThrown = false;
- ServerSocket ss = null;
- try {
- ss = new ServerSocket(3132);
- Thread thr = new Thread() {
- Socket s = null;
-
- public void run() {
- try {
- s = new Socket(InetAddress.getLocalHost().getHostName(), 3132);
- Thread.sleep(1);
- } catch(InterruptedException ie) {
- fail("InterruptedException was thrown.");
- } catch(UnknownHostException uhe) {
- fail("UnknownHostException was thrown.");
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- } finally {
- try {
- s.close();
- } catch(Exception e) {}
- }
- }
- };
- thr.start();
- ss.accept();
- ss.close();
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- } catch(SecurityException se) {
- isSecurityExceptionThrown = true;
- } finally {
- try {
- if(!ss.isClosed())
- ss.close();
- } catch(Exception e) {
- }
-
- }
- return isSecurityExceptionThrown;
- }
-
- /**
- * @tests {@link java.lang.SecurityManager#checkConnect(String, int)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkConnect",
- args = {java.lang.String.class, int.class}
- )
- public void test_checkConnectLjava_lang_StringI() {
- String hostName = "localhost";
- int port = 1024;
-
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- mutableSM.denyPermission(new SocketPermission("localhost:1024-",
- "accept, connect, listen"));
- System.setSecurityManager(mutableSM);
- try {
- try {
- mutableSM.checkConnect(hostName, port);
- fail("This should throw a SecurityException.");
- } catch (SecurityException e) {
- // expected
- }
-
- assertTrue(createSocketAddress(hostName, port));
-
- try {
- mutableSM.checkConnect(hostName, -1);
- fail("This should throw a SecurityException.");
- } catch (SecurityException e) {
- // expected
- }
-
- try {
- mutableSM.checkConnect(null, 1024);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- } finally {
- System.setSecurityManager(null);
- }
-
- assertFalse(createSocketAddress(hostName, port));
- }
-
- boolean createSocketAddress(String hostname, int port) {
-
- try {
- new InetSocketAddress(hostname, port);
- } catch(SecurityException se) {
- return true;
- }
- return false;
- }
-
- /**
- * @tests {@link java.lang.SecurityManager#checkConnect(String, int, Object)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkConnect",
- args = {java.lang.String.class, int.class, java.lang.Object.class}
- )
- @SuppressWarnings("nls")
- public void test_checkConnectLjava_lang_String_int_Ljava_lang_Object() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- mutableSM.denyPermission(new SocketPermission("localhost:1024-",
- "accept, connect, listen"));
- System.setSecurityManager(mutableSM);
- try {
- ProtectionDomain pDomain = this.getClass().getProtectionDomain();
- ProtectionDomain[] pd = { pDomain };
- AccessControlContext acc = new AccessControlContext(pd);
- try {
- mutableSM.checkConnect("localhost", 1024, acc);
- fail("This should throw a SecurityException.");
- } catch (SecurityException e) {
- // expected
- }
-
- try {
- mutableSM.checkConnect("localhost", -1, acc);
- // The action "resolve" is implicitely in the denied Permission
- // that was added to the denied permissions at the beginning of
- // this test. So this throws a security Exception on the RI and
- // also on android.
- fail("This should throw a SecurityException.");
- } catch (SecurityException e) {
- // expected
- }
-
- assertTrue(createSocketAddress("localhost", 1024));
-
- try {
- mutableSM.checkConnect(null, 1024, acc);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- System.setSecurityManager(null);
- try {
- mutableSM.checkConnect("localhost", 1024, null);
- fail("SecurityException was not thrown.");
- } catch(SecurityException se) {
- //expected
- }
- } finally {
- System.setSecurityManager(null);
- }
- assertFalse(createSocketAddress("localhost", 1024));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkCreateClassLoader",
- args = {}
- )
- public void test_checkCreateClassLoader() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- System.setSecurityManager(mutableSM);
- try {
- mutableSM.checkCreateClassLoader();
- } catch (SecurityException e) {
- fail("Unexpected SecurityException " + e.toString());
- }
-
- SecurityManager localManager = new MockSecurityManager();
- try {
- System.setSecurityManager(localManager);
- try {
- localManager.checkCreateClassLoader();
- fail("Expected SecurityException was not thrown");
- } catch (SecurityException e) {
- // expected
- }
- } finally {
- System.setSecurityManager(null);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkDelete",
- args = {java.lang.String.class}
- )
- public void test_checkDeleteLjava_lang_String() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- mutableSM
- .denyPermission(new FilePermission("<<ALL FILES>>", "delete"));
- try {
- System.setSecurityManager(mutableSM);
-
- try {
- mutableSM.checkDelete("new.file");
- fail("SecurityException was not thrown");
- } catch (SecurityException npe) {
- // expected
- }
-
- try {
- mutableSM.checkDelete(null);
- fail("NullPointerException was not thrown");
- } catch (NullPointerException npe) {
- // expected
- }
- } finally {
- System.setSecurityManager(null);
- }
-
- SecurityManager localManager = new MockSecurityManager();
- try {
- System.setSecurityManager(localManager);
- try {
- localManager.checkDelete(deletedFile);
- fail("Expected SecurityException was not thrown");
- } catch (SecurityException e) {
- // expected
- }
- } finally {
- System.setSecurityManager(null);
- }
- }
-
- /**
- * @tests {@link java.lang.SecurityManager#checkExec(String)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkExec",
- args = {java.lang.String.class}
- )
- @SuppressWarnings("nls")
- public void test_checkExecLjava_lang_String() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- mutableSM
- .denyPermission(new FilePermission("<<ALL FILES>>", "execute"));
- System.setSecurityManager(mutableSM);
- try {
- mutableSM.checkExec("java");
- fail("This should throw a SecurityException.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(null);
- }
-
- try {
- mutableSM.checkExec(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- /**
- * @tests {@link java.lang.SecurityManager#checkExit(int)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkExit",
- args = {int.class}
- )
- @SuppressWarnings("nls")
- public void test_checkExit_int() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- try {
- mutableSM.checkExit(0);
- } catch(SecurityException se) {
- fail("SecurityException was thrown.");
- }
- mutableSM.denyPermission(new RuntimePermission("exitVM"));
- System.setSecurityManager(mutableSM);
- try {
- mutableSM.checkExit(0);
- fail("This should throw a SecurityException.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(null);
- }
- }
-
- /**
- * @tests {@link java.lang.SecurityManager#checkLink(String)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkLink",
- args = {java.lang.String.class}
- )
- @SuppressWarnings("nls")
- public void test_checkLinkLjava_lang_String() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- mutableSM.denyPermission(new RuntimePermission("loadLibrary.harmony"));
- System.setSecurityManager(mutableSM);
- try {
- try {
- mutableSM.checkLink("harmony");
- fail("This should throw a SecurityException.");
- } catch (SecurityException e) {
- // expected
- }
-
- try {
- mutableSM.checkLink(null);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- } finally {
- System.setSecurityManager(null);
- }
- }
-
- /**
- * @tests {@link java.lang.SecurityManager#checkListen(int)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkListen",
- args = {int.class}
- )
- @SuppressWarnings("nls")
- public void test_checkListen_int() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- try {
- mutableSM.checkListen(80);
- } catch(SecurityException se) {
- fail("SecurityException was thrown.");
- }
- mutableSM
- .denyPermission(new SocketPermission("localhost:80", "listen"));
- System.setSecurityManager(mutableSM);
-
- try {
- mutableSM.checkListen(80);
- fail("This should throw a SecurityException.");
- } catch (SecurityException e) {
- // expected
- }
- mutableSM.addPermission(new AllPermission());
- mutableSM.denyPermission(new SocketPermission("localhost:1024-",
- "listen"));
- System.setSecurityManager(mutableSM);
- try {
- mutableSM.checkListen(0);
- fail("This should throw a SecurityException.");
- } catch (SecurityException e) {
- // expected
- }
- }
-
- /**
- * @throws UnknownHostException
- * @tests {@link java.lang.SecurityManager#checkMulticast(java.net.InetAddress)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies SecurityException.",
- method = "checkMulticast",
- args = {java.net.InetAddress.class}
- )
- @SuppressWarnings("nls")
- public void test_checkMulticastLjava_net_InetAddress()
- throws UnknownHostException {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- try {
- mutableSM.checkMulticast(InetAddress.getByName("localhost"));
- } catch(SecurityException se) {
- fail("SecurityException is thrown.");
- }
- mutableSM.denyPermission(new SocketPermission(InetAddress.getByName(
- "localhost").getHostAddress(), "accept,connect"));
- System.setSecurityManager(mutableSM);
- try {
- mutableSM.checkMulticast(InetAddress.getByName("localhost"));
- fail("This should throw a SecurityException.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(null);
- }
-
- try {
- mutableSM.checkMulticast(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @throws UnknownHostException
- * @tests {@link java.lang.SecurityManager#checkMulticast(java.net.InetAddress,byte)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkMulticast",
- args = {java.net.InetAddress.class, byte.class}
- )
- @SuppressWarnings( { "nls", "deprecation" })
- public void test_checkMulticastLjava_net_InetAddress_int()
- throws UnknownHostException {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- try {
- mutableSM.checkMulticast(
- InetAddress.getByName("localhost"), (byte) 0);
- } catch(SecurityException se) {
- fail("SecurityException is thrown.");
- }
- mutableSM.denyPermission(new SocketPermission(InetAddress.getByName(
- "localhost").getHostAddress(), "accept,connect"));
- System.setSecurityManager(mutableSM);
- try {
- try {
- // the second parameter is the TTL(time to live)
- mutableSM.checkMulticast(InetAddress.getByName("localhost"),
- (byte) 0);
- fail("This should throw a SecurityException.");
- } catch (SecurityException e) {
- // expected
- }
-
- try {
- mutableSM.checkMulticast(null, (byte) 0);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException ne) {
- //expected
- }
- } finally {
- System.setSecurityManager(null);
- }
- }
-
- /**
- *
- * @tests {@link java.lang.SecurityManager#checkPermission(Permission, Object)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkPermission",
- args = {java.security.Permission.class, java.lang.Object.class}
- )
- @SuppressWarnings("nls")
- public void test_checkPermissionLjava_security_PermissionLjava_lang_Object() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- Permission denyp = new SocketPermission("localhost:1024-",
- "accept, connect, listen");
- mutableSM.denyPermission(denyp);
- System.setSecurityManager(mutableSM);
- ProtectionDomain pDomain = this.getClass().getProtectionDomain();
- ProtectionDomain[] pd = { pDomain };
- AccessControlContext acc = new AccessControlContext(pd);
- try {
- mutableSM.checkPermission(denyp, acc);
- fail("This should throw a SecurityException.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(null);
- }
-
- try {
- mutableSM.checkPermission(null, acc);
- fail("NullPointerException was not thrown.");
- } catch (NullPointerException npe) {
- // expected
- }
-
- try {
- mutableSM.checkPermission(denyp, null);
- fail("SecurityException was not thrown.");
- } catch (SecurityException se) {
- // expected
- }
- }
-
- /**
- * @tests {@link java.lang.SecurityManager#checkPrintJobAccess()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkPrintJobAccess",
- args = {}
- )
- @SuppressWarnings("nls")
- public void test_checkPrintJobAccess() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- try {
- mutableSM.checkPrintJobAccess();
- } catch(SecurityException se) {
- fail("SecurityException is thrown.");
- }
- mutableSM.denyPermission(new RuntimePermission("queuePrintJob"));
- System.setSecurityManager(mutableSM);
- try {
- mutableSM.checkPrintJobAccess();
- fail("This should throw a SecurityException.");
- } catch (SecurityException e) {
- // expected
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkPropertiesAccess",
- args = {}
- )
- public void test_checkPropertiesAccess() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- System.setSecurityManager(mutableSM);
- try {
- mutableSM.checkPropertiesAccess();
- } catch (SecurityException e) {
- fail("Unexpected SecurityException " + e.toString());
- } finally {
- System.setSecurityManager(null);
- }
-
- SecurityManager localManager = new MockSecurityManager();
- try {
- System.setSecurityManager(localManager);
- try {
- localManager.checkPropertiesAccess();
- fail("Expected SecurityException was not thrown");
- } catch (SecurityException e) {
- // expected
- }
- } finally {
- System.setSecurityManager(null);
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkPropertyAccess",
- args = {java.lang.String.class}
- )
- public void test_checkPropertyAccessLjava_lang_String() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- System.setSecurityManager(mutableSM);
- try {
- mutableSM.checkPropertyAccess("key");
- } catch (SecurityException e) {
- fail("Unexpected SecurityException " + e.toString());
- } finally {
- System.setSecurityManager(null);
- }
-
- SecurityManager localManager = new MockSecurityManager();
- try {
- System.setSecurityManager(localManager);
- try {
- localManager.checkPropertyAccess("key");
- fail("Expected SecurityException was not thrown");
- } catch (SecurityException e) {
- // expected
- }
- try {
- localManager.checkPropertyAccess("");
- fail("Expected IllegalArgumentException was not thrown");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- localManager.checkPropertyAccess(null);
- fail("Expected NullPointerException was not thrown");
- } catch (NullPointerException e) {
- // expected
- }
- } finally {
- System.setSecurityManager(null);
- }
- }
-
- /**
- * @tests {@link java.lang.SecurityManager#checkRead(FileDescriptor)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkRead",
- args = {java.io.FileDescriptor.class}
- )
- @SuppressWarnings("nls")
- public void test_checkReadLjava_io_FileDescriptor() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- try {
- mutableSM.checkRead(new FileDescriptor());
- } catch(SecurityException se) {
- fail("SecurityException is thrown.");
- }
- mutableSM.denyPermission(new RuntimePermission("readFileDescriptor"));
- System.setSecurityManager(mutableSM);
- try {
- mutableSM.checkRead(new FileDescriptor());
- fail("This should throw a SecurityException.");
- } catch (SecurityException e) {
- // expected
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkRead",
- args = {java.lang.String.class}
- )
- public void test_checkReadLjava_lang_String() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- try {
- mutableSM.checkRead(readedFile);
- } catch(SecurityException se) {
- fail("SecurityException is thrown.");
- }
- mutableSM.denyPermission(new RuntimePermission("readFileDescriptor"));
- System.setSecurityManager(mutableSM);
- try {
- try {
- mutableSM.checkRead(readedFile);
- } catch (SecurityException e) {
- fail("Unexpected SecurityException " + e.toString());
- }
-
- SecurityManager localManager = new MockSecurityManager();
- System.setSecurityManager(localManager);
- try {
- localManager.checkRead(readedFile);
- fail("Expected SecurityException was not thrown");
- } catch (SecurityException e) {
- // expected
- }
-
- try {
- localManager.checkRead((String) null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- } finally {
- System.setSecurityManager(null);
- }
- }
-
- /**
- * @tests {@link java.lang.SecurityManager#checkRead(String,Object)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies SecurityException.",
- method = "checkRead",
- args = {java.lang.String.class, java.lang.Object.class}
- )
- @SuppressWarnings("nls")
- public void test_checkReadLjava_lang_StringLjava_lang_Object() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- ProtectionDomain pDomain = this.getClass().getProtectionDomain();
- ProtectionDomain[] pd = { pDomain };
- AccessControlContext acc = new AccessControlContext(pd);
- mutableSM.denyPermission(new FilePermission("<<ALL FILES>>", "read"));
- System.setSecurityManager(mutableSM);
- try {
- try {
- mutableSM.checkRead("aa", acc);
- fail("This should throw a SecurityException.");
- } catch (SecurityException e) {
- // expected
- }
-
- try {
- mutableSM.checkRead(null, acc);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- } finally {
- System.setSecurityManager(null);
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkSecurityAccess",
- args = {java.lang.String.class}
- )
- public void test_checkSecurityAccessLjava_lang_String() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- System.setSecurityManager(mutableSM);
- try {
- mutableSM.checkSecurityAccess("getPolicy");
- } catch (SecurityException e) {
- fail("Unexpected SecurityException " + e.toString());
- } finally {
- System.setSecurityManager(null);
- }
-
- SecurityManager localManager = new MockSecurityManager();
- try {
- System.setSecurityManager(localManager);
- try {
- localManager.checkSecurityAccess("getPolicy");
- fail("Expected SecurityException was not thrown");
- } catch (SecurityException e) {
- // expected
- }
- try {
- localManager.checkSecurityAccess("");
- fail("Expected IllegalArgumentException was not thrown");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- localManager.checkSecurityAccess(null);
- fail("Expected NullPointerException was not thrown");
- } catch (NullPointerException e) {
- // expected
- }
- } finally {
- System.setSecurityManager(null);
- }
- }
-
- /**
- * @tests {@link java.lang.SecurityManager#checkSetFactory()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkSetFactory",
- args = {}
- )
- @SuppressWarnings("nls")
- public void test_checkSetFactory() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- assertFalse(setFactory());
- mutableSM.denyPermission(new RuntimePermission("setFactory"));
- System.setSecurityManager(mutableSM);
- try {
- try {
- mutableSM.checkSetFactory();
- fail("This should throw a SecurityException.");
- } catch (SecurityException e) {
- // expected
- }
- assertTrue(setFactory());
- } finally {
- System.setSecurityManager(null);
- }
- }
-
- boolean setFactory() {
- try {
- ServerSocket.setSocketFactory(null);
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- } catch(SecurityException se) {
- return true;
- }
- return false;
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "Mark this method not feasable: AWTPermission doesn't exist",
- method = "checkAwtEventQueueAccess",
- args = {}
- )
- public void test_checkAwtEventQueueAccess() {
- mutableSM.addPermission(new AllPermission());
- // TODO AWTPermission class is unavailable
- //mutableSM.denyPermission(new AWTPermission("accessEventQueue"));
- //System.setSecurityManager(mutableSM);
- //try {
- // try {
- // mutableSM.checkAwtEventQueueAccess();
- // fail("This should throw a SecurityException.");
- // } catch (SecurityException e) {
- // expected
- // }
- //} finally {
- // System.setSecurityManager(null);
- //}
- }
-
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "Mark this method not feasable: AWTPermission doesn't exist",
- method = "checkTopLevelWindow",
- args = {java.lang.Object.class}
- )
- public void test_checkTopLevelWindowLjava_lang_Object() {
- // assertFalse("Calling thread isn't trusted to bring up the top-level window",
- // mutableSM.checkTopLevelWindow(this));
-
- try {
- SecurityManager localManager = new MockSecurityManager();
- System.setSecurityManager(localManager);
- assertTrue("Calling thread is trusted to bring up the top-level window",
- localManager.checkTopLevelWindow(this));
- try {
- localManager.checkTopLevelWindow(null);
- fail("Expected NullPointerexception was not thrown");
- } catch (NullPointerException e) {
- // expected
- }
- } finally {
- System.setSecurityManager(null);
- }
- //TODO AWTPermission class is unavailable
- //mutableSM.addPermission(new AllPermission());
- //assertTrue(mutableSM.checkTopLevelWindow(new Object()));
- //mutableSM.denyPermission(new AWTPermission("showWindowWithoutWarningBanner"));
- //System.setSecurityManager(mutableSM);
- //try {
- // assertFalse(mutableSM.checkTopLevelWindow(new Object()));
- //} finally {
- // System.setSecurityManager(null);
- //}
-
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkWrite",
- args = {java.io.FileDescriptor.class}
- )
- public void test_checkWriteLjava_io_FileDescriptor() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- try {
- mutableSM.checkWrite(new FileDescriptor());
- } catch(SecurityException se) {
- fail("SecurityException was thrown.");
- }
- mutableSM.denyPermission(new RuntimePermission("writeFileDescriptor"));
- System.setSecurityManager(mutableSM);
- try {
- mutableSM.checkWrite(new FileDescriptor());
- fail("This should throw a SecurityException.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(null);
- }
-
- try {
- mutableSM.checkWrite((FileDescriptor) null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkWrite",
- args = {java.lang.String.class}
- )
- public void test_checkWriteLjava_lang_String() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- try {
- mutableSM.checkWrite(writedFile);
- } catch(SecurityException se) {
- fail("SecurityException was thrown.");
- }
- mutableSM.denyPermission(new RuntimePermission("writeFileDescriptor"));
- System.setSecurityManager(mutableSM);
- try {
- mutableSM.checkWrite(writedFile);
- } catch (SecurityException e) {
- fail("Unexpected SecurityException " + e.toString());
- } finally {
- System.setSecurityManager(null);
- }
-
- try {
- SecurityManager localManager = new MockSecurityManager();
- System.setSecurityManager(localManager);
- try {
- localManager.checkWrite(writedFile);
- fail("Expected SecurityException was not thrown");
- } catch (SecurityException e) {
- // expected
- }
- } finally {
- System.setSecurityManager(null);
- }
-
- try {
- mutableSM.checkWrite((String) null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- /**
- * @tests {@link java.lang.SecurityManager#getInCheck()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInCheck",
- args = {}
- )
- public void test_getIncheck() {
- mockSM.setInCheck(false);
- assertFalse(mockSM.getInCheck());
- mockSM.setInCheck(true);
- assertTrue(mockSM.getInCheck());
- }
-
- /**
- * @tests {@link java.lang.SecurityManager#getSecurityContext()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSecurityContext",
- args = {}
- )
- @SuppressWarnings("nls")
- public void test_getSecurityContext() {
- // enable all but one check
- mutableSM.addPermission(new AllPermission());
- mutableSM.denyPermission(new FilePermission("<<ALL FILES>>", "read"));
- System.setSecurityManager(mutableSM);
- try {
- try {
- mutableSM.getSecurityContext();
- } catch(Exception e) {
- fail("Unexpected exception was thrown: " + e.toString());
- }
-
- try {
- mutableSM.checkRead("aa", mutableSM.getSecurityContext());
- fail("This should throw a SecurityException.");
- } catch (SecurityException e) {
- // expected
- }
-
- } finally {
- System.setSecurityManager(null);
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getThreadGroup",
- args = {}
- )
- public void test_getThreadGroup() throws InterruptedException {
- final ThreadGroup tgroup = new ThreadGroup(mutableSM.getThreadGroup(),
- "groupName");
- assertNotNull("Incorrect thread group", tgroup);
- class MyThread extends Thread{
- public int newCount;
-
- public MyThread() {
- super(tgroup, "threadName");
- }
-
- @Override
- public void run() {
- super.run();
- newCount = tgroup.activeCount();
- }
- }
- MyThread t = new MyThread();
- t.start();
- t.join();
- assertEquals("Incorrect active count value", 1, t.newCount);
- }
-
- /**
- * @tests {@link java.lang.SecurityManager#classDepth(String)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = ".",
- method = "classDepth",
- args = {java.lang.String.class}
- )
- @SuppressWarnings("nls")
- public void test_classDepthLjava_lang_String() {
- assertEquals(-1, mockSM.classDepth("nothing"));
- }
-
- /**
- * @tests {@link java.lang.SecurityManager#classLoaderDepth()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "classLoaderDepth",
- args = {}
- )
- public void test_classLoaderDepth() {
- assertEquals(-1, mockSM.classLoaderDepth());
- }
-
- /**
- * @tests {@link java.lang.SecurityManager#currentClassLoader()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "currentClassLoader",
- args = {}
- )
- public void test_currentClassLoader() {
- assertNull(mockSM.currentClassLoader());
- }
-
- /**
- * @tests {@link java.lang.SecurityManager#currentLoadedClass()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "currentLoadedClass",
- args = {}
- )
- public void test_currentLoadedClass() {
- assertNull(mockSM.currentLoadedClass());
- }
-
- /**
- * @tests {@link java.lang.SecurityManager#inClass(String)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "inClass",
- args = {java.lang.String.class}
- )
- @SuppressWarnings("nls")
- public void test_inClassLjava_lang_String() {
- assertFalse(mockSM.inClass("nothing"));
- assertTrue(mockSM.inClass(MockSecurityManager.class.getName()));
- }
-
- /**
- * @tests {@link java.lang.SecurityManager#inClassLoader()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "inClassLoader",
- args = {}
- )
- public void test_inClassLoader() {
- assertFalse(mockSM.inClassLoader());
- }
-
- /**
- * @tests {@link java.lang.SecurityManager#getClassContext()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getClassContext",
- args = {}
- )
- public void test_getClassContext() {
-
- Class [] stack = {MockSecurityManager.class,
- getClass(), TestCase.class};
-
- Class [] returnedStack = mockSM.getClassContext();
-
- assertNotNull(returnedStack);
- assertTrue(returnedStack.length > stack.length);
- for(int i = 0; i < stack.length; i++) {
- assertEquals(stack[i].getName() + " class should have " + i +
- " position in the classes stack, but there is " +
- returnedStack[i].getName(),
- stack[i], returnedStack[i]);
- }
- }
-
- // set some protected method to public for testing
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- mutableSM = new MutableSecurityManager();
- mockSM = new MockSecurityManager();
- originalSM = System.getSecurityManager();
- }
-
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
- System.setSecurityManager(originalSM);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ShortTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ShortTest.java
deleted file mode 100644
index 34f9958..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ShortTest.java
+++ /dev/null
@@ -1,841 +0,0 @@
-/* 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(Short.class)
-public class ShortTest extends TestCase {
- private Short sp = new Short((short) 18000);
- private Short sn = new Short((short) -19000);
-
- /**
- * @tests java.lang.Short#byteValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks boundary values.",
- method = "byteValue",
- args = {}
- )
- public void test_byteValue() {
- // Test for method byte java.lang.Short.byteValue()
- assertEquals("Returned incorrect byte value", 0, new Short(Short.MIN_VALUE)
- .byteValue());
- assertEquals("Returned incorrect byte value", -1, new Short(Short.MAX_VALUE)
- .byteValue());
- }
-
- /**
- * @tests java.lang.Short#compareTo(java.lang.Short)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.lang.Short.class}
- )
- public void test_compareToLjava_lang_Short() {
- // Test for method int java.lang.Short.compareTo(java.lang.Short)
- Short s = new Short((short) 1);
- Short x = new Short((short) 3);
- assertTrue(
- "Should have returned negative value when compared to greater short",
- s.compareTo(x) < 0);
- x = new Short((short) -1);
- assertTrue(
- "Should have returned positive value when compared to lesser short",
- s.compareTo(x) > 0);
- x = new Short((short) 1);
- assertEquals("Should have returned zero when compared to equal short",
- 0, s.compareTo(x));
-
- try {
- new Short((short)0).compareTo(null);
- fail("No NPE");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @tests java.lang.Short#decode(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Doesn't check that no whitespace characters are permitted in the String. ",
- method = "decode",
- args = {java.lang.String.class}
- )
- public void test_decodeLjava_lang_String2() {
- // Test for method java.lang.Short
- // java.lang.Short.decode(java.lang.String)
- assertTrue("Did not decode -1 correctly", Short.decode("-1")
- .shortValue() == (short) -1);
- assertTrue("Did not decode -100 correctly", Short.decode("-100")
- .shortValue() == (short) -100);
- assertTrue("Did not decode 23 correctly", Short.decode("23")
- .shortValue() == (short) 23);
- assertTrue("Did not decode 0x10 correctly", Short.decode("0x10")
- .shortValue() == (short) 16);
- assertTrue("Did not decode 32767 correctly", Short.decode("32767")
- .shortValue() == (short) 32767);
- assertTrue("Did not decode -32767 correctly", Short.decode("-32767")
- .shortValue() == (short) -32767);
- assertTrue("Did not decode -32768 correctly", Short.decode("-32768")
- .shortValue() == (short) -32768);
-
- boolean exception = false;
- try {
- Short.decode("123s");
- } catch (NumberFormatException e) {
- // correct
- exception = true;
- }
- assertTrue("Did not throw NumberFormatException decoding 123s",
- exception);
-
- exception = false;
- try {
- Short.decode("32768");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
-
- exception = false;
- try {
- Short.decode("-32769");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
-
- exception = false;
- try {
- Short.decode("0x8000");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for hex MAX_VALUE + 1", exception);
-
- exception = false;
- try {
- Short.decode("-0x8001");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for hex MIN_VALUE - 1", exception);
- }
-
- /**
- * @tests java.lang.Short#parseShort(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "parseShort",
- args = {java.lang.String.class}
- )
- public void test_parseShortLjava_lang_String2() {
- // Test for method short java.lang.Short.parseShort(java.lang.String)
- short sp = Short.parseShort("32746");
- short sn = Short.parseShort("-32746");
-
- assertTrue("Incorrect parse of short", sp == (short) 32746
- && (sn == (short) -32746));
- assertEquals("Returned incorrect value for 0", 0, Short.parseShort("0"));
- assertTrue("Returned incorrect value for most negative value", Short
- .parseShort("-32768") == (short) 0x8000);
- assertTrue("Returned incorrect value for most positive value", Short
- .parseShort("32767") == 0x7fff);
-
- boolean exception = false;
- try {
- Short.parseShort("32768");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
-
- exception = false;
- try {
- Short.parseShort("-32769");
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
- }
-
- /**
- * @tests java.lang.Short#parseShort(java.lang.String, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "parseShort",
- args = {java.lang.String.class, int.class}
- )
- public void test_parseShortLjava_lang_StringI2() {
- // Test for method short java.lang.Short.parseShort(java.lang.String,
- // int)
- boolean aThrow = true;
- assertEquals("Incorrectly parsed hex string",
- 255, Short.parseShort("FF", 16));
- assertEquals("Incorrectly parsed oct string",
- 16, Short.parseShort("20", 8));
- assertEquals("Incorrectly parsed dec string",
- 20, Short.parseShort("20", 10));
- assertEquals("Incorrectly parsed bin string",
- 4, Short.parseShort("100", 2));
- assertEquals("Incorrectly parsed -hex string", -255, Short
- .parseShort("-FF", 16));
- assertEquals("Incorrectly parsed -oct string",
- -16, Short.parseShort("-20", 8));
- assertEquals("Incorrectly parsed -bin string", -4, Short
- .parseShort("-100", 2));
- assertEquals("Returned incorrect value for 0 hex", 0, Short.parseShort("0",
- 16));
- assertTrue("Returned incorrect value for most negative value hex",
- Short.parseShort("-8000", 16) == (short) 0x8000);
- assertTrue("Returned incorrect value for most positive value hex",
- Short.parseShort("7fff", 16) == 0x7fff);
- assertEquals("Returned incorrect value for 0 decimal", 0, Short.parseShort(
- "0", 10));
- assertTrue("Returned incorrect value for most negative value decimal",
- Short.parseShort("-32768", 10) == (short) 0x8000);
- assertTrue("Returned incorrect value for most positive value decimal",
- Short.parseShort("32767", 10) == 0x7fff);
-
- try {
- Short.parseShort("FF", 2);
- } catch (NumberFormatException e) {
- // Correct
- aThrow = false;
- }
- if (aThrow) {
- fail(
- "Failed to throw exception when passed hex string and base 2 radix");
- }
-
- boolean exception = false;
- try {
- Short.parseShort("10000000000", 10);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue(
- "Failed to throw exception when passed string larger than 16 bits",
- exception);
-
- exception = false;
- try {
- Short.parseShort("32768", 10);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MAX_VALUE + 1", exception);
-
- exception = false;
- try {
- Short.parseShort("-32769", 10);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for MIN_VALUE - 1", exception);
-
- exception = false;
- try {
- Short.parseShort("8000", 16);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for hex MAX_VALUE + 1", exception);
-
- exception = false;
- try {
- Short.parseShort("-8001", 16);
- } catch (NumberFormatException e) {
- // Correct
- exception = true;
- }
- assertTrue("Failed to throw exception for hex MIN_VALUE + 1", exception);
- }
-
- /**
- * @tests java.lang.Short#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString2() {
- // Test for method java.lang.String java.lang.Short.toString()
- assertTrue("Invalid string returned", sp.toString().equals("18000")
- && (sn.toString().equals("-19000")));
- assertEquals("Returned incorrect string", "32767", new Short((short) 32767)
- .toString());
- assertEquals("Returned incorrect string", "-32767", new Short((short) -32767)
- .toString());
- assertEquals("Returned incorrect string", "-32768", new Short((short) -32768)
- .toString());
- }
-
- /**
- * @tests java.lang.Short#toString(short)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "toString",
- args = {short.class}
- )
- public void test_toStringS2() {
- // Test for method java.lang.String java.lang.Short.toString(short)
- assertEquals("Returned incorrect string", "32767", Short.toString((short) 32767)
- );
- assertEquals("Returned incorrect string", "-32767", Short.toString((short) -32767)
- );
- assertEquals("Returned incorrect string", "-32768", Short.toString((short) -32768)
- );
- }
-
- /**
- * @tests java.lang.Short#valueOf(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks boundary values.",
- method = "valueOf",
- args = {java.lang.String.class}
- )
- public void test_valueOfLjava_lang_String2() {
- // Test for method java.lang.Short
- // java.lang.Short.valueOf(java.lang.String)
- assertEquals("Returned incorrect short", -32768, Short.valueOf("-32768")
- .shortValue());
- assertEquals("Returned incorrect short", 32767, Short.valueOf("32767")
- .shortValue());
- }
-
- /**
- * @tests java.lang.Short#valueOf(java.lang.String, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {java.lang.String.class, int.class}
- )
- public void test_valueOfLjava_lang_StringI2() {
- // Test for method java.lang.Short
- // java.lang.Short.valueOf(java.lang.String, int)
- boolean aThrow = true;
- assertEquals("Incorrectly parsed hex string", 255, Short.valueOf("FF", 16)
- .shortValue());
- assertEquals("Incorrectly parsed oct string", 16, Short.valueOf("20", 8)
- .shortValue());
- assertEquals("Incorrectly parsed dec string", 20, Short.valueOf("20", 10)
- .shortValue());
- assertEquals("Incorrectly parsed bin string", 4, Short.valueOf("100", 2)
- .shortValue());
- assertEquals("Incorrectly parsed -hex string", -255, Short.valueOf("-FF", 16)
- .shortValue());
- assertEquals("Incorrectly parsed -oct string", -16, Short.valueOf("-20", 8)
- .shortValue());
- assertEquals("Incorrectly parsed -bin string", -4, Short.valueOf("-100", 2)
- .shortValue());
- assertTrue("Did not decode 32767 correctly", Short.valueOf("32767", 10)
- .shortValue() == (short) 32767);
- assertTrue("Did not decode -32767 correctly", Short.valueOf("-32767",
- 10).shortValue() == (short) -32767);
- assertTrue("Did not decode -32768 correctly", Short.valueOf("-32768",
- 10).shortValue() == (short) -32768);
- try {
- Short.valueOf("FF", 2);
- } catch (NumberFormatException e) {
- // Correct
- aThrow = false;
- }
- if (aThrow) {
- fail(
- "Failed to throw exception when passed hex string and base 2 radix");
- }
- try {
- Short.valueOf("10000000000", 10);
- } catch (NumberFormatException e) {
- // Correct
- return;
- }
- fail(
- "Failed to throw exception when passed string larger than 16 bits");
- }
- /**
- * @tests java.lang.Short#valueOf(short)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {short.class}
- )
- public void test_valueOfS() {
- assertEquals(new Short(Short.MIN_VALUE), Short.valueOf(Short.MIN_VALUE));
- assertEquals(new Short(Short.MAX_VALUE), Short.valueOf(Short.MAX_VALUE));
- assertEquals(new Short((short) 0), Short.valueOf((short) 0));
-
- short s = -128;
- while (s < 128) {
- assertEquals(new Short(s), Short.valueOf(s));
- assertSame(Short.valueOf(s), Short.valueOf(s));
- s++;
- }
- }
-
- /**
- * @tests java.lang.Short#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- assertEquals(1, new Short((short)1).hashCode());
- assertEquals(2, new Short((short)2).hashCode());
- assertEquals(0, new Short((short)0).hashCode());
- assertEquals(-1, new Short((short)-1).hashCode());
- }
-
- /**
- * @tests java.lang.Short#Short(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Short",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- assertEquals(new Short((short)0), new Short("0"));
- assertEquals(new Short((short)1), new Short("1"));
- assertEquals(new Short((short)-1), new Short("-1"));
-
- try {
- new Short("0x1");
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {}
-
- try {
- new Short("9.2");
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {}
-
- try {
- new Short("");
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {}
-
- try {
- new Short(null);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {}
- }
-
- /**
- * @tests java.lang.Short#Short(short)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Short",
- args = {short.class}
- )
- public void test_ConstructorS() {
- assertEquals(1, new Short((short)1).shortValue());
- assertEquals(2, new Short((short)2).shortValue());
- assertEquals(0, new Short((short)0).shortValue());
- assertEquals(-1, new Short((short)-1).shortValue());
- }
-
- /**
- * @tests java.lang.Short#byteValue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't check boundary values.",
- method = "byteValue",
- args = {}
- )
- public void test_byteValue1() {
- assertEquals(1, new Short((short)1).byteValue());
- assertEquals(2, new Short((short)2).byteValue());
- assertEquals(0, new Short((short)0).byteValue());
- assertEquals(-1, new Short((short)-1).byteValue());
- }
-
- /**
- * @tests java.lang.Short#equals(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- assertEquals(new Short((short)0), Short.valueOf((short)0));
- assertEquals(new Short((short)1), Short.valueOf((short)1));
- assertEquals(new Short((short)-1), Short.valueOf((short)-1));
-
- Short fixture = new Short((short)25);
- assertEquals(fixture, fixture);
- assertFalse(fixture.equals(null));
- assertFalse(fixture.equals("Not a Short"));
- }
-
- /**
- * @tests java.lang.Short#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- assertEquals("-1", new Short((short)-1).toString());
- assertEquals("0", new Short((short)0).toString());
- assertEquals("1", new Short((short)1).toString());
- assertEquals("-1", new Short((short)0xFFFF).toString());
- }
-
- /**
- * @tests java.lang.Short#toString(short)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "toString",
- args = {short.class}
- )
- public void test_toStringS() {
- assertEquals("-1", Short.toString((short)-1));
- assertEquals("0", Short.toString((short)0));
- assertEquals("1", Short.toString((short)1));
- assertEquals("-1", Short.toString((short)0xFFFF));
- }
-
- /**
- * @tests java.lang.Short#valueOf(String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't check boundary values.",
- method = "valueOf",
- args = {java.lang.String.class}
- )
- public void test_valueOfLjava_lang_String() {
- assertEquals(new Short((short)0), Short.valueOf("0"));
- assertEquals(new Short((short)1), Short.valueOf("1"));
- assertEquals(new Short((short)-1), Short.valueOf("-1"));
-
- try {
- Short.valueOf("0x1");
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {}
-
- try {
- Short.valueOf("9.2");
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {}
-
- try {
- Short.valueOf("");
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {}
-
- try {
- Short.valueOf(null);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {}
- }
-
- /**
- * @tests java.lang.Short#valueOf(String,int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {java.lang.String.class, int.class}
- )
- public void test_valueOfLjava_lang_StringI() {
- assertEquals(new Short((short)0), Short.valueOf("0", 10));
- assertEquals(new Short((short)1), Short.valueOf("1", 10));
- assertEquals(new Short((short)-1), Short.valueOf("-1", 10));
-
- //must be consistent with Character.digit()
- assertEquals(Character.digit('1', 2), Short.valueOf("1", 2).byteValue());
- assertEquals(Character.digit('F', 16), Short.valueOf("F", 16).byteValue());
-
- try {
- Short.valueOf("0x1", 10);
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {}
-
- try {
- Short.valueOf("9.2", 10);
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {}
-
- try {
- Short.valueOf("", 10);
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {}
-
- try {
- Short.valueOf(null, 10);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {}
- }
-
- /**
- * @tests java.lang.Short#parseShort(String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Doesn't check boundary values, unicodes.",
- method = "parseShort",
- args = {java.lang.String.class}
- )
- public void test_parseShortLjava_lang_String() {
- assertEquals(0, Short.parseShort("0"));
- assertEquals(1, Short.parseShort("1"));
- assertEquals(-1, Short.parseShort("-1"));
-
- try {
- Short.parseShort("0x1");
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {}
-
- try {
- Short.parseShort("9.2");
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {}
-
- try {
- Short.parseShort("");
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {}
-
- try {
- Short.parseShort(null);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {}
- }
-
- /**
- * @tests java.lang.Short#parseShort(String,int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Doesn't check boundary values.",
- method = "parseShort",
- args = {java.lang.String.class, int.class}
- )
- public void test_parseShortLjava_lang_StringI() {
- assertEquals(0, Short.parseShort("0", 10));
- assertEquals(1, Short.parseShort("1", 10));
- assertEquals(-1, Short.parseShort("-1", 10));
-
- //must be consistent with Character.digit()
- assertEquals(Character.digit('1', 2), Short.parseShort("1", 2));
- assertEquals(Character.digit('F', 16), Short.parseShort("F", 16));
-
- try {
- Short.parseShort("0x1", 10);
- fail("Expected NumberFormatException with hex string.");
- } catch (NumberFormatException e) {}
-
- try {
- Short.parseShort("9.2", 10);
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {}
-
- try {
- Short.parseShort("", 10);
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {}
-
- try {
- Short.parseShort(null, 10);
- fail("Expected NumberFormatException with null string.");
- } catch (NumberFormatException e) {}
- }
-
- /**
- * @tests java.lang.Short#decode(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "decode",
- args = {java.lang.String.class}
- )
- public void test_decodeLjava_lang_String() {
- assertEquals(new Short((short)0), Short.decode("0"));
- assertEquals(new Short((short)1), Short.decode("1"));
- assertEquals(new Short((short)-1), Short.decode("-1"));
- assertEquals(new Short((short)0xF), Short.decode("0xF"));
- assertEquals(new Short((short)0xF), Short.decode("#F"));
- assertEquals(new Short((short)0xF), Short.decode("0XF"));
- assertEquals(new Short((short)07), Short.decode("07"));
-
- try {
- Short.decode(" 0 ");
- fail("NumberFormatException is not thrown.");
- } catch(NumberFormatException nfe) {
- //expected
- }
-
- try {
- Short.decode("9.2");
- fail("Expected NumberFormatException with floating point string.");
- } catch (NumberFormatException e) {}
-
- try {
- Short.decode("");
- fail("Expected NumberFormatException with empty string.");
- } catch (NumberFormatException e) {}
-
- try {
- Short.decode(null);
- //undocumented NPE, but seems consistent across JREs
- fail("Expected NullPointerException with null string.");
- } catch (NullPointerException e) {}
- }
-
- /**
- * @tests java.lang.Short#doubleValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "doubleValue",
- args = {}
- )
- public void test_doubleValue() {
- assertEquals(-1D, new Short((short)-1).doubleValue(), 0D);
- assertEquals(0D, new Short((short)0).doubleValue(), 0D);
- assertEquals(1D, new Short((short)1).doubleValue(), 0D);
- }
-
- /**
- * @tests java.lang.Short#floatValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "floatValue",
- args = {}
- )
- public void test_floatValue() {
- assertEquals(-1F, new Short((short)-1).floatValue(), 0F);
- assertEquals(0F, new Short((short)0).floatValue(), 0F);
- assertEquals(1F, new Short((short)1).floatValue(), 0F);
- }
-
- /**
- * @tests java.lang.Short#intValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "intValue",
- args = {}
- )
- public void test_intValue() {
- assertEquals(-1, new Short((short)-1).intValue());
- assertEquals(0, new Short((short)0).intValue());
- assertEquals(1, new Short((short)1).intValue());
- }
-
- /**
- * @tests java.lang.Short#longValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "longValue",
- args = {}
- )
- public void test_longValue() {
- assertEquals(-1L, new Short((short)-1).longValue());
- assertEquals(0L, new Short((short)0).longValue());
- assertEquals(1L, new Short((short)1).longValue());
- }
-
- /**
- * @tests java.lang.Short#shortValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "shortValue",
- args = {}
- )
- public void test_shortValue() {
- assertEquals(-1, new Short((short)-1).shortValue());
- assertEquals(0, new Short((short)0).shortValue());
- assertEquals(1, new Short((short)1).shortValue());
- }
-
- /**
- * @tests java.lang.Short#reverseBytes(short)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reverseBytes",
- args = {short.class}
- )
- public void test_reverseBytesS() {
- assertEquals((short)0xABCD, Short.reverseBytes((short)0xCDAB));
- assertEquals((short)0x1234, Short.reverseBytes((short)0x3412));
- assertEquals((short)0x0011, Short.reverseBytes((short)0x1100));
- assertEquals((short)0x2002, Short.reverseBytes((short)0x0220));
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StackOverflowErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StackOverflowErrorTest.java
deleted file mode 100644
index 009349f..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StackOverflowErrorTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(StackOverflowError.class)
-public class StackOverflowErrorTest extends TestCase {
-
- /**
- * @tests java.lang.StackOverflowError#StackOverflowError()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StackOverflowError",
- args = {}
- )
- public void test_Constructor() {
- StackOverflowError e = new StackOverflowError();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.StackOverflowError#StackOverflowError(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StackOverflowError",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- StackOverflowError e = new StackOverflowError("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StackTraceElementOriginal.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StackTraceElementOriginal.java
deleted file mode 100644
index 1bbe8c5..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StackTraceElementOriginal.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargetClass;
-import junit.framework.TestCase;
-
-@TestTargetClass(StackTraceElement.class)
-public class StackTraceElementOriginal extends TestCase {
-
- public void pureJavaMethod(Object test) throws Exception {
- throw new Exception("pure java method");
- }
-
- native public void pureNativeMethod(Object test);
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StackTraceElementTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StackTraceElementTest.java
deleted file mode 100644
index 2995d44..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StackTraceElementTest.java
+++ /dev/null
@@ -1,285 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(StackTraceElement.class)
-public class StackTraceElementTest extends TestCase {
- private StackTraceElementOriginal original;
-
- @Override
- protected void setUp() throws Exception {
- original = new StackTraceElementOriginal();
- super.setUp();
- }
-
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- /**
- * @tests java.lang.StackTraceElement#StackTraceElement(java.lang.String,
- * java.lang.String, java.lang.String, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StackTraceElement",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, int.class}
- )
- public void
- test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_StringI() {
- StackTraceElement ste2 = null;
- try {
- original.pureJavaMethod(new Object());
- } catch (Exception e) {
- StackTraceElement ste1 = e.getStackTrace()[0];
- ste2 = new StackTraceElement(ste1.getClassName(),
- ste1.getMethodName(),
- ste1.getFileName(),
- ste1.getLineNumber());
- assertEquals("Incorrect value of class name",
- ste1.getClassName(), ste2.getClassName());
- assertEquals("Incorrect value of method name",
- ste1.getMethodName(), ste2.getMethodName());
- assertEquals("Incorrect value of file name",
- ste1.getFileName(), ste2.getFileName());
- assertEquals("Incorrect value of line number",
- ste1.getLineNumber(), ste2.getLineNumber());
- }
- assertNotNull("Incorrect stack trace object", ste2);
- try {
- new StackTraceElement(null,
- ste2.getMethodName(),
- ste2.getFileName(),
- ste2.getLineNumber());
- fail("Expected NullPointerException was not thrown");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- new StackTraceElement(ste2.getClassName(),
- null,
- ste2.getFileName(),
- ste2.getLineNumber());
- fail("Expected NullPointerException was not thrown");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- new StackTraceElement(ste2.getClassName(),
- ste2.getMethodName(),
- null,
- ste2.getLineNumber());
- } catch (NullPointerException e) {
- fail("Unexpected exception " + e.toString());
- }
- }
-
- /**
- * @tests java.lang.StackTraceElement#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- try {
- original.pureJavaMethod(new Object());
- } catch (Exception e) {
- StackTraceElement ste1 = e.getStackTrace()[0];
- StackTraceElement ste2 =
- new StackTraceElement(ste1.getClassName(),
- ste1.getMethodName(),
- ste1.getFileName(),
- ste1.getLineNumber());
- assertEquals("Objects are equaled", ste1, ste2);
- }
- }
-
- /**
- * @tests java.lang.StackTraceElement#getClassName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getClassName",
- args = {}
- )
- public void test_getClassName() {
- try {
- original.pureJavaMethod(new Object());
- } catch (Exception e) {
- assertEquals("Incorrect class name",
- getClass().getPackage().getName() +
- ".StackTraceElementOriginal",
- e.getStackTrace()[0].getClassName());
- assertEquals("Incorrect class name",
- getClass().getPackage().getName() +
- ".StackTraceElementTest",
- e.getStackTrace()[1].getClassName());
- }
- }
-
- /**
- * @tests java.lang.StackTraceElement#getFileName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFileName",
- args = {}
- )
- public void test_getFileName() {
- try {
- original.pureJavaMethod(new Object());
- } catch (Exception e) {
- assertEquals("Incorrect file name",
- "StackTraceElementOriginal.java",
- e.getStackTrace()[0].getFileName());
- assertEquals("Incorrect file name",
- "StackTraceElementTest.java",
- e.getStackTrace()[1].getFileName());
- }
- }
-
- /**
- * @tests java.lang.StackTraceElement#getLineNumber()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLineNumber",
- args = {}
- )
- public void test_getLineNumber() {
- try {
- original.pureJavaMethod(new Object());
- } catch (Exception e) {
- assertEquals("Incorrect line number",
- 26, e.getStackTrace()[0].getLineNumber());
- }
- }
-
- /**
- * @tests java.lang.StackTraceElement#getMethodName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMethodName",
- args = {}
- )
- public void test_getMethodName() {
- try {
- original.pureJavaMethod(new Object());
- } catch (Exception e) {
- assertEquals("Incorrect method name",
- "pureJavaMethod",
- e.getStackTrace()[0].getMethodName());
- assertEquals("Incorrect method name",
- "test_getMethodName",
- e.getStackTrace()[1].getMethodName());
- }
- }
-
- /**
- * @tests java.lang.StackTraceElement#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- try {
- original.pureJavaMethod(new Object());
- } catch (Exception e) {
- StackTraceElement ste1 = e.getStackTrace()[0];
- StackTraceElement ste2 =
- new StackTraceElement(ste1.getClassName(),
- ste1.getMethodName(),
- ste1.getFileName(),
- ste1.getLineNumber());
- assertEquals("Incorrect value of hash code",
- ste1.hashCode(), ste2.hashCode());
- assertFalse("Incorrect value of hash code",
- ste1.hashCode() == e.getStackTrace()[1].hashCode());
- }
- }
-
- /**
- * @tests java.lang.StackTraceElement#isNativeMethod()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isNativeMethod",
- args = {}
- )
- public void test_isNativeMethod() {
- try {
- original.pureJavaMethod(new Object());
- } catch (Exception e) {
- assertFalse("Incorrect method type",
- e.getStackTrace()[0].isNativeMethod());
- }
- try {
- original.pureNativeMethod(new Object());
- } catch (Error e) {
- assertTrue("Incorrect method type",
- e.getStackTrace()[0].isNativeMethod());
- }
- }
-
- /**
- * @tests java.lang.StackTraceElement#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- try {
- original.pureJavaMethod(new Object());
- } catch (Exception e) {
- StackTraceElement ste = e.getStackTrace()[0];
- assertTrue("String representation doesn't contain a package name",
- ste.toString().contains(getClass().getPackage().getName()));
- assertTrue("String representation doesn't contain a class name",
- ste.toString().contains("StackTraceElementOriginal"));
- assertTrue("String representation doesn't contain a file name",
- ste.toString().contains("StackTraceElementOriginal.java"));
- assertTrue("String representation doesn't contain a line number",
- ste.toString().contains("26"));
- assertTrue("String representation doesn't contain a method name",
- ste.toString().contains("pureJavaMethod"));
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StrictMathTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StrictMathTest.java
deleted file mode 100644
index 0a811ef..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StrictMathTest.java
+++ /dev/null
@@ -1,1462 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(StrictMath.class)
-public class StrictMathTest extends junit.framework.TestCase {
-
- double HYP = StrictMath.sqrt(2.0);
-
- double OPP = 1.0;
-
- double ADJ = 1.0;
-
- /* Required to make previous preprocessor flags work - do not remove */
- int unused = 0;
-
- /**
- * @tests java.lang.StrictMath#pow(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "pow",
- args = {double.class, double.class}
- )
- public void test_pow() {
- // tests changes in fdlibm5.3
- assertTrue(Double.longBitsToDouble(-4610068591539890326L) ==
- StrictMath.pow(-1.0000000000000002e+00,4.5035996273704970e+15));
- assertTrue(Double.longBitsToDouble( 4601023824101950163L) ==
- StrictMath.pow(-9.9999999999999978e-01,4.035996273704970e+15));
-
- assertEquals("Incorrect value was returned.", 1.0,
- StrictMath.pow(Double.MAX_VALUE, 0.0));
- assertEquals("Incorrect value was returned.", 1.0,
- StrictMath.pow(Double.MAX_VALUE, -0.0));
- assertEquals("Incorrect value was returned.", Double.NaN,
- StrictMath.pow(Double.MAX_VALUE, Double.NaN));
- assertEquals("Incorrect value was returned.", Double.NaN,
- StrictMath.pow(Double.NaN, 1.0));
- assertEquals("Incorrect value was returned.", Double.POSITIVE_INFINITY,
- StrictMath.pow(1.1, Double.POSITIVE_INFINITY));
- assertEquals("Incorrect value was returned.", Double.POSITIVE_INFINITY,
- StrictMath.pow(0.9, Double.NEGATIVE_INFINITY));
-
- assertEquals("Incorrect value was returned.", 0.0,
- StrictMath.pow(1.1, Double.NEGATIVE_INFINITY));
- assertEquals("Incorrect value was returned.", 0.0,
- StrictMath.pow(0.9, Double.POSITIVE_INFINITY));
-
- assertEquals("Incorrect value was returned.", Double.NaN,
- StrictMath.pow(-1.0, Double.POSITIVE_INFINITY));
- assertEquals("Incorrect value was returned.", Double.NaN,
- StrictMath.pow(1.0, Double.NEGATIVE_INFINITY));
-
- assertEquals("Incorrect value was returned.", 0.0,
- StrictMath.pow(0.0, 1.1));
- assertEquals("Incorrect value was returned.", 0.0,
- StrictMath.pow(Double.POSITIVE_INFINITY, -1.0));
-
- assertEquals("Incorrect value was returned.", 0.0,
- StrictMath.pow(-0.0, 1.1));
- assertEquals("Incorrect value was returned.", 0.0,
- StrictMath.pow(Double.POSITIVE_INFINITY, -1.0));
-
- assertEquals("Incorrect value was returned.", Double.POSITIVE_INFINITY,
- StrictMath.pow(0.0, -1.0));
- assertEquals("Incorrect value was returned.", Double.POSITIVE_INFINITY,
- StrictMath.pow(Double.POSITIVE_INFINITY, 1.0));
-
- assertEquals("Incorrect value was returned.", 0.0,
- StrictMath.pow(-0.0, 2.0));
- assertEquals("Incorrect value was returned.", 0.0,
- StrictMath.pow(Double.NEGATIVE_INFINITY, -2.0));
-
- assertEquals("Incorrect value was returned.", -0.0,
- StrictMath.pow(-0.0, 1.0));
- assertEquals("Incorrect value was returned.", -0.0,
- StrictMath.pow(Double.NEGATIVE_INFINITY, -1.0));
-
- assertEquals("Incorrect value was returned.", Double.POSITIVE_INFINITY,
- StrictMath.pow(-0.0, -2.0));
- assertEquals("Incorrect value was returned.", Double.POSITIVE_INFINITY,
- StrictMath.pow(Double.NEGATIVE_INFINITY, 2.0));
-
- assertEquals("Incorrect value was returned.", Double.NEGATIVE_INFINITY,
- StrictMath.pow(-0.0, -1.0));
- assertEquals("Incorrect value was returned.", Double.NEGATIVE_INFINITY,
- StrictMath.pow(Double.NEGATIVE_INFINITY, 1.0));
-
- assertEquals("Incorrect value was returned.", -0.999,
- StrictMath.pow(-0.999, 1.0));
-
- assertEquals("Incorrect value was returned.", Double.NaN,
- StrictMath.pow(-0.999, 1.1));
- }
-
- /**
- * @tests java.lang.StrictMath#tan(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "tan",
- args = {double.class}
- )
- public void test_tan(){
- // tests changes in fdlibm5.3
- assertTrue(Double.longBitsToDouble( 4850236541654588678L) == StrictMath.tan( 1.7765241907548024E+269));
- assertEquals("Incorrect value of tan was returned.",
- Double.NaN, StrictMath.tan(Double.NaN));
- assertEquals("Incorrect value of tan was returned.",
- Double.NaN, StrictMath.tan(Double.POSITIVE_INFINITY));
- assertEquals("Incorrect value of tan was returned.",
- Double.NaN, StrictMath.tan(Double.NEGATIVE_INFINITY));
- assertEquals("Incorrect value of tan was returned.",
- 0.0, StrictMath.tan(0.0));
- assertEquals("Incorrect value of tan was returned.",
- -0.0, StrictMath.tan(-0.0));
- }
-
- /**
- * @tests java.lang.StrictMath#asin(double)
- * @tests java.lang.StrictMath#exp(double)
- * @tests java.lang.StrictMath#sinh(double)
- * @tests java.lang.StrictMath#expm1(double)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Checks one value.",
- method = "asin",
- args = {double.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Checks one value.",
- method = "exp",
- args = {double.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Checks one value.",
- method = "sinh",
- args = {double.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Checks one value.",
- method = "expm1",
- args = {double.class}
- )
- })
- public void test_inexact(){
- assertTrue( 4485585228743840298L == Double.doubleToRawLongBits(StrictMath.asin(7.4505805E-9)));
- assertTrue( 4607182418816794624L == Double.doubleToRawLongBits(StrictMath.exp(3.7252902E-9)));
- assertTrue( 4481081628995577220L == Double.doubleToRawLongBits(StrictMath.sinh(3.7252902E-9)));
- assertTrue(-4616189618054758400L == Double.doubleToRawLongBits(StrictMath.expm1(-40)));
- }
-
- /**
- * @tests java.lang.StrictMath#abs(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "abs",
- args = {double.class}
- )
- public void test_absD() {
- // Test for method double java.lang.StrictMath.abs(double)
-
- assertTrue("Incorrect double abs value",
- (StrictMath.abs(-1908.8976) == 1908.8976));
- assertTrue("Incorrect double abs value",
- (StrictMath.abs(1908.8976) == 1908.8976));
-
- assertEquals(0.0, StrictMath.abs(0.0));
- assertEquals(0.0, StrictMath.abs(-0.0));
- assertEquals(Double.POSITIVE_INFINITY, StrictMath.abs(Double.POSITIVE_INFINITY));
- assertEquals(Double.POSITIVE_INFINITY, StrictMath.abs(Double.NEGATIVE_INFINITY));
- assertEquals(Double.NaN, StrictMath.abs(Double.NaN));
- }
-
- /**
- * @tests java.lang.StrictMath#abs(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "abs",
- args = {float.class}
- )
- public void test_absF() {
- // Test for method float java.lang.StrictMath.abs(float)
- assertTrue("Incorrect float abs value",
- (StrictMath.abs(-1908.8976f) == 1908.8976f));
- assertTrue("Incorrect float abs value",
- (StrictMath.abs(1908.8976f) == 1908.8976f));
-
- assertEquals(0f, StrictMath.abs(0f));
- assertEquals(0f, StrictMath.abs(-0f));
- assertEquals(Float.POSITIVE_INFINITY, StrictMath.abs(Float.POSITIVE_INFINITY));
- assertEquals(Float.POSITIVE_INFINITY, StrictMath.abs(Float.NEGATIVE_INFINITY));
- assertEquals(Float.NaN, StrictMath.abs(Float.NaN));
- }
-
- /**
- * @tests java.lang.StrictMath#abs(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "abs",
- args = {int.class}
- )
- public void test_absI() {
- // Test for method int java.lang.StrictMath.abs(int)
- assertTrue("Incorrect int abs value",
- (StrictMath.abs(-1908897) == 1908897));
- assertTrue("Incorrect int abs value",
- (StrictMath.abs(1908897) == 1908897));
-
- assertEquals(Integer.MIN_VALUE, StrictMath.abs(Integer.MIN_VALUE));
- }
-
- /**
- * @tests java.lang.StrictMath#abs(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "abs",
- args = {long.class}
- )
- public void test_absJ() {
- // Test for method long java.lang.StrictMath.abs(long)
- assertTrue("Incorrect long abs value", (StrictMath
- .abs(-19088976000089L) == 19088976000089L));
- assertTrue("Incorrect long abs value",
- (StrictMath.abs(19088976000089L) == 19088976000089L));
-
- assertEquals(Long.MIN_VALUE, StrictMath.abs(Long.MIN_VALUE));
- }
-
- /**
- * @tests java.lang.StrictMath#acos(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "acos",
- args = {double.class}
- )
- public void test_acosD() {
- // Test for method double java.lang.StrictMath.acos(double)
- assertTrue("Returned incorrect arc cosine", StrictMath.cos(StrictMath
- .acos(ADJ / HYP)) == ADJ / HYP);
-
- assertEquals(Double.NaN, StrictMath.acos(Double.NaN));
- assertEquals(Double.NaN, StrictMath.acos(1.1));
- }
-
- /**
- * @tests java.lang.StrictMath#asin(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "asin",
- args = {double.class}
- )
- public void test_asinD() {
- // Test for method double java.lang.StrictMath.asin(double)
- assertTrue("Returned incorrect arc sine", StrictMath.sin(StrictMath
- .asin(OPP / HYP)) == OPP / HYP);
-
- assertEquals(Double.NaN, StrictMath.asin(Double.NaN));
- assertEquals(Double.NaN, StrictMath.asin(1.1));
- assertEquals(0.0, StrictMath.asin(0.0));
- assertEquals(-0.0, StrictMath.asin(-0.0));
- }
-
- /**
- * @tests java.lang.StrictMath#atan(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Doesn't check boundary values.",
- method = "atan",
- args = {double.class}
- )
- public void test_atanD() {
- // Test for method double java.lang.StrictMath.atan(double)
- double answer = StrictMath.tan(StrictMath.atan(1.0));
- assertTrue("Returned incorrect arc tangent: " + answer, answer <= 1.0
- && answer >= 9.9999999999999983E-1);
- }
-
- /**
- * @tests java.lang.StrictMath#atan2(double, double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "atan2",
- args = {double.class, double.class}
- )
- public void test_atan2DD() {
- // Test for method double java.lang.StrictMath.atan2(double, double)
- double answer = StrictMath.atan(StrictMath.tan(1.0));
- assertTrue("Returned incorrect arc tangent: " + answer, answer <= 1.0
- && answer >= 9.9999999999999983E-1);
-
- assertEquals(Double.NaN, StrictMath.atan2(Double.NaN, 1.0));
- assertEquals(Double.NaN, StrictMath.atan2(Double.NaN, 1.0));
-
- assertEquals(0.0, StrictMath.atan2(0.0, 1.0));
- assertEquals(0.0, StrictMath.atan2(1.0, Double.POSITIVE_INFINITY));
-
- assertEquals(-0.0, StrictMath.atan2(-0.0, 1.0));
- assertEquals(-0.0, StrictMath.atan2(-1.0, Double.POSITIVE_INFINITY));
-
- assertEquals(StrictMath.PI, StrictMath.atan2(0.0, -1.0));
- assertEquals(StrictMath.PI, StrictMath.atan2(1.0,
- Double.NEGATIVE_INFINITY));
-
- assertEquals(-StrictMath.PI, StrictMath.atan2(-0.0, -1.0));
- assertEquals(-StrictMath.PI, StrictMath.atan2(-1.0,
- Double.NEGATIVE_INFINITY));
-
- assertEquals(StrictMath.PI/2, StrictMath.atan2(1.0, 0.0));
- assertEquals(StrictMath.PI/2, StrictMath.atan2(1.0, -0.0));
- assertEquals(StrictMath.PI/2, StrictMath.atan2(Double.POSITIVE_INFINITY, 0.0));
-
- assertEquals(-StrictMath.PI/2, StrictMath.atan2(-1.0, 0.0));
- assertEquals(-StrictMath.PI/2, StrictMath.atan2(-1.0, -0.0));
- assertEquals(-StrictMath.PI/2, StrictMath.atan2(Double.NEGATIVE_INFINITY, 1.0));
-
- assertEquals(StrictMath.PI/4, StrictMath.atan2(Double.POSITIVE_INFINITY,
- Double.POSITIVE_INFINITY));
- assertEquals(3*StrictMath.PI/4,
- StrictMath.atan2(Double.POSITIVE_INFINITY,
- Double.NEGATIVE_INFINITY));
-
- assertEquals(-StrictMath.PI/4,
- StrictMath.atan2(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY));
-
- assertEquals(-3*StrictMath.PI/4,
- StrictMath.atan2(Double.NEGATIVE_INFINITY,
- Double.NEGATIVE_INFINITY));
- }
-
- /**
- * @tests java.lang.StrictMath#cbrt(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "cbrt",
- args = {double.class}
- )
- @SuppressWarnings("boxing")
- public void test_cbrt_D() {
- // Test for special situations
- assertTrue("Should return Double.NaN", Double.isNaN(StrictMath
- .cbrt(Double.NaN)));
- assertEquals("Should return Double.POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath
- .cbrt(Double.POSITIVE_INFINITY));
- assertEquals("Should return Double.NEGATIVE_INFINITY",
- Double.NEGATIVE_INFINITY, StrictMath
- .cbrt(Double.NEGATIVE_INFINITY));
- assertEquals(Double.doubleToLongBits(0.0), Double
- .doubleToLongBits(StrictMath.cbrt(0.0)));
- assertEquals(Double.doubleToLongBits(+0.0), Double
- .doubleToLongBits(StrictMath.cbrt(+0.0)));
- assertEquals(Double.doubleToLongBits(-0.0), Double
- .doubleToLongBits(StrictMath.cbrt(-0.0)));
-
- assertEquals("Should return 3.0", 3.0, StrictMath.cbrt(27.0));
- assertEquals("Should return 23.111993172558684", 23.111993172558684,
- StrictMath.cbrt(12345.6));
- assertEquals("Should return 5.643803094122362E102",
- 5.643803094122362E102, StrictMath.cbrt(Double.MAX_VALUE));
- assertEquals("Should return 0.01", 0.01, StrictMath.cbrt(0.000001));
-
- assertEquals("Should return -3.0", -3.0, StrictMath.cbrt(-27.0));
- assertEquals("Should return -23.111993172558684", -23.111993172558684,
- StrictMath.cbrt(-12345.6));
- assertEquals("Should return 1.7031839360032603E-108",
- 1.7031839360032603E-108, StrictMath.cbrt(Double.MIN_VALUE));
- assertEquals("Should return -0.01", -0.01, StrictMath.cbrt(-0.000001));
-
- try{
- StrictMath.cbrt((Double)null);
- fail("Should throw NullPointerException");
- }catch(NullPointerException e){
- //expected
- }
- }
-
- /**
- * @tests java.lang.StrictMath#ceil(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ceil",
- args = {double.class}
- )
- public void test_ceilD() {
- // Test for method double java.lang.StrictMath.ceil(double)
- assertEquals("Incorrect ceiling for double",
- 79, StrictMath.ceil(78.89), 0.0);
- assertEquals("Incorrect ceiling for double",
- -78, StrictMath.ceil(-78.89), 0.0);
-
- assertEquals("Incorrect ceiling for mathematical integer",
- -78, StrictMath.ceil(-78), 0.0);
- assertEquals("Incorrect ceiling for NaN",
- Double.NaN, StrictMath.ceil(Double.NaN));
- assertEquals("Incorrect ceiling for positive infinity",
- Double.POSITIVE_INFINITY,
- StrictMath.ceil(Double.POSITIVE_INFINITY));
- assertEquals("Incorrect ceiling for negative infinity",
- Double.NEGATIVE_INFINITY,
- StrictMath.ceil(Double.NEGATIVE_INFINITY));
- assertEquals("Incorrect ceiling for positive zero.",
- 0.0, StrictMath.ceil(0.0));
- assertEquals("Incorrect ceiling for negative zero.",
- -0.0, StrictMath.ceil(-0.0));
- assertEquals("Incorrect ceiling for negative zero.",
- -0.0, StrictMath.ceil(-0.5));
- }
-
- /**
- * @tests java.lang.StrictMath#cos(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "cos",
- args = {double.class}
- )
- public void test_cosD() {
- // Test for method double java.lang.StrictMath.cos(double)
-
- assertTrue("Returned incorrect cosine", StrictMath.cos(StrictMath
- .acos(ADJ / HYP)) == ADJ / HYP);
- assertEquals("Returned incorrect cosine", StrictMath.cos(Double.NaN),
- Double.NaN);
- }
-
- /**
- * @tests java.lang.StrictMath#cosh(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "cosh",
- args = {double.class}
- )
- @SuppressWarnings("boxing")
- public void test_cosh_D() {
- // Test for special situations
- assertTrue("Should return NaN", Double.isNaN(StrictMath
- .cosh(Double.NaN)));
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath
- .cosh(Double.POSITIVE_INFINITY));
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath
- .cosh(Double.NEGATIVE_INFINITY));
- assertEquals("Should return 1.0", 1.0, StrictMath.cosh(+0.0));
- assertEquals("Should return 1.0", 1.0, StrictMath.cosh(-0.0));
-
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath.cosh(1234.56));
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath.cosh(-1234.56));
- assertEquals("Should return 1.0000000000005", 1.0000000000005,
- StrictMath.cosh(0.000001));
- assertEquals("Should return 1.0000000000005", 1.0000000000005,
- StrictMath.cosh(-0.000001));
- assertEquals("Should return 5.212214351945598", 5.212214351945598,
- StrictMath.cosh(2.33482));
-
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath.cosh(Double.MAX_VALUE));
- assertEquals("Should return 1.0", 1.0, StrictMath
- .cosh(Double.MIN_VALUE));
- }
-
- /**
- * @tests java.lang.StrictMath#exp(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "exp",
- args = {double.class}
- )
- public void test_expD() {
- // Test for method double java.lang.StrictMath.exp(double)
- assertTrue("Incorrect answer returned for simple power", StrictMath
- .abs(StrictMath.exp(4D) - StrictMath.E * StrictMath.E
- * StrictMath.E * StrictMath.E) < 0.1D);
- assertTrue("Incorrect answer returned for larger power", StrictMath
- .log(StrictMath.abs(StrictMath.exp(5.5D)) - 5.5D) < 10.0D);
- assertEquals("Returned incorrect value for NaN argument", Double.NaN,
- StrictMath.exp(Double.NaN));
- assertEquals("Returned incorrect value for positive infinity.",
- Double.POSITIVE_INFINITY, StrictMath.exp(Double.POSITIVE_INFINITY));
- assertEquals("Returned incorrect value for negative infinity.",
- 0.0, StrictMath.exp(Double.NEGATIVE_INFINITY));
- }
-
- /**
- * @tests java.lang.StrictMath#expm1(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "expm1",
- args = {double.class}
- )
- @SuppressWarnings("boxing")
- public void test_expm1_D() {
- //Test for special cases
- assertTrue("Should return NaN", Double.isNaN(StrictMath.expm1(Double.NaN)));
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath.expm1(Double.POSITIVE_INFINITY));
- assertEquals("Should return -1.0", -1.0, StrictMath
- .expm1(Double.NEGATIVE_INFINITY));
- assertEquals(Double.doubleToLongBits(0.0), Double
- .doubleToLongBits(StrictMath.expm1(0.0)));
- assertEquals(Double.doubleToLongBits(+0.0), Double
- .doubleToLongBits(StrictMath.expm1(+0.0)));
- assertEquals(Double.doubleToLongBits(-0.0), Double
- .doubleToLongBits(StrictMath.expm1(-0.0)));
-
- assertEquals("Should return -9.999950000166666E-6",
- -9.999950000166666E-6, StrictMath.expm1(-0.00001));
- assertEquals("Should return 1.0145103074469635E60",
- 1.0145103074469635E60, StrictMath.expm1(138.16951162));
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath
- .expm1(123456789123456789123456789.4521584223));
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath.expm1(Double.MAX_VALUE));
- assertEquals("Should return MIN_VALUE", Double.MIN_VALUE, StrictMath
- .expm1(Double.MIN_VALUE));
-
- }
-
- /**
- * @tests java.lang.StrictMath#floor(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "floor",
- args = {double.class}
- )
- public void test_floorD() {
- // Test for method double java.lang.StrictMath.floor(double)
- assertEquals("Incorrect floor for double",
- 78, StrictMath.floor(78.89), 0.0);
- assertEquals("Incorrect floor for double",
- -79, StrictMath.floor(-78.89), 0.0);
- assertEquals("Incorrect floor for mathematical integer",
- -79, StrictMath.floor(-79), 0.0);
- assertEquals("Incorrect floor for NaN",
- Double.NaN, StrictMath.floor(Double.NaN));
- assertEquals("Incorrect floor for positive infinity.",
- Double.POSITIVE_INFINITY, StrictMath.floor(Double.POSITIVE_INFINITY));
- assertEquals("Incorrect floor for negative infinity.",
- Double.NEGATIVE_INFINITY, StrictMath.floor(Double.NEGATIVE_INFINITY));
- assertEquals("Incorrect floor for positive zero.",
- 0.0, StrictMath.floor(0.0));
- assertEquals("Incorrect floor for negative zero.",
- -0.0, StrictMath.floor(-0.0));
- }
-
- /**
- * @tests java.lang.StrictMath#hypot(double, double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hypot",
- args = {double.class, double.class}
- )
- @SuppressWarnings("boxing")
- public void test_hypot_DD() {
- // Test for special cases
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath.hypot(Double.POSITIVE_INFINITY,
- 1.0));
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath.hypot(Double.NEGATIVE_INFINITY,
- 123.324));
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath.hypot(-758.2587,
- Double.POSITIVE_INFINITY));
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath.hypot(5687.21,
- Double.NEGATIVE_INFINITY));
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath.hypot(Double.POSITIVE_INFINITY,
- Double.NEGATIVE_INFINITY));
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath.hypot(Double.NEGATIVE_INFINITY,
- Double.POSITIVE_INFINITY));
- assertTrue("Should return NaN",Double.isNaN(StrictMath.hypot(Double.NaN,
- 2342301.89843)));
- assertTrue("Should return NaN",Double.isNaN(StrictMath.hypot(-345.2680,
- Double.NaN)));
-
- assertEquals("Should return 2396424.905416697", 2396424.905416697, StrictMath
- .hypot(12322.12, -2396393.2258));
- assertEquals("Should return 138.16958070558556", 138.16958070558556,
- StrictMath.hypot(-138.16951162, 0.13817035864));
- assertEquals("Should return 1.7976931348623157E308",
- 1.7976931348623157E308, StrictMath.hypot(Double.MAX_VALUE, 211370.35));
- assertEquals("Should return 5413.7185", 5413.7185, StrictMath.hypot(
- -5413.7185, Double.MIN_VALUE));
-
- }
-
- /**
- * @tests java.lang.StrictMath#IEEEremainder(double, double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IEEEremainder",
- args = {double.class, double.class}
- )
- public void test_IEEEremainderDD() {
- // Test for method double java.lang.StrictMath.IEEEremainder(double,
- // double)
- assertEquals("Incorrect remainder returned", 0.0, StrictMath.IEEEremainder(
- 1.0, 1.0), 0.0);
- assertTrue(
- "Incorrect remainder returned",
- StrictMath.IEEEremainder(1.32, 89.765) >= 1.4705063220631647E-2
- || StrictMath.IEEEremainder(1.32, 89.765) >= 1.4705063220631649E-2);
-
- assertEquals(Double.NaN, StrictMath.IEEEremainder(Double.NaN, 0.0));
- assertEquals(Double.NaN, StrictMath.IEEEremainder(0.0, Double.NaN));
- assertEquals(Double.NaN, StrictMath.IEEEremainder(Double.POSITIVE_INFINITY, 0.0));
- assertEquals(Double.NaN, StrictMath.IEEEremainder(Double.NEGATIVE_INFINITY, 0.0));
- assertEquals(Double.NaN, StrictMath.IEEEremainder(0.0, 0.0));
- assertEquals(Double.NaN, StrictMath.IEEEremainder(-0.0, 0.0));
-
- assertEquals(1.0, StrictMath.IEEEremainder(1.0, Double.POSITIVE_INFINITY));
- assertEquals(1.0, StrictMath.IEEEremainder(1.0, Double.NEGATIVE_INFINITY));
-
- }
-
- /**
- * @tests java.lang.StrictMath#log(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "log",
- args = {double.class}
- )
- public void test_logD() {
- // Test for method double java.lang.StrictMath.log(double)
- for (double d = 10; d >= -10; d -= 0.5) {
- double answer = StrictMath.log(StrictMath.exp(d));
- assertTrue("Answer does not equal expected answer for d = " + d
- + " answer = " + answer,
- StrictMath.abs(answer - d) <= StrictMath
- .abs(d * 0.00000001));
- }
-
- assertEquals("Returned incorrect value for NaN.",
- Double.NaN, StrictMath.log(Double.NaN));
- assertEquals("Returned incorrect value for positive infinity.",
- Double.POSITIVE_INFINITY, StrictMath.log(Double.POSITIVE_INFINITY));
- assertEquals("Returned incorrect value for negative infinity.",
- Double.NaN, StrictMath.log(Double.NEGATIVE_INFINITY));
- assertEquals("Returned incorrect value for positive zero.",
- Double.NEGATIVE_INFINITY, StrictMath.log(0.0));
- assertEquals("Returned incorrect value for negative zero.",
- Double.NEGATIVE_INFINITY, StrictMath.log(-0.0));
- }
-
- /**
- * @tests java.lang.StrictMath#log10(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "log10",
- args = {double.class}
- )
- @SuppressWarnings("boxing")
- public void test_log10_D() {
- // Test for special cases
- assertTrue("Should return NaN", Double.isNaN(StrictMath
- .log10(Double.NaN)));
- assertTrue("Should return NaN", Double.isNaN(StrictMath
- .log10(-2541.05745687234187532)));
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath
- .log10(Double.POSITIVE_INFINITY));
- assertEquals("Should return NEGATIVE_INFINITY",
- Double.NEGATIVE_INFINITY, StrictMath.log10(0.0));
- assertEquals("Should return NEGATIVE_INFINITY",
- Double.NEGATIVE_INFINITY, StrictMath.log10(+0.0));
- assertEquals("Should return NEGATIVE_INFINITY",
- Double.NEGATIVE_INFINITY, StrictMath.log10(-0.0));
- assertEquals("Should return 14.0", 14.0, StrictMath.log10(StrictMath
- .pow(10, 14)));
-
- assertEquals("Should return 3.7389561269540406", 3.7389561269540406,
- StrictMath.log10(5482.2158));
- assertEquals("Should return 14.661551142893833", 14.661551142893833,
- StrictMath.log10(458723662312872.125782332587));
- assertEquals("Should return -0.9083828622192334", -0.9083828622192334,
- StrictMath.log10(0.12348583358871));
- assertEquals("Should return 308.25471555991675", 308.25471555991675,
- StrictMath.log10(Double.MAX_VALUE));
- assertEquals("Should return -323.3062153431158", -323.3062153431158,
- StrictMath.log10(Double.MIN_VALUE));
- }
-
- /**
- * @tests java.lang.StrictMath#log1p(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "log1p",
- args = {double.class}
- )
- @SuppressWarnings("boxing")
- public void test_log1p_D() {
- // Test for special cases
- assertTrue("Should return NaN", Double.isNaN(StrictMath
- .log1p(Double.NaN)));
- assertTrue("Should return NaN", Double.isNaN(StrictMath
- .log1p(-32.0482175)));
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath
- .log1p(Double.POSITIVE_INFINITY));
- assertEquals(Double.doubleToLongBits(0.0), Double
- .doubleToLongBits(StrictMath.log1p(0.0)));
- assertEquals(Double.doubleToLongBits(+0.0), Double
- .doubleToLongBits(StrictMath.log1p(+0.0)));
- assertEquals(Double.doubleToLongBits(-0.0), Double
- .doubleToLongBits(StrictMath.log1p(-0.0)));
-
- assertEquals("Should return -0.2941782295312541", -0.2941782295312541,
- StrictMath.log1p(-0.254856327));
- assertEquals("Should return 7.368050685564151", 7.368050685564151,
- StrictMath.log1p(1583.542));
- assertEquals("Should return 0.4633708685409921", 0.4633708685409921,
- StrictMath.log1p(0.5894227));
- assertEquals("Should return 709.782712893384", 709.782712893384,
- StrictMath.log1p(Double.MAX_VALUE));
- assertEquals("Should return Double.MIN_VALUE", Double.MIN_VALUE,
- StrictMath.log1p(Double.MIN_VALUE));
- }
-
- /**
- * @tests java.lang.StrictMath#max(double, double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "max",
- args = {double.class, double.class}
- )
- public void test_maxDD() {
- // Test for method double java.lang.StrictMath.max(double, double)
- assertEquals("Incorrect double max value", 1908897.6000089, StrictMath.max(
- -1908897.6000089, 1908897.6000089), 0D);
- assertEquals("Incorrect double max value", 1908897.6000089, StrictMath.max(2.0,
- 1908897.6000089), 0D);
- assertEquals("Incorrect double max value", -2.0, StrictMath.max(-2.0,
- -1908897.6000089), 0D);
-
- assertEquals("Incorrect double max value", Double.NaN,
- StrictMath.max(Double.NaN, 1.0));
- assertEquals("Incorrect double max value", 0.0,
- StrictMath.max(0.0, -0.0));
- }
-
- /**
- * @tests java.lang.StrictMath#max(float, float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "max",
- args = {float.class, float.class}
- )
- public void test_maxFF() {
- // Test for method float java.lang.StrictMath.max(float, float)
- assertTrue("Incorrect float max value", StrictMath.max(-1908897.600f,
- 1908897.600f) == 1908897.600f);
- assertTrue("Incorrect float max value", StrictMath.max(2.0f,
- 1908897.600f) == 1908897.600f);
- assertTrue("Incorrect float max value", StrictMath.max(-2.0f,
- -1908897.600f) == -2.0f);
- assertEquals("Incorrect float max value", Float.NaN,
- StrictMath.max(Float.NaN, 1f));
- assertEquals("Incorrect float max value", 0f,
- StrictMath.max(0f, -0f));
- }
-
- /**
- * @tests java.lang.StrictMath#max(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "max",
- args = {int.class, int.class}
- )
- public void test_maxII() {
- // Test for method int java.lang.StrictMath.max(int, int)
- assertEquals("Incorrect int max value", 19088976, StrictMath.max(-19088976,
- 19088976));
- assertEquals("Incorrect int max value",
- 19088976, StrictMath.max(20, 19088976));
- assertEquals("Incorrect int max value",
- -20, StrictMath.max(-20, -19088976));
- assertEquals("Returned incorrect value.", Integer.MAX_VALUE,
- StrictMath.max(Integer.MAX_VALUE, 1));
- assertEquals("Returned incorrect value.", Integer.MIN_VALUE,
- StrictMath.max(Integer.MIN_VALUE, Integer.MIN_VALUE));
- }
-
- /**
- * @tests java.lang.StrictMath#max(long, long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "max",
- args = {long.class, long.class}
- )
- public void test_maxJJ() {
- // Test for method long java.lang.StrictMath.max(long, long)
- assertEquals("Incorrect long max value", 19088976000089L, StrictMath.max(-19088976000089L,
- 19088976000089L));
- assertEquals("Incorrect long max value", 19088976000089L, StrictMath.max(20,
- 19088976000089L));
- assertEquals("Incorrect long max value", -20, StrictMath.max(-20,
- -19088976000089L));
-
- assertEquals("Returned incorrect value.", Long.MAX_VALUE,
- StrictMath.max(Long.MAX_VALUE, 1));
- assertEquals("Returned incorrect value.", Long.MIN_VALUE,
- StrictMath.max(Long.MIN_VALUE, Long.MIN_VALUE));
- }
-
- /**
- * @tests java.lang.StrictMath#min(double, double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "min",
- args = {double.class, double.class}
- )
- public void test_minDD() {
- // Test for method double java.lang.StrictMath.min(double, double)
- assertEquals("Incorrect double min value", -1908897.6000089, StrictMath.min(
- -1908897.6000089, 1908897.6000089), 0D);
- assertEquals("Incorrect double min value", 2.0, StrictMath.min(2.0,
- 1908897.6000089), 0D);
- assertEquals("Incorrect double min value", -1908897.6000089, StrictMath.min(-2.0,
- -1908897.6000089), 0D);
- assertEquals("Returned incorrect value.", Double.NaN,
- StrictMath.min(Double.NaN, 1.0));
- assertEquals("Returned incorrect value.", Double.NaN,
- StrictMath.min(1.0, Double.NaN));
- assertEquals("Returned incorrect value.", -0.0, StrictMath.min(0.0, -0.0));
- }
-
- /**
- * @tests java.lang.StrictMath#min(float, float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "min",
- args = {float.class, float.class}
- )
- public void test_minFF() {
- // Test for method float java.lang.StrictMath.min(float, float)
- assertTrue("Incorrect float min value", StrictMath.min(-1908897.600f,
- 1908897.600f) == -1908897.600f);
- assertTrue("Incorrect float min value", StrictMath.min(2.0f,
- 1908897.600f) == 2.0f);
- assertTrue("Incorrect float min value", StrictMath.min(-2.0f,
- -1908897.600f) == -1908897.600f);
-
- assertEquals("Returned incorrect value.", Float.NaN,
- StrictMath.min(Float.NaN, 1f));
- assertEquals("Returned incorrect value.", Float.NaN,
- StrictMath.min(1f, Float.NaN));
- assertEquals("Returned incorrect value.", -0f, StrictMath.min(0f, -0f));
- }
-
- /**
- * @tests java.lang.StrictMath#min(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "min",
- args = {int.class, int.class}
- )
- public void test_minII() {
- // Test for method int java.lang.StrictMath.min(int, int)
- assertEquals("Incorrect int min value", -19088976, StrictMath.min(-19088976,
- 19088976));
- assertEquals("Incorrect int min value",
- 20, StrictMath.min(20, 19088976));
- assertEquals("Incorrect int min value",
- -19088976, StrictMath.min(-20, -19088976));
-
- assertEquals("Incorrect value was returned.", Double.MIN_VALUE,
- StrictMath.min(Double.MIN_VALUE, Double.MIN_VALUE));
- }
-
- /**
- * @tests java.lang.StrictMath#min(long, long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "min",
- args = {long.class, long.class}
- )
- public void test_minJJ() {
- // Test for method long java.lang.StrictMath.min(long, long)
- assertEquals("Incorrect long min value", -19088976000089L, StrictMath.min(-19088976000089L,
- 19088976000089L));
- assertEquals("Incorrect long min value", 20, StrictMath.min(20,
- 19088976000089L));
- assertEquals("Incorrect long min value", -19088976000089L, StrictMath.min(-20,
- -19088976000089L));
- assertEquals("Incorrect value was returned.", Long.MIN_VALUE,
- StrictMath.min(Long.MIN_VALUE, Long.MIN_VALUE));
- }
-
- /**
- * @tests java.lang.StrictMath#pow(double, double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "pow",
- args = {double.class, double.class}
- )
- public void test_powDD() {
- // Test for method double java.lang.StrictMath.pow(double, double)
- assertTrue("pow returned incorrect value",
- (long) StrictMath.pow(2, 8) == 256l);
- assertTrue("pow returned incorrect value",
- StrictMath.pow(2, -8) == 0.00390625d);
-
- assertEquals(1.0, StrictMath.pow(1.0, 0.0));
- assertEquals(1.0, StrictMath.pow(1.0, -0.0));
-
- assertEquals(Double.NaN, StrictMath.pow(1.0, Double.NaN));
- assertEquals(Double.NaN, StrictMath.pow(Double.NaN, 1.0));
-
- assertEquals(Double.POSITIVE_INFINITY,
- StrictMath.pow(1.1, Double.POSITIVE_INFINITY));
- assertEquals(Double.POSITIVE_INFINITY,
- StrictMath.pow(0.1, Double.NEGATIVE_INFINITY));
-
- assertEquals(0.0, StrictMath.pow(1.1, Double.NEGATIVE_INFINITY));
- assertEquals(0.0, StrictMath.pow(0.1, Double.POSITIVE_INFINITY));
-
- assertEquals(Double.NaN, StrictMath.pow(1.0, Double.NEGATIVE_INFINITY));
- assertEquals(Double.NaN, StrictMath.pow(1.0, Double.POSITIVE_INFINITY));
-
- assertEquals(0.0, StrictMath.pow(0.0, 1.0));
- assertEquals(0.0, StrictMath.pow(Double.POSITIVE_INFINITY, -1.0));
-
- assertEquals(Double.POSITIVE_INFINITY, StrictMath.pow(0.0, -1.0));
- assertEquals(Double.POSITIVE_INFINITY,
- StrictMath.pow(Double.POSITIVE_INFINITY, 1.0));
-
- assertEquals(0.0, StrictMath.pow(-0.0, 2.0));
- assertEquals(0.0, StrictMath.pow(Double.NEGATIVE_INFINITY, -2.0));
-
- assertEquals(Double.POSITIVE_INFINITY, StrictMath.pow(-0.0, -2.0));
- assertEquals(Double.POSITIVE_INFINITY, StrictMath.pow(
- Double.NEGATIVE_INFINITY, 2.0));
-
- assertEquals(Double.NEGATIVE_INFINITY, StrictMath.pow(-0.0, -1.0));
- assertEquals(Double.NEGATIVE_INFINITY, StrictMath.pow(
- Double.NEGATIVE_INFINITY, 1.0));
-
- assertEquals(Double.NaN, StrictMath.pow(-1.0, 1.1));
- }
-
- /**
- * @tests java.lang.StrictMath#rint(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "rint",
- args = {double.class}
- )
- public void test_rintD() {
- // Test for method double java.lang.StrictMath.rint(double)
- assertEquals("Failed to round properly - up to odd",
- 3.0, StrictMath.rint(2.9), 0D);
- assertTrue("Failed to round properly - NaN", Double.isNaN(StrictMath
- .rint(Double.NaN)));
- assertEquals("Failed to round properly down to even", 2.0, StrictMath
- .rint(2.1), 0D);
- assertTrue("Failed to round properly " + 2.5 + " to even", StrictMath
- .rint(2.5) == 2.0);
- }
-
- /**
- * @tests java.lang.StrictMath#round(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "round",
- args = {double.class}
- )
- public void test_roundD() {
- // Test for method long java.lang.StrictMath.round(double)
- assertEquals("Incorrect rounding of a float",
- -91, StrictMath.round(-90.89d));
-
- assertEquals("Incorrect rounding of NaN", 0l,
- StrictMath.round(Double.NaN));
- assertEquals("Incorrect rounding of NEGATIVE_INFINITY", Long.MIN_VALUE,
- StrictMath.round(Double.NEGATIVE_INFINITY));
- assertEquals("Incorrect rounding of value less than Long.MIN_VALUE",
- Long.MIN_VALUE, StrictMath.round(new Double(Long.MIN_VALUE - 0.1)));
- assertEquals("Incorrect rounding of Long.MIN_VALUE",
- Long.MIN_VALUE, StrictMath.round(new Double(Long.MIN_VALUE)));
- assertEquals("Incorrect rounding of Long.MAX_VALUE",
- Long.MAX_VALUE, StrictMath.round(Double.POSITIVE_INFINITY));
- assertEquals("Incorrect rounding of value greater than Long.MAX_VALUE",
- Long.MAX_VALUE, StrictMath.round(new Double(Long.MAX_VALUE + 0.1)));
-
- }
-
- /**
- * @tests java.lang.StrictMath#round(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "round",
- args = {float.class}
- )
- public void test_roundF() {
- // Test for method int java.lang.StrictMath.round(float)
- assertEquals("Incorrect rounding of a float",
- -91, StrictMath.round(-90.89f));
-
- assertEquals("Incorrect rounding of NaN", 0l,
- StrictMath.round(Float.NaN));
- assertEquals("Incorrect rounding of NEGATIVE_INFINITY",
- Integer.MIN_VALUE, StrictMath.round(Float.NEGATIVE_INFINITY));
- assertEquals("Incorrect rounding of value less than Integer.MIN_VALUE",
- Integer.MIN_VALUE, StrictMath.round(new Float(Integer.MIN_VALUE - 0.1)));
- assertEquals("Incorrect rounding of Integer.MIN_VALUE",
- Integer.MIN_VALUE, StrictMath.round(new Float(Integer.MIN_VALUE)));
- assertEquals("Incorrect rounding of Integer.MAX_VALUE",
- Integer.MAX_VALUE, StrictMath.round(Float.POSITIVE_INFINITY));
- assertEquals("Incorrect rounding of value greater than Integer.MAX_VALUE",
- Integer.MAX_VALUE, StrictMath.round(new Float(Integer.MAX_VALUE + 0.1)));
- }
-
- /**
- * @tests java.lang.StrictMath#signum(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "signum",
- args = {double.class}
- )
- public void test_signum_D() {
- assertTrue(Double.isNaN(StrictMath.signum(Double.NaN)));
- assertEquals(Double.doubleToLongBits(0.0), Double
- .doubleToLongBits(StrictMath.signum(0.0)));
- assertEquals(Double.doubleToLongBits(+0.0), Double
- .doubleToLongBits(StrictMath.signum(+0.0)));
- assertEquals(Double.doubleToLongBits(-0.0), Double
- .doubleToLongBits(StrictMath.signum(-0.0)));
-
- assertEquals(1.0, StrictMath.signum(253681.2187962), 0D);
- assertEquals(-1.0, StrictMath.signum(-125874693.56), 0D);
- assertEquals(1.0, StrictMath.signum(1.2587E-308), 0D);
- assertEquals(-1.0, StrictMath.signum(-1.2587E-308), 0D);
-
- assertEquals(1.0, StrictMath.signum(Double.MAX_VALUE), 0D);
- assertEquals(1.0, StrictMath.signum(Double.MIN_VALUE), 0D);
- assertEquals(-1.0, StrictMath.signum(-Double.MAX_VALUE), 0D);
- assertEquals(-1.0, StrictMath.signum(-Double.MIN_VALUE), 0D);
- assertEquals(1.0, StrictMath.signum(Double.POSITIVE_INFINITY), 0D);
- assertEquals(-1.0, StrictMath.signum(Double.NEGATIVE_INFINITY), 0D);
-
- }
-
- /**
- * @tests java.lang.StrictMath#signum(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "signum",
- args = {float.class}
- )
- public void test_signum_F() {
- assertTrue(Float.isNaN(StrictMath.signum(Float.NaN)));
- assertEquals(Float.floatToIntBits(0.0f), Float
- .floatToIntBits(StrictMath.signum(0.0f)));
- assertEquals(Float.floatToIntBits(+0.0f), Float
- .floatToIntBits(StrictMath.signum(+0.0f)));
- assertEquals(Float.floatToIntBits(-0.0f), Float
- .floatToIntBits(StrictMath.signum(-0.0f)));
-
- assertEquals(1.0f, StrictMath.signum(253681.2187962f), 0f);
- assertEquals(-1.0f, StrictMath.signum(-125874693.56f), 0f);
- assertEquals(1.0f, StrictMath.signum(1.2587E-11f), 0f);
- assertEquals(-1.0f, StrictMath.signum(-1.2587E-11f), 0f);
-
- assertEquals(1.0f, StrictMath.signum(Float.MAX_VALUE), 0f);
- assertEquals(1.0f, StrictMath.signum(Float.MIN_VALUE), 0f);
- assertEquals(-1.0f, StrictMath.signum(-Float.MAX_VALUE), 0f);
- assertEquals(-1.0f, StrictMath.signum(-Float.MIN_VALUE), 0f);
- assertEquals(1.0f, StrictMath.signum(Float.POSITIVE_INFINITY), 0f);
- assertEquals(-1.0f, StrictMath.signum(Float.NEGATIVE_INFINITY), 0f);
- }
-
- /**
- * @tests java.lang.StrictMath#sin(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sin",
- args = {double.class}
- )
- public void test_sinD() {
- // Test for method double java.lang.StrictMath.sin(double)
- assertTrue("Returned incorrect sine", StrictMath.sin(StrictMath
- .asin(OPP / HYP)) == OPP / HYP);
-
- assertEquals("Returned incorrect sin value.",
- Double.NaN, StrictMath.sin(Double.NaN));
-
- assertEquals("Returned incorrect sin value.",
- Double.NaN, StrictMath.sin(Double.POSITIVE_INFINITY));
-
- assertEquals("Returned incorrect sin value.",
- Double.NaN, StrictMath.sin(Double.NEGATIVE_INFINITY));
-
- assertEquals("Returned incorrect sin value.",
- 0.0, StrictMath.sin(0.0));
- assertEquals("Returned incorrect sin value.",
- -0.0, StrictMath.sin(-0.0));
- }
-
- /**
- * @tests java.lang.StrictMath#sinh(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sinh",
- args = {double.class}
- )
- public void test_sinh_D() {
- // Test for special situations
- assertTrue(Double.isNaN(StrictMath.sinh(Double.NaN)));
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath
- .sinh(Double.POSITIVE_INFINITY), 0D);
- assertEquals("Should return NEGATIVE_INFINITY",
- Double.NEGATIVE_INFINITY, StrictMath
- .sinh(Double.NEGATIVE_INFINITY), 0D);
- assertEquals(Double.doubleToLongBits(0.0), Double
- .doubleToLongBits(StrictMath.sinh(0.0)));
- assertEquals(Double.doubleToLongBits(+0.0), Double
- .doubleToLongBits(StrictMath.sinh(+0.0)));
- assertEquals(Double.doubleToLongBits(-0.0), Double
- .doubleToLongBits(StrictMath.sinh(-0.0)));
-
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath.sinh(1234.56), 0D);
- assertEquals("Should return NEGATIVE_INFINITY",
- Double.NEGATIVE_INFINITY, StrictMath.sinh(-1234.56), 0D);
- assertEquals("Should return 1.0000000000001666E-6",
- 1.0000000000001666E-6, StrictMath.sinh(0.000001), 0D);
- assertEquals("Should return -1.0000000000001666E-6",
- -1.0000000000001666E-6, StrictMath.sinh(-0.000001), 0D);
- assertEquals("Should return 5.115386441963859", 5.115386441963859,
- StrictMath.sinh(2.33482), 0D);
- assertEquals("Should return POSITIVE_INFINITY",
- Double.POSITIVE_INFINITY, StrictMath.sinh(Double.MAX_VALUE), 0D);
- assertEquals("Should return 4.9E-324", 4.9E-324, StrictMath
- .sinh(Double.MIN_VALUE), 0D);
- }
-
- /**
- * @tests java.lang.StrictMath#sqrt(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sqrt",
- args = {double.class}
- )
- public void test_sqrtD() {
- // Test for method double java.lang.StrictMath.sqrt(double)
- assertEquals("Incorrect root returned1",
- 2, StrictMath.sqrt(StrictMath.pow(StrictMath.sqrt(2), 4)), 0.0);
- assertEquals("Incorrect root returned2", 7, StrictMath.sqrt(49), 0.0);
-
- assertEquals("Incorrect root was returned.", Double.NaN,
- StrictMath.sqrt(Double.NaN));
- assertEquals("Incorrect root was returned.", Double.NaN,
- StrictMath.sqrt(-0.1));
- assertEquals("Incorrect root was returned.", Double.POSITIVE_INFINITY,
- StrictMath.sqrt(Double.POSITIVE_INFINITY));
-
- assertEquals("Incorrect root was returned.", 0.0, StrictMath.sqrt(0.0));
- assertEquals("Incorrect root was returned.", -0.0, StrictMath.sqrt(-0.0));
- }
-
- /**
- * @tests java.lang.StrictMath#tan(double)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Doesn't check boundary values.",
- method = "tan",
- args = {double.class}
- )
- public void test_tanD() {
- // Test for method double java.lang.StrictMath.tan(double)
- assertTrue(
- "Returned incorrect tangent: ",
- StrictMath.tan(StrictMath.atan(1.0)) <= 1.0
- || StrictMath.tan(StrictMath.atan(1.0)) >= 9.9999999999999983E-1);
- }
-
- /**
- * @tests java.lang.StrictMath#tanh(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "tanh",
- args = {double.class}
- )
- public void test_tanh_D() {
- // Test for special situations
- assertTrue(Double.isNaN(StrictMath.tanh(Double.NaN)));
- assertEquals("Should return +1.0", +1.0, StrictMath
- .tanh(Double.POSITIVE_INFINITY), 0D);
- assertEquals("Should return -1.0", -1.0, StrictMath
- .tanh(Double.NEGATIVE_INFINITY), 0D);
- assertEquals(Double.doubleToLongBits(0.0), Double
- .doubleToLongBits(StrictMath.tanh(0.0)));
- assertEquals(Double.doubleToLongBits(+0.0), Double
- .doubleToLongBits(StrictMath.tanh(+0.0)));
- assertEquals(Double.doubleToLongBits(-0.0), Double
- .doubleToLongBits(StrictMath.tanh(-0.0)));
-
- assertEquals("Should return 1.0", 1.0, StrictMath.tanh(1234.56), 0D);
- assertEquals("Should return -1.0", -1.0, StrictMath.tanh(-1234.56), 0D);
- assertEquals("Should return 9.999999999996666E-7",
- 9.999999999996666E-7, StrictMath.tanh(0.000001), 0D);
- assertEquals("Should return 0.981422884124941", 0.981422884124941,
- StrictMath.tanh(2.33482), 0D);
- assertEquals("Should return 1.0", 1.0, StrictMath
- .tanh(Double.MAX_VALUE), 0D);
- assertEquals("Should return 4.9E-324", 4.9E-324, StrictMath
- .tanh(Double.MIN_VALUE), 0D);
- }
-
- /**
- * @tests java.lang.StrictMath#random()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "random",
- args = {}
- )
- public void test_random() {
- // There isn't a place for these tests so just stick them here
- assertEquals("Wrong value E",
- 4613303445314885481L, Double.doubleToLongBits(StrictMath.E));
- assertEquals("Wrong value PI",
- 4614256656552045848L, Double.doubleToLongBits(StrictMath.PI));
-
- for (int i = 500; i >= 0; i--) {
- double d = StrictMath.random();
- assertTrue("Generated number is out of range: " + d, d >= 0.0
- && d < 1.0);
- }
- }
-
- /**
- * @tests java.lang.StrictMath#toRadians(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toRadians",
- args = {double.class}
- )
- public void test_toRadiansD() {
- for (double d = 500; d >= 0; d -= 1.0) {
- double converted = StrictMath.toDegrees(StrictMath.toRadians(d));
- assertTrue("Converted number not equal to original. d = " + d,
- converted >= d * 0.99999999 && converted <= d * 1.00000001);
- }
- }
-
- /**
- * @tests java.lang.StrictMath#toDegrees(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toDegrees",
- args = {double.class}
- )
- public void test_toDegreesD() {
- for (double d = 500; d >= 0; d -= 1.0) {
- double converted = StrictMath.toRadians(StrictMath.toDegrees(d));
- assertTrue("Converted number not equal to original. d = " + d,
- converted >= d * 0.99999999 && converted <= d * 1.00000001);
- }
- }
-
- /**
- * @tests java.lang.StrictMath#ulp(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ulp",
- args = {double.class}
- )
- @SuppressWarnings("boxing")
- public void test_ulp_D() {
- // Test for special cases
- assertTrue("Should return NaN", Double
- .isNaN(StrictMath.ulp(Double.NaN)));
- assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY,
- StrictMath.ulp(Double.POSITIVE_INFINITY), 0D);
- assertEquals("Returned incorrect value", Double.POSITIVE_INFINITY,
- StrictMath.ulp(Double.NEGATIVE_INFINITY), 0D);
- assertEquals("Returned incorrect value", Double.MIN_VALUE, StrictMath
- .ulp(0.0), 0D);
- assertEquals("Returned incorrect value", Double.MIN_VALUE, StrictMath
- .ulp(+0.0), 0D);
- assertEquals("Returned incorrect value", Double.MIN_VALUE, StrictMath
- .ulp(-0.0), 0D);
- assertEquals("Returned incorrect value", StrictMath.pow(2, 971),
- StrictMath.ulp(Double.MAX_VALUE), 0D);
- assertEquals("Returned incorrect value", StrictMath.pow(2, 971),
- StrictMath.ulp(-Double.MAX_VALUE), 0D);
-
- assertEquals("Returned incorrect value", Double.MIN_VALUE, StrictMath
- .ulp(Double.MIN_VALUE), 0D);
- assertEquals("Returned incorrect value", Double.MIN_VALUE, StrictMath
- .ulp(-Double.MIN_VALUE), 0D);
-
- assertEquals("Returned incorrect value", 2.220446049250313E-16,
- StrictMath.ulp(1.0), 0D);
- assertEquals("Returned incorrect value", 2.220446049250313E-16,
- StrictMath.ulp(-1.0), 0D);
- assertEquals("Returned incorrect value", 2.2737367544323206E-13,
- StrictMath.ulp(1153.0), 0D);
- }
-
- /**
- * @tests java.lang.StrictMath#ulp(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ulp",
- args = {float.class}
- )
- @SuppressWarnings("boxing")
- public void test_ulp_f() {
- // Test for special cases
- assertTrue("Should return NaN", Float.isNaN(StrictMath.ulp(Float.NaN)));
- assertEquals("Returned incorrect value", Float.POSITIVE_INFINITY,
- StrictMath.ulp(Float.POSITIVE_INFINITY), 0f);
- assertEquals("Returned incorrect value", Float.POSITIVE_INFINITY,
- StrictMath.ulp(Float.NEGATIVE_INFINITY), 0f);
- assertEquals("Returned incorrect value", Float.MIN_VALUE, StrictMath
- .ulp(0.0f), 0f);
- assertEquals("Returned incorrect value", Float.MIN_VALUE, StrictMath
- .ulp(+0.0f), 0f);
- assertEquals("Returned incorrect value", Float.MIN_VALUE, StrictMath
- .ulp(-0.0f), 0f);
- assertEquals("Returned incorrect value", 2.028241E31f, StrictMath
- .ulp(Float.MAX_VALUE), 0f);
- assertEquals("Returned incorrect value", 2.028241E31f, StrictMath
- .ulp(-Float.MAX_VALUE), 0f);
-
- assertEquals("Returned incorrect value", 1.4E-45f, StrictMath
- .ulp(Float.MIN_VALUE), 0f);
- assertEquals("Returned incorrect value", 1.4E-45f, StrictMath
- .ulp(-Float.MIN_VALUE), 0f);
-
- assertEquals("Returned incorrect value", 1.1920929E-7f, StrictMath
- .ulp(1.0f), 0f);
- assertEquals("Returned incorrect value", 1.1920929E-7f, StrictMath
- .ulp(-1.0f), 0f);
- assertEquals("Returned incorrect value", 1.2207031E-4f, StrictMath
- .ulp(1153.0f), 0f);
- assertEquals("Returned incorrect value", 5.6E-45f, Math
- .ulp(9.403954E-38f), 0f);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/String2Test.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/String2Test.java
deleted file mode 100644
index c151caf..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/String2Test.java
+++ /dev/null
@@ -1,1741 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.UnsupportedEncodingException;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.IllegalFormatException;
-import java.util.Locale;
-import java.util.regex.Pattern;
-import java.util.regex.PatternSyntaxException;
-
-@TestTargetClass(String.class)
-public class String2Test extends junit.framework.TestCase {
-
- String hw1 = "HelloWorld";
-
- String hw2 = "HelloWorld";
-
- String hwlc = "helloworld";
-
- String hwuc = "HELLOWORLD";
-
- String hello1 = "Hello";
-
- String world1 = "World";
-
- String comp11 = "Test String";
-
- Object obj = new Object();
-
- char[] buf = { 'W', 'o', 'r', 'l', 'd' };
-
- char[] rbuf = new char[5];
-
- /**
- * @tests java.lang.String#String()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {java.lang.String.class}
- )
- public void test_Constructor() {
- // Test for method java.lang.String()
- assertTrue("Created incorrect string", new String().equals(""));
- }
-
- /**
- * @tests java.lang.String#String(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {byte[].class}
- )
- public void test_Constructor$B() {
- // Test for method java.lang.String(byte [])
- assertTrue("Failed to create string", new String(hw1.getBytes())
- .equals(hw1));
- }
-
- /**
- * @tests java.lang.String#String(byte[], int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {byte[].class, int.class}
- )
- @SuppressWarnings("deprecation")
- public void test_Constructor$BI() {
- // Test for method java.lang.String(byte [], int)
- String s = new String(new byte[] { 65, 66, 67, 68, 69 }, 0);
- assertTrue("Incorrect string returned: " + s, s.equals("ABCDE"));
- s = new String(new byte[] { 65, 66, 67, 68, 69 }, 1);
- assertTrue("Did not use nonzero hibyte", !s.equals("ABCDE"));
- }
-
- /**
- * @tests java.lang.String#String(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {byte[].class, int.class, int.class}
- )
- public void test_Constructor$BII() {
- // Test for method java.lang.String(byte [], int, int)
- assertTrue("Failed to create string", new String(hw1.getBytes(), 0, hw1
- .getBytes().length).equals(hw1));
-
- boolean exception = false;
- try {
- new String(new byte[0], 0, Integer.MAX_VALUE);
- } catch (IndexOutOfBoundsException e) {
- exception = true;
- }
- assertTrue("Did not throw exception", exception);
- }
-
- /**
- * @tests java.lang.String#String(byte[], int, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {byte[].class, int.class, int.class, int.class}
- )
- @SuppressWarnings("deprecation")
- public void test_Constructor$BIII() {
- // Test for method java.lang.String(byte [], int, int, int)
- String s = new String(new byte[] { 65, 66, 67, 68, 69 }, 0, 1, 3);
- assertTrue("Incorrect string returned: " + s, s.equals("BCD"));
- s = new String(new byte[] { 65, 66, 67, 68, 69 }, 1, 0, 5);
- assertTrue("Did not use nonzero hibyte", !s.equals("ABCDE"));
- }
-
- /**
- * @tests java.lang.String#String(byte[], int, int, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {byte[].class, int.class, int.class, java.lang.String.class}
- )
- public void test_Constructor$BIILjava_lang_String() throws Exception {
- // Test for method java.lang.String(byte [], int, int, java.lang.String)
- String s = null;
- try {
- s = new String(new byte[] { 65, 66, 67, 68, 69 }, 0, 5, "8859_1");
- } catch (Exception e) {
- fail("Threw exception : " + e.getMessage());
- }
- assertTrue("Incorrect string returned: " + s, s.equals("ABCDE"));
- //Regression for HARMONY-1111
- assertNotNull(new String(new byte[] {(byte)0xC0}, 0, 1, "UTF-8"));
- }
-
- /**
- * @tests java.lang.String#String(byte[], java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {byte[].class, java.lang.String.class}
- )
- public void test_Constructor$BLjava_lang_String() {
- // Test for method java.lang.String(byte [], java.lang.String)
- String s = null;
- try {
- s = new String(new byte[] { 65, 66, 67, 68, 69 }, "8859_1");
- } catch (Exception e) {
- fail("Threw exception : " + e.getMessage());
- }
- assertTrue("Incorrect string returned: " + s, s.equals("ABCDE"));
- }
-
- /**
- * @tests java.lang.String#String(char[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {char[].class}
- )
- public void test_Constructor$C() {
- // Test for method java.lang.String(char [])
- assertEquals("Failed Constructor test", "World", new String(buf));
- }
-
- /**
- * @tests java.lang.String#String(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {char[].class, int.class, int.class}
- )
- public void test_Constructor$CII() {
- // Test for method java.lang.String(char [], int, int)
- char[] buf = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
- String s = new String(buf, 0, buf.length);
- assertTrue("Incorrect string created", hw1.equals(s));
-
- boolean exception = false;
- try {
- new String(new char[0], 0, Integer.MAX_VALUE);
- } catch (IndexOutOfBoundsException e) {
- exception = true;
- }
- assertTrue("Did not throw exception", exception);
- }
-
- /**
- * @tests java.lang.String#String(int[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {int[].class, int.class, int.class}
- )
- public void test_Constructor$III() {
- // Test for method java.lang.String(int [], int, int)
- try {
- new String(new int[0], 2, Integer.MAX_VALUE);
- fail("Did not throw exception");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.String#String(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.lang.String(java.lang.String)
- String s = new String("Hello World");
- assertEquals("Failed to construct correct string", "Hello World", s
- );
- }
-
- /**
- * @tests java.lang.String#String(java.lang.StringBuffer)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {java.lang.StringBuffer.class}
- )
- public void test_ConstructorLjava_lang_StringBuffer() {
- // Test for method java.lang.String(java.lang.StringBuffer)
- StringBuffer sb = new StringBuffer();
- sb.append("HelloWorld");
- assertEquals("Created incorrect string", "HelloWorld", new String(sb)
- );
- }
-
- /**
- * @tests java.lang.String#charAt(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "charAt",
- args = {int.class}
- )
- public void test_charAtI() {
- // Test for method char java.lang.String.charAt(int)
- assertTrue("Incorrect character returned", hw1.charAt(5) == 'W'
- && (hw1.charAt(1) != 'Z'));
-
- String testString = "Test String";
- try {
- testString.charAt(testString.length());
- fail("IndexOutOfBoundsException was not thrown.");
- } catch(IndexOutOfBoundsException iobe) {
- //expected
- }
-
- try {
- testString.charAt(Integer.MAX_VALUE);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch(IndexOutOfBoundsException iobe) {
- //expected
- }
-
- try {
- testString.charAt(-1);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch(IndexOutOfBoundsException iobe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.String#compareTo(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.lang.String.class}
- )
- public void test_compareToLjava_lang_String() {
- // Test for method int java.lang.String.compareTo(java.lang.String)
- assertTrue("Returned incorrect value for first < second", "aaaaab"
- .compareTo("aaaaac") < 0);
- assertEquals("Returned incorrect value for first = second", 0, "aaaaac"
- .compareTo("aaaaac"));
- assertTrue("Returned incorrect value for first > second", "aaaaac"
- .compareTo("aaaaab") > 0);
- assertTrue("Considered case to not be of importance", !("A"
- .compareTo("a") == 0));
-
- try {
- "fixture".compareTo(null);
- fail("No NPE");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @tests java.lang.String#compareToIgnoreCase(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compareToIgnoreCase",
- args = {java.lang.String.class}
- )
- public void test_compareToIgnoreCaseLjava_lang_String() {
- // Test for method int
- // java.lang.String.compareToIgnoreCase(java.lang.String)
- assertTrue("Returned incorrect value for first < second", "aaaaab"
- .compareToIgnoreCase("aaaaac") < 0);
- assertEquals("Returned incorrect value for first = second", 0, "aaaaac"
- .compareToIgnoreCase("aaaaac"));
- assertTrue("Returned incorrect value for first > second", "aaaaac"
- .compareToIgnoreCase("aaaaab") > 0);
- assertEquals("Considered case to not be of importance", 0, "A"
- .compareToIgnoreCase("a"));
-
- assertTrue("0xbf should not compare = to 'ss'", "\u00df"
- .compareToIgnoreCase("ss") != 0);
- assertEquals("0x130 should compare = to 'i'", 0, "\u0130"
- .compareToIgnoreCase("i"));
- assertEquals("0x131 should compare = to 'i'", 0, "\u0131"
- .compareToIgnoreCase("i"));
-
- Locale defLocale = Locale.getDefault();
- try {
- Locale.setDefault(new Locale("tr", ""));
- assertEquals("Locale tr: 0x130 should compare = to 'i'", 0, "\u0130"
- .compareToIgnoreCase("i"));
- assertEquals("Locale tr: 0x131 should compare = to 'i'", 0, "\u0131"
- .compareToIgnoreCase("i"));
- } finally {
- Locale.setDefault(defLocale);
- }
-
- try {
- "fixture".compareToIgnoreCase(null);
- fail("No NPE");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @tests java.lang.String#concat(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "concat",
- args = {java.lang.String.class}
- )
- public void test_concatLjava_lang_String() {
- // Test for method java.lang.String
- // java.lang.String.concat(java.lang.String)
- assertTrue("Concatenation failed to produce correct string", hello1
- .concat(world1).equals(hw1));
- boolean exception = false;
- try {
- String a = new String("test");
- String b = null;
- a.concat(b);
- } catch (NullPointerException e) {
- exception = true;
- }
- assertTrue("Concatenation failed to throw NP exception (1)", exception);
- exception = false;
- try {
- String a = new String("");
- String b = null;
- a.concat(b);
- } catch (NullPointerException e) {
- exception = true;
- }
- assertTrue("Concatenation failed to throw NP exception (2)", exception);
-
- String s1 = "";
- String s2 = "s2";
- String s3 = s1.concat(s2);
- assertEquals(s2, s3);
-
- s3 = s2.concat(s1);
- assertSame(s2, s3);
- }
-
- /**
- * @tests java.lang.String#copyValueOf(char[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "copyValueOf",
- args = {char[].class}
- )
- public void test_copyValueOf$C() {
- // Test for method java.lang.String java.lang.String.copyValueOf(char
- // [])
- char[] t = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
- assertEquals("copyValueOf returned incorrect String", "HelloWorld", String.copyValueOf(
- t));
- }
-
- /**
- * @tests java.lang.String#copyValueOf(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "copyValueOf",
- args = {char[].class, int.class, int.class}
- )
- public void test_copyValueOf$CII() {
- // Test for method java.lang.String java.lang.String.copyValueOf(char
- // [], int, int)
- char[] t = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
- assertEquals("copyValueOf returned incorrect String", "World", String.copyValueOf(
- t, 5, 5));
- }
-
- /**
- * @tests java.lang.String#endsWith(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "endsWith",
- args = {java.lang.String.class}
- )
- public void test_endsWithLjava_lang_String() {
- // Test for method boolean java.lang.String.endsWith(java.lang.String)
- assertTrue("Failed to fine ending string", hw1.endsWith("ld"));
- assertFalse("Doesn't return false value.", hw1.endsWith("ld "));
- assertFalse("Doesn't return false value.", hw1.endsWith(" "));
- assertTrue("Returned incorrect value for empty string.", hw1.endsWith(""));
- try {
- hw1.endsWith(null);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.String#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean java.lang.String.equals(java.lang.Object)
- assertTrue("String not equal", hw1.equals(hw2) && !(hw1.equals(comp11)));
- }
-
- /**
- * @tests java.lang.String#equalsIgnoreCase(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equalsIgnoreCase",
- args = {java.lang.String.class}
- )
- public void test_equalsIgnoreCaseLjava_lang_String() {
- // Test for method boolean
- // java.lang.String.equalsIgnoreCase(java.lang.String)
- assertTrue("lc version returned unequal to uc", hwlc
- .equalsIgnoreCase(hwuc));
-
- assertTrue("Returned false for equals strings.", hwlc
- .equalsIgnoreCase(hwlc));
-
- assertFalse("Returned true for different strings.", hwlc
- .equalsIgnoreCase(hwuc + " "));
- }
-
- /**
- * @tests java.lang.String#getBytes()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBytes",
- args = {}
- )
- public void test_getBytes() {
- // Test for method byte [] java.lang.String.getBytes()
- byte[] sbytes = hw1.getBytes();
- for (int i = 0; i < hw1.length(); i++)
- assertTrue("Returned incorrect bytes", sbytes[i] == (byte) hw1
- .charAt(i));
-
- char[] chars = new char[1];
- for (int i = 0; i < 65536; i++) {
- // skip surrogates
- if (i == 0xd800)
- i = 0xe000;
- byte[] result = null;
- chars[0] = (char) i;
- String string = new String(chars);
- try {
- result = string.getBytes("8859_1");
- if (i < 256) {
- assertEquals((byte)i, result[0]);
- } else {
- /*
- * Substitue character should be 0x1A [1], but may be
- * '?' character.
- * [1] http://en.wikipedia.org/wiki/Substitute_character
- */
- assertTrue(result[0] == '?' || result[0] == 0x1a);
- }
- } catch (java.io.UnsupportedEncodingException e) {
- }
- try {
- result = string.getBytes("UTF8");
- int length = i < 0x80 ? 1 : (i < 0x800 ? 2 : 3);
- assertTrue("Wrong length UTF8: " + Integer.toHexString(i),
- result.length == length);
- assertTrue(
- "Wrong bytes UTF8: " + Integer.toHexString(i),
- (i < 0x80 && result[0] == i)
- || (i >= 0x80
- && i < 0x800
- && result[0] == (byte) (0xc0 | ((i & 0x7c0) >> 6)) && result[1] == (byte) (0x80 | (i & 0x3f)))
- || (i >= 0x800
- && result[0] == (byte) (0xe0 | (i >> 12))
- && result[1] == (byte) (0x80 | ((i & 0xfc0) >> 6)) && result[2] == (byte) (0x80 | (i & 0x3f))));
- } catch (java.io.UnsupportedEncodingException e) {
- }
-
- String bytes = null;
- try {
- bytes = new String(result, "UTF8");
- assertTrue("Wrong UTF8 byte length: " + bytes.length() + "("
- + i + ")", bytes.length() == 1);
- assertTrue(
- "Wrong char UTF8: "
- + Integer.toHexString(bytes.charAt(0)) + " ("
- + i + ")", bytes.charAt(0) == i);
- } catch (java.io.UnsupportedEncodingException e) {
- }
- }
-
- byte[] bytes = new byte[1];
- for (int i = 0; i < 256; i++) {
- bytes[0] = (byte) i;
- String result = null;
- try {
- result = new String(bytes, "8859_1");
- assertEquals("Wrong char length", 1, result.length());
- assertTrue("Wrong char value", result.charAt(0) == (char) i);
- } catch (java.io.UnsupportedEncodingException e) {
- }
- }
- }
-
- /**
- * @tests java.lang.String#getBytes(int, int, byte[], int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBytes",
- args = {int.class, int.class, byte[].class, int.class}
- )
- @SuppressWarnings("deprecation")
- public void test_getBytesII$BI() {
- // Test for method void java.lang.String.getBytes(int, int, byte [],
- // int)
- byte[] buf = new byte[5];
- "Hello World".getBytes(6, 11, buf, 0);
- assertEquals("Returned incorrect bytes", "World", new String(buf));
-
- try {
- "Hello World".getBytes(-1, 1, null, 0);
- fail("Expected IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- //expected
- } catch (NullPointerException e) {
- fail("Threw wrong exception");
- }
-
- try {
- "Hello World".getBytes(6, 2, null, 0);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- "Hello World".getBytes(2, 10, new byte[10], 4);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.String#getBytes(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBytes",
- args = {java.lang.String.class}
- )
- public void test_getBytesLjava_lang_String() throws Exception {
- // Test for method byte [] java.lang.String.getBytes(java.lang.String)
- byte[] buf = "Hello World".getBytes();
- assertEquals("Returned incorrect bytes", "Hello World", new String(buf));
-
- try {
- "string".getBytes("8849_1");
- fail("No UnsupportedEncodingException");
- } catch (UnsupportedEncodingException e) {
- }
-
- byte[] bytes = "\u3048".getBytes("UTF-8");
- byte[] expected = new byte[] {(byte)0xE3, (byte)0x81, (byte)0x88};
- assertEquals(expected[0], bytes[0]);
- assertEquals(expected[1], bytes[1]);
- assertEquals(expected[2], bytes[2]);
-
- // Regression for HARMONY-663
- try {
- // BEGIN android-changed
- // (replaced non-ASCII-printable characters with escapes)
- "string".getBytes(
- "?Q?D??_??_6ffa?+vG?_??\u00ef\u00bf\u00bd??\u0015");
- // END android-changed
- fail("No UnsupportedEncodingException");
- } catch (UnsupportedEncodingException e) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.String#getChars(int, int, char[], int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getChars",
- args = {int.class, int.class, char[].class, int.class}
- )
- public void test_getCharsII$CI() {
- // Test for method void java.lang.String.getChars(int, int, char [],
- // int)
- hw1.getChars(5, hw1.length(), rbuf, 0);
-
- for (int i = 0; i < rbuf.length; i++)
- assertTrue("getChars returned incorrect char(s)", rbuf[i] == buf[i]);
-
- try {
- "Hello World".getChars(-1, 1, null, 0);
- fail("Expected IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- //expected
- } catch (NullPointerException e) {
- fail("Threw wrong exception");
- }
-
- try {
- "Hello World".getChars(6, 2, null, 0);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- "Hello World".getChars(2, 10, new char[10], 4);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.String#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- // Test for method int java.lang.String.hashCode()
- int hwHashCode = 0;
- final int hwLength = hw1.length();
- int powerOfThirtyOne = 1;
- for (int counter = hwLength - 1; counter >= 0; counter--) {
- hwHashCode += hw1.charAt(counter) * powerOfThirtyOne;
- powerOfThirtyOne *= 31;
- }
- assertTrue("String did not hash to correct value--got: "
- + String.valueOf(hw1.hashCode()) + " but wanted: "
- + String.valueOf(hwHashCode), hw1.hashCode() == hwHashCode);
- assertTrue("The empty string \"\" did not hash to zero", 0 == ""
- .hashCode());
- }
-
- /**
- * @tests java.lang.String#indexOf(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "indexOf",
- args = {int.class}
- )
- public void test_indexOfI() {
- // Test for method int java.lang.String.indexOf(int)
- assertEquals("Invalid index returned", 1, hw1.indexOf('e'));
-
- assertEquals("Doesn't return -1 if there is no such character.", -1,
- hw1.indexOf('q'));
- }
-
- /**
- * @tests java.lang.String#indexOf(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "indexOf",
- args = {int.class, int.class}
- )
- public void test_indexOfII() {
- // Test for method int java.lang.String.indexOf(int, int)
- assertEquals("Invalid character index returned", 5, hw1.indexOf('W', 2));
- assertEquals("Doesn't return -1 if there is no such character.", -1,
- hw1.indexOf('H', 2));
-
- }
-
- /**
- * @tests java.lang.String#indexOf(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "indexOf",
- args = {java.lang.String.class}
- )
- public void test_indexOfLjava_lang_String() {
- // Test for method int java.lang.String.indexOf(java.lang.String)
- assertTrue("Failed to find string", hw1.indexOf("World") > 0);
- assertTrue("Failed to find string", !(hw1.indexOf("ZZ") > 0));
- assertEquals("Doesn't return -1 for unknown string.",
- -1, hw1.indexOf("Heo"));
- }
-
- /**
- * @tests java.lang.String#indexOf(java.lang.String, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "indexOf",
- args = {java.lang.String.class, int.class}
- )
- public void test_indexOfLjava_lang_StringI() {
- // Test for method int java.lang.String.indexOf(java.lang.String, int)
- assertTrue("Failed to find string", hw1.indexOf("World", 0) > 0);
- assertTrue("Found string outside index", !(hw1.indexOf("Hello", 6) > 0));
- assertEquals("Did not accept valid negative starting position", 0, hello1
- .indexOf("", -5));
- assertEquals("Reported wrong error code", 5, hello1.indexOf("", 5));
- assertEquals("Wrong for empty in empty", 0, "".indexOf("", 0));
- }
-
- /**
- * @tests java.lang.String#intern()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "intern",
- args = {}
- )
- public void test_intern() {
- // Test for method java.lang.String java.lang.String.intern()
- assertTrue("Intern returned incorrect result", hw1.intern() == hw2
- .intern());
- }
-
- /**
- * @tests java.lang.String#lastIndexOf(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lastIndexOf",
- args = {int.class}
- )
- public void test_lastIndexOfI() {
- // Test for method int java.lang.String.lastIndexOf(int)
- assertEquals("Failed to return correct index", 5, hw1.lastIndexOf('W'));
- assertEquals("Returned index for non-existent char",
- -1, hw1.lastIndexOf('Z'));
-
- }
-
- /**
- * @tests java.lang.String#lastIndexOf(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lastIndexOf",
- args = {int.class, int.class}
- )
- public void test_lastIndexOfII() {
- // Test for method int java.lang.String.lastIndexOf(int, int)
- assertEquals("Failed to return correct index",
- 5, hw1.lastIndexOf('W', 6));
- assertEquals("Returned index for char out of specified range", -1, hw1
- .lastIndexOf('W', 4));
- assertEquals("Returned index for non-existent char", -1, hw1.lastIndexOf('Z',
- 9));
-
- }
-
- /**
- * @tests java.lang.String#lastIndexOf(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lastIndexOf",
- args = {java.lang.String.class}
- )
- public void test_lastIndexOfLjava_lang_String() {
- // Test for method int java.lang.String.lastIndexOf(java.lang.String)
- assertEquals("Returned incorrect index", 5, hw1.lastIndexOf("World"));
- assertEquals("Found String outside of index", -1, hw1
- .lastIndexOf("HeKKKKKKKK"));
- }
-
- /**
- * @tests java.lang.String#lastIndexOf(java.lang.String, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lastIndexOf",
- args = {java.lang.String.class, int.class}
- )
- public void test_lastIndexOfLjava_lang_StringI() {
- // Test for method int java.lang.String.lastIndexOf(java.lang.String,
- // int)
- assertEquals("Returned incorrect index", 5, hw1.lastIndexOf("World", 9));
- int result = hw1.lastIndexOf("Hello", 2);
- assertTrue("Found String outside of index: " + result, result == 0);
- assertEquals("Reported wrong error code",
- -1, hello1.lastIndexOf("", -5));
- assertEquals("Did not accept valid large starting position", 5, hello1
- .lastIndexOf("", 5));
- }
-
- /**
- * @tests java.lang.String#length()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "length",
- args = {}
- )
- public void test_length() {
- // Test for method int java.lang.String.length()
- assertEquals("Invalid length returned", 11, comp11.length());
- }
-
- /**
- * @tests java.lang.String#regionMatches(int, java.lang.String, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "regionMatches",
- args = {int.class, java.lang.String.class, int.class, int.class}
- )
- public void test_regionMatchesILjava_lang_StringII() {
- // Test for method boolean java.lang.String.regionMatches(int,
- // java.lang.String, int, int)
- String bogusString = "xxcedkedkleiorem lvvwr e''' 3r3r 23r";
-
- assertTrue("identical regions failed comparison", hw1.regionMatches(2,
- hw2, 2, 5));
- assertTrue("Different regions returned true", !hw1.regionMatches(2,
- bogusString, 2, 5));
- assertFalse("Returned true for negative offset.", hw1.regionMatches(-1,
- hw2, 2, 5));
- assertFalse("Returned true for negative offset.", hw1.regionMatches(2,
- hw2, -1, 5));
- assertFalse("Returned true for toffset+len is greater than the length.",
- hw1.regionMatches(5, hw2, 2, 6));
- assertFalse("Returned true for ooffset+len is greater than the length.",
- hw1.regionMatches(2, hw2, 5, 6));
- }
-
- /**
- * @tests java.lang.String#regionMatches(boolean, int, java.lang.String,
- * int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "regionMatches",
- args = {boolean.class, int.class, java.lang.String.class, int.class, int.class}
- )
- public void test_regionMatchesZILjava_lang_StringII() {
- // Test for method boolean java.lang.String.regionMatches(boolean, int,
- // java.lang.String, int, int)
-
- String bogusString = "xxcedkedkleiorem lvvwr e''' 3r3r 23r";
-
- assertTrue("identical regions failed comparison", hw1.regionMatches(
- false, 2, hw2, 2, 5));
- assertTrue("identical regions failed comparison with different cases",
- hw1.regionMatches(true, 2, hw2, 2, 5));
- assertTrue("Different regions returned true", !hw1.regionMatches(true,
- 2, bogusString, 2, 5));
- assertTrue("identical regions failed comparison with different cases",
- hw1.regionMatches(false, 2, hw2, 2, 5));
-
- assertFalse("Returned true for negative offset.", hw1.regionMatches(true,
- -1, hw2, 2, 5));
- assertFalse("Returned true for negative offset.", hw1.regionMatches(false,
- 2, hw2, -1, 5));
- assertFalse("Returned true for toffset+len is greater than the length.",
- hw1.regionMatches(true, 5, hw2, 2, 6));
- assertFalse("Returned true for ooffset+len is greater than the length.",
- hw1.regionMatches(false, 2, hw2, 5, 6));
-
- assertTrue("identical regions failed comparison", hwuc.regionMatches(
- true, 0, hwlc, 0, hwuc.length()));
- assertFalse("non identical regions failed comparison", hwuc.regionMatches(
- false, 0, hwlc, 0, hwuc.length()));
- }
-
- /**
- * @tests java.lang.String#replace(char, char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "replace",
- args = {char.class, char.class}
- )
- public void test_replaceCC() {
- // Test for method java.lang.String java.lang.String.replace(char, char)
- assertEquals("Failed replace", "HezzoWorzd", hw1.replace('l', 'z'));
- assertEquals("Returned incorrect string.", hw1, hw1.replace("!", "."));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "replaceAll",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_replaceAll() {
- String str = "!'123123.123HelloWorld!123123helloworld#";
- String [] patterns = {"[hw\\p{Upper}]", "(o|l){2,}", "([\'\"]?)(\\d+)",
- "^!.*#$"};
-
- String [] results = {"!\'123123.123?ello?orld!123123?ello?orld#",
- "!\'123123.123He?World!123123he?world#",
- "!?.?HelloWorld!?helloworld#", "?"};
-
- for(int i = 0; i < patterns.length; i++) {
- assertEquals("Returned incorrect string",
- results[i], str.replaceAll(patterns[i], "?"));
- }
-
- try {
- str.replaceAll("[abc*", "?");
- fail("PatternSyntaxException is not thrown.");
- } catch(PatternSyntaxException pse) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "replaceFirst",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_replaceFirst() {
- String str = "!'123123.123HelloWorld!123123helloworld#";
- String [] patterns = {"[hw\\p{Upper}]", "(o|l){2,}", "([\'\"]?)(\\d+)",
- "^!.*#$"};
-
- String [] results = {"!'123123.123?elloWorld!123123helloworld#",
- "!'123123.123He?World!123123helloworld#",
- "!?.123HelloWorld!123123helloworld#", "?"};
-
- for(int i = 0; i < patterns.length; i++) {
- assertEquals("Returned incorrect string",
- results[i], str.replaceFirst(patterns[i], "?"));
- }
-
- try {
- str.replaceFirst("[abc*", "?");
- fail("PatternSyntaxException is not thrown.");
- } catch(PatternSyntaxException pse) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "split",
- args = {java.lang.String.class}
- )
- public void test_splitLString() {
- String str = "!'123123.123HelloWorld!123123helloworld#";
- String [] patterns = {"[!.1]", "(\\d+).*e(l+)o.*orld"};
- String [][] results = {{"", "'","23", "23", "", "23HelloWorld", "", "23",
- "23helloworld#"},
- {"!'", "#"}};
-
- for(int i = 0; i < patterns.length; i++) {
- assertTrue("Returned incorrect string array for pattern: " +
- patterns[i], Arrays.equals(results[i], str.split(patterns[i])));
- }
-
- try {
- str.split("[a}");
- fail("PatternSyntaxException is not thrown.");
- } catch(PatternSyntaxException pse) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "split",
- args = {java.lang.String.class, int.class}
- )
- public void test_splitLStringLint() {
- String str = "!'123123.123HelloWorld!123123helloworld#";
- String pattern = "[!.1]";
- String [][] results = {{"", "'","23", "23.123HelloWorld!123123helloworld#"},
- {"", "'","23", "23", "", "23HelloWorld", "", "23",
- "23helloworld#"}};
-
- assertTrue("Returned incorrect string array for limit 4",
- Arrays.equals(results[0], str.split(pattern, 4)));
- assertTrue("Returned incorrect string array for limit 9",
- Arrays.equals(results[1], str.split(pattern, 9)));
- assertTrue("Returned incorrect string array for limit 0",
- Arrays.equals(results[1], str.split(pattern, 0)));
- assertTrue("Returned incorrect string array for limit -1",
- Arrays.equals(results[1], str.split(pattern, -1)));
- assertTrue("Returned incorrect string array for limit 10",
- Arrays.equals(results[1], str.split(pattern, 10)));
- assertTrue("Returned incorrect string array for limit Integer.MAX_VALUE",
- Arrays.equals(results[1], str.split(pattern, Integer.MAX_VALUE)));
-
- try {
- str.split("[a}", 0);
- fail("PatternSyntaxException is not thrown.");
- } catch(PatternSyntaxException pse) {
- //expected
- }
- }
-
-
-
- /**
- * @tests java.lang.String#replace(CharSequence, CharSequence)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "replace",
- args = {java.lang.CharSequence.class, java.lang.CharSequence.class}
- )
- public void test_replaceLjava_langCharSequenceLjava_langCharSequence() {
- assertEquals("Failed replace", "aaccdd", "aabbdd".replace(
- new StringBuffer("bb"), "cc"));
- assertEquals("Failed replace by bigger seq", "cccbccc", "aba".replace(
- "a", "ccc"));
- assertEquals("Failed replace by smaller seq", "$bba^",
- "$aaaaa^".replace(new StringBuilder("aa"), "b"));
-
- try {
- "".replace((CharSequence) null, "123".subSequence(0, 1));
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- try {
- "".replace("123".subSequence(0, 1), (CharSequence) null);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.String#startsWith(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "startsWith",
- args = {java.lang.String.class}
- )
- public void test_startsWithLjava_lang_String() {
- // Test for method boolean java.lang.String.startsWith(java.lang.String)
- assertTrue("Failed to find string", hw1.startsWith("Hello"));
- assertTrue("Found incorrect string", !hw1.startsWith("T"));
- }
-
- /**
- * @tests java.lang.String#startsWith(java.lang.String, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "startsWith",
- args = {java.lang.String.class, int.class}
- )
- public void test_startsWithLjava_lang_StringI() {
- // Test for method boolean java.lang.String.startsWith(java.lang.String,
- // int)
- assertTrue("Failed to find string", hw1.startsWith("World", 5));
- assertTrue("Found incorrect string", !hw1.startsWith("Hello", 5));
- }
-
- /**
- * @tests java.lang.String#substring(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "substring",
- args = {int.class}
- )
- public void test_substringI() {
- // Test for method java.lang.String java.lang.String.substring(int)
- assertEquals("Incorrect substring returned",
- "World", hw1.substring(5));
- assertTrue("not identical", hw1.substring(0) == hw1);
-
- try {
- hw1.substring(-1);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
-
- try {
- hw1.substring(hw1.length() + 1);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
-
- try {
- hw1.substring(Integer.MAX_VALUE);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.String#substring(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "substring",
- args = {int.class, int.class}
- )
- public void test_substringII() {
- // Test for method java.lang.String java.lang.String.substring(int, int)
- assertTrue("Incorrect substring returned", hw1.substring(0, 5).equals(
- "Hello")
- && (hw1.substring(5, 10).equals("World")));
- assertTrue("not identical", hw1.substring(0, hw1.length()) == hw1);
-
- try {
- hw1.substring(-1, hw1.length());
- fail("IndexOutOfBoundsException was not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
-
- try {
- hw1.substring(Integer.MAX_VALUE, hw1.length());
- fail("IndexOutOfBoundsException was not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
-
- try {
- hw1.substring(0, Integer.MAX_VALUE);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
- }
-
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "subSequence",
- args = {int.class, int.class}
- )
- public void test_subSequence() {
- // Test for method java.lang.String java.lang.String.substring(int, int)
- assertTrue("Incorrect substring returned", hw1.subSequence(0, 5).equals(
- "Hello") && (hw1.subSequence(5, 10).equals("World")));
- assertTrue("not identical", hw1.subSequence(0, hw1.length()) == hw1);
-
- try {
- hw1.subSequence(0, Integer.MAX_VALUE);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
-
- try {
- hw1.subSequence(Integer.MAX_VALUE, hw1.length());
- fail("IndexOutOfBoundsException was not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
-
- try {
- hw1.subSequence(-1, hw1.length());
- fail("IndexOutOfBoundsException was not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.String#toCharArray()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toCharArray",
- args = {}
- )
- public void test_toCharArray() {
- // Test for method char [] java.lang.String.toCharArray()
-
- String s = new String(buf, 0, buf.length);
- char[] schars = s.toCharArray();
- for (int i = 0; i < s.length(); i++)
- assertTrue("Returned incorrect char aray", buf[i] == schars[i]);
- }
-
- /**
- * @tests java.lang.String#toLowerCase()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toLowerCase",
- args = {}
- )
- public void test_toLowerCase() {
- // Test for method java.lang.String java.lang.String.toLowerCase()
- assertTrue("toLowerCase case conversion did not succeed", hwuc
- .toLowerCase().equals(hwlc));
-
- assertEquals("a) Sigma has same lower case value at end of word with Unicode 3.0",
- "\u03c3", "\u03a3".toLowerCase());
- assertEquals("b) Sigma has same lower case value at end of word with Unicode 3.0",
- "a \u03c3", "a \u03a3".toLowerCase());
- }
-
- /**
- * @tests java.lang.String#toLowerCase(java.util.Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toLowerCase",
- args = {java.util.Locale.class}
- )
- public void test_toLowerCaseLjava_util_Locale() {
- // Test for method java.lang.String
- // java.lang.String.toLowerCase(java.util.Locale)
- assertTrue("toLowerCase case conversion did not succeed", hwuc
- .toLowerCase(java.util.Locale.getDefault()).equals(hwlc));
- assertEquals("Invalid \\u0049 for English", "\u0069", "\u0049".toLowerCase(
- Locale.ENGLISH));
- assertEquals("Invalid \\u0049 for Turkish", "\u0131", "\u0049".toLowerCase(
- new Locale("tr", "")));
- }
-
- /**
- * @tests java.lang.String#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.lang.String.toString()
- assertTrue("Incorrect string returned", hw1.toString().equals(hw1));
- }
-
- /**
- * @tests java.lang.String#toUpperCase()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toUpperCase",
- args = {}
- )
- public void test_toUpperCase() {
- // Test for method java.lang.String java.lang.String.toUpperCase()
- assertTrue("Returned string is not UpperCase", hwlc.toUpperCase()
- .equals(hwuc));
-
- assertEquals("Wrong conversion", "SS", "\u00df".toUpperCase());
-
- String s = "a\u00df\u1f56";
- assertTrue("Invalid conversion", !s.toUpperCase().equals(s));
-
- }
-
- /**
- * @tests java.lang.String#toUpperCase(java.util.Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toUpperCase",
- args = {java.util.Locale.class}
- )
- public void test_toUpperCaseLjava_util_Locale() {
- // Test for method java.lang.String
- // java.lang.String.toUpperCase(java.util.Locale)
- assertTrue("Returned string is not UpperCase", hwlc.toUpperCase()
- .equals(hwuc));
- assertEquals("Invalid \\u0069 for English", "\u0049", "\u0069".toUpperCase(
- Locale.ENGLISH));
- assertEquals("Invalid \\u0069 for Turkish", "\u0130", "\u0069".toUpperCase(
- new Locale("tr", "")));
- }
-
- /**
- * @tests java.lang.String#trim()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "trim",
- args = {}
- )
- public void test_trim() {
- // Test for method java.lang.String java.lang.String.trim()
- assertTrue("Incorrect string returned", " HelloWorld ".trim().equals(
- hw1));
- assertEquals("Incorrect string returned", hw1, " HelloWorld ".trim());
- assertTrue("Incorrect string returned", " ".trim().equals(""));
- }
-
- /**
- * @tests java.lang.String#valueOf(char[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {char[].class}
- )
- public void test_valueOf$C() {
- // Test for method java.lang.String java.lang.String.valueOf(char [])
- assertEquals("Returned incorrect String",
- "World", String.valueOf(buf));
- assertEquals("Returned incorrect String",
- "", String.valueOf(new char[]{}));
- try {
- String.valueOf(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.String#valueOf(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {char[].class, int.class, int.class}
- )
- public void test_valueOf$CII() {
- // Test for method java.lang.String java.lang.String.valueOf(char [],
- // int, int)
- char[] t = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
- assertEquals("copyValueOf returned incorrect String", "World", String.valueOf(t,
- 5, 5));
-
- try {
- String.valueOf(t, 0, t.length + 1);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
-
- try {
- String.valueOf(t, 0, -1);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
-
- try {
- String.valueOf(t, 0, Integer.MAX_VALUE);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.String#valueOf(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {char.class}
- )
- public void test_valueOfC() {
- // Test for method java.lang.String java.lang.String.valueOf(char)
- for (int i = 0; i < 65536; i++)
- assertTrue("Incorrect valueOf(char) returned: " + i, String
- .valueOf((char) i).charAt(0) == (char) i);
- }
-
- /**
- * @tests java.lang.String#valueOf(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {double.class}
- )
- public void test_valueOfD() {
- // Test for method java.lang.String java.lang.String.valueOf(double)
- assertEquals("Incorrect double string returned", "1.7976931348623157E308", String.valueOf(
- Double.MAX_VALUE));
- }
-
- /**
- * @tests java.lang.String#valueOf(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {float.class}
- )
- public void test_valueOfF() {
- // Test for method java.lang.String java.lang.String.valueOf(float)
- assertTrue("incorrect float string returned--got: "
- + String.valueOf(1.0F) + " wanted: 1.0", String.valueOf(1.0F)
- .equals("1.0"));
- assertTrue("incorrect float string returned--got: "
- + String.valueOf(0.9F) + " wanted: 0.9", String.valueOf(0.9F)
- .equals("0.9"));
- assertTrue("incorrect float string returned--got: "
- + String.valueOf(109.567F) + " wanted: 109.567", String
- .valueOf(109.567F).equals("109.567"));
- }
-
- /**
- * @tests java.lang.String#valueOf(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {int.class}
- )
- public void test_valueOfI() {
- // Test for method java.lang.String java.lang.String.valueOf(int)
- assertEquals("returned invalid int string", "1", String.valueOf(1));
- }
-
- /**
- * @tests java.lang.String#valueOf(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {long.class}
- )
- public void test_valueOfJ() {
- // Test for method java.lang.String java.lang.String.valueOf(long)
- assertEquals("returned incorrect long string", "927654321098", String.valueOf(
- 927654321098L));
- }
-
- /**
- * @tests java.lang.String#valueOf(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {java.lang.Object.class}
- )
- public void test_valueOfLjava_lang_Object() {
- // Test for method java.lang.String
- // java.lang.String.valueOf(java.lang.Object)
- assertTrue("Incorrect Object string returned", obj.toString().equals(
- String.valueOf(obj)));
- assertEquals("Incorrect value was returned for null.",
- "null", String.valueOf((Object) null));
- }
-
- /**
- * @tests java.lang.String#valueOf(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {boolean.class}
- )
- public void test_valueOfZ() {
- // Test for method java.lang.String java.lang.String.valueOf(boolean)
- assertTrue("Incorrect boolean string returned", String.valueOf(false)
- .equals("false")
- && (String.valueOf(true).equals("true")));
- }
-
- /**
- * @tests java.lang.String#contentEquals(CharSequence cs)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "NullPointerException is not verified.",
- method = "contentEquals",
- args = {java.lang.CharSequence.class}
- )
- public void test_contentEqualsLjava_lang_CharSequence() {
- // Test for method java.lang.String java.lang.String.contentEquals(CharSequence cs)
- assertFalse("Incorrect result of compare", "qwerty".contentEquals(""));
- }
-
- /**
- * @tests java.lang.String#format(Locale, String, Object[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- @SuppressWarnings("boxing")
- public void test_format() {
- assertEquals("13% of sum is 0x11",
- String.format("%d%% of %s is 0x%x", 13, "sum", 17));
-
- assertEquals("3 2 1 4 3 2 1", String.format(
- "%3$d %2$d %1$d %4$d %3$d %2$d %1$d", 1, 2, 3, 4));
-
- assertEquals("empty format", "", String.format("", 123, this));
- try {
- String.format(null);
- fail("NPE is expected on null format");
- } catch (NullPointerException ok){}
-
- try {
- String.format("%d%% of %s is 0x%x", "123");
- fail("IllegalFormatException was not thrown.");
- } catch(IllegalFormatException ife) {
- //expected
- }
-
- try {
- String.format("%tu", "123");
- fail("IllegalFormatException was not thrown.");
- } catch(IllegalFormatException ife) {
- //expected
- }
-
- }
-
- /**
- * @tests java.lang.String#format(Locale, String, Object...)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "format",
- args = {java.util.Locale.class, java.lang.String.class, java.lang.Object[].class}
- )
- @SuppressWarnings("boxing")
- public void test_format_Locale() {
- Locale l = new Locale("UK");
- assertEquals("13% of sum is 0x11",
- String.format(l, "%d%% of %s is 0x%x", 13, "sum", 17));
- assertEquals("empty format", "", String.format("", 123, this));
- try {
- String.format(l, null, "");
- fail("NPE is expected on null format");
- } catch (NullPointerException ok){}
-
- try {
- String.format(l, "%d", "test");
- fail("IllegalFormatException wasn't thrown.");
- } catch(IllegalFormatException ife) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "matches",
- args = {java.lang.String.class}
- )
- public void test_matches() {
- String[] patterns = {
- "(a|b)*abb",
- "(1*2*3*4*)*567",
- "(a|b|c|d)*aab",
- "(1|2|3|4|5|6|7|8|9|0)(1|2|3|4|5|6|7|8|9|0)*",
- "(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ)*",
- "(a|b)*(a|b)*A(a|b)*lice.*",
- "(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)*(1|2|3|4|5|6|7|8|9|0)*|while|for|struct|if|do",
-
- };
-
- String[] patternsInc = {
- "(ac)*bb",
- "(1)*567",
- "(c)*ab",
- "(|8|9|0)(1|2|7|8|9|0)*",
- "(z)",
- "(a)*A(b)*lice.",
- "(a|b|c|d|e)",
-
- };
-
- String[][] strings = {
- { "abb", "ababb", "abababbababb", "abababbababbabababbbbbabb" },
- { "213567", "12324567", "1234567", "213213567",
- "21312312312567", "444444567" },
- { "abcdaab", "aab", "abaab", "cdaab", "acbdadcbaab" },
- { "213234567", "3458", "0987654", "7689546432", "0398576",
- "98432", "5" },
- {
- "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
- "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
- + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" },
- { "ababbaAabababblice", "ababbaAliceababab", "ababbAabliceaaa",
- "abbbAbbbliceaaa", "Alice" },
- { "a123", "bnxnvgds156", "for", "while", "if", "struct" },
- { "xy" }, { "xy" }, { "xcy" }
-
- };
-
- for (int i = 0; i < patterns.length; i++) {
- for (int j = 0; j < strings[i].length; j++) {
- assertTrue("Incorrect match: " + patterns[i] + " vs "
- + strings[i][j], strings[i][j].matches(patterns[i]));
- assertFalse("" + i, strings[i][j].matches(patternsInc[i]));
- }
- }
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBuffer2Test.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBuffer2Test.java
deleted file mode 100644
index 8b03ced..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBuffer2Test.java
+++ /dev/null
@@ -1,1107 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(StringBuffer.class)
-public class StringBuffer2Test extends junit.framework.TestCase {
-
- StringBuffer testBuffer;
-
- /**
- * @tests java.lang.StringBuffer#StringBuffer()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StringBuffer",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.lang.StringBuffer()
- new StringBuffer();
- assertTrue("Invalid buffer created", true);
- }
-
- /**
- * @tests java.lang.StringBuffer#StringBuffer(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StringBuffer",
- args = {int.class}
- )
- public void test_ConstructorI() {
- // Test for method java.lang.StringBuffer(int)
- StringBuffer sb = new StringBuffer(8);
- assertEquals("Newly constructed buffer is of incorrect length", 0, sb
- .length());
- }
-
- /**
- * @tests java.lang.StringBuffer#StringBuffer(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StringBuffer",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.lang.StringBuffer(java.lang.String)
-
- StringBuffer sb = new StringBuffer("HelloWorld");
-
- assertTrue("Invalid buffer created", sb.length() == 10
- && (sb.toString().equals("HelloWorld")));
-
- boolean pass = false;
- try {
- new StringBuffer(null);
- } catch (NullPointerException e) {
- pass = true;
- }
- assertTrue("Should throw NullPointerException", pass);
- }
-
- /**
- * @tests java.lang.StringBuffer#append(char[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {char[].class}
- )
- public void test_append$C() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.append(char [])
- char buf[] = new char[4];
- "char".getChars(0, 4, buf, 0);
- testBuffer.append(buf);
- assertEquals("Append of char[] failed",
- "This is a test bufferchar", testBuffer.toString());
- }
-
- /**
- * @tests java.lang.StringBuffer#append(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "append",
- args = {char[].class, int.class, int.class}
- )
- public void test_append$CII() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.append(char [], int, int)
- StringBuffer sb = new StringBuffer();
- char[] buf1 = { 'H', 'e', 'l', 'l', 'o' };
- char[] buf2 = { 'W', 'o', 'r', 'l', 'd' };
- sb.append(buf1, 0, buf1.length);
- assertEquals("Buffer is invalid length after append", 5, sb.length());
- sb.append(buf2, 0, buf2.length);
- assertEquals("Buffer is invalid length after append", 10, sb.length());
- assertTrue("Buffer contains invalid chars", (sb.toString()
- .equals("HelloWorld")));
- }
-
- /**
- * @tests java.lang.StringBuffer#append(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {char.class}
- )
- public void test_appendC() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.append(char)
- StringBuffer sb = new StringBuffer();
- char buf1 = 'H';
- char buf2 = 'W';
- sb.append(buf1);
- assertEquals("Buffer is invalid length after append", 1, sb.length());
- sb.append(buf2);
- assertEquals("Buffer is invalid length after append", 2, sb.length());
- assertTrue("Buffer contains invalid chars",
- (sb.toString().equals("HW")));
- }
-
- /**
- * @tests java.lang.StringBuffer#append(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {double.class}
- )
- public void test_appendD() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.append(double)
- StringBuffer sb = new StringBuffer();
- sb.append(Double.MAX_VALUE);
- assertEquals("Buffer is invalid length after append", 22, sb.length());
- assertEquals("Buffer contains invalid characters",
- "1.7976931348623157E308", sb.toString());
- }
-
- /**
- * @tests java.lang.StringBuffer#append(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {float.class}
- )
- public void test_appendF() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.append(float)
- StringBuffer sb = new StringBuffer();
- final float floatNum = 900.87654F;
- sb.append(floatNum);
- assertTrue("Buffer is invalid length after append: " + sb.length(), sb
- .length() == String.valueOf(floatNum).length());
- assertTrue("Buffer contains invalid characters", sb.toString().equals(
- String.valueOf(floatNum)));
- }
-
- /**
- * @tests java.lang.StringBuffer#append(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {int.class}
- )
- public void test_appendI() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.append(int)
- StringBuffer sb = new StringBuffer();
- sb.append(9000);
- assertEquals("Buffer is invalid length after append", 4, sb.length());
- sb.append(1000);
- assertEquals("Buffer is invalid length after append", 8, sb.length());
- assertEquals("Buffer contains invalid characters",
- "90001000", sb.toString());
- }
-
- /**
- * @tests java.lang.StringBuffer#append(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {long.class}
- )
- public void test_appendJ() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.append(long)
-
- StringBuffer sb = new StringBuffer();
- long t = 927654321098L;
- sb.append(t);
- assertEquals("Buffer is of invlaid length", 12, sb.length());
- assertEquals("Buffer contains invalid characters",
- "927654321098", sb.toString());
- }
-
- /**
- * @tests java.lang.StringBuffer#append(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {java.lang.Object.class}
- )
- public void test_appendLjava_lang_Object() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.append(java.lang.Object)
- StringBuffer sb = new StringBuffer();
- Object obj1 = new Object();
- Object obj2 = new Object();
- sb.append(obj1);
- sb.append(obj2);
- assertTrue("Buffer contains invalid characters", sb.toString().equals(
- obj1.toString() + obj2.toString()));
- }
-
- /**
- * @tests java.lang.StringBuffer#append(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {java.lang.String.class}
- )
- public void test_appendLjava_lang_String() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.append(java.lang.String)
- StringBuffer sb = new StringBuffer();
- String buf1 = "Hello";
- String buf2 = "World";
- sb.append(buf1);
- assertEquals("Buffer is invalid length after append", 5, sb.length());
- sb.append(buf2);
- assertEquals("Buffer is invalid length after append", 10, sb.length());
- assertTrue("Buffer contains invalid chars", (sb.toString()
- .equals("HelloWorld")));
- }
-
- /**
- * @tests java.lang.StringBuffer#append(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {boolean.class}
- )
- public void test_appendZ() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.append(boolean)
- StringBuffer sb = new StringBuffer();
- sb.append(false);
- assertEquals("Buffer is invalid length after append", 5, sb.length());
- sb.append(true);
- assertEquals("Buffer is invalid length after append", 9, sb.length());
- assertTrue("Buffer is invalid length after append", (sb.toString()
- .equals("falsetrue")));
- }
-
- /**
- * @tests java.lang.StringBuffer#capacity()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "capacity",
- args = {}
- )
- public void test_capacity() {
- // Test for method int java.lang.StringBuffer.capacity()
- StringBuffer sb = new StringBuffer(10);
- assertEquals("Returned incorrect capacity", 10, sb.capacity());
- sb.ensureCapacity(100);
- assertTrue("Returned incorrect capacity", sb.capacity() >= 100);
- }
-
- /**
- * @tests java.lang.StringBuffer#charAt(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "charAt",
- args = {int.class}
- )
- public void test_charAtI() {
- // Test for method char java.lang.StringBuffer.charAt(int)
- assertEquals("Returned incorrect char", 's', testBuffer.charAt(3));
-
- // Test for StringIndexOutOfBoundsException
- boolean exception = false;
- try {
- testBuffer.charAt(-1);
- } catch (StringIndexOutOfBoundsException e) {
- exception = true;
- } catch (ArrayIndexOutOfBoundsException e) {
- }
- assertTrue("Should throw StringIndexOutOfBoundsException", exception);
- }
-
- /**
- * @tests java.lang.StringBuffer#delete(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "delete",
- args = {int.class, int.class}
- )
- public void test_deleteII() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.delete(int, int)
- testBuffer.delete(7, 7);
- assertEquals("Deleted chars when start == end", "This is a test buffer", testBuffer.toString()
- );
- testBuffer.delete(4, 14);
- assertEquals("Deleted incorrect chars",
- "This buffer", testBuffer.toString());
-
- testBuffer = new StringBuffer("This is a test buffer");
- String sharedStr = testBuffer.toString();
- testBuffer.delete(0, testBuffer.length());
- assertEquals("Didn't clone shared buffer", "This is a test buffer", sharedStr
- );
- assertTrue("Deleted incorrect chars", testBuffer.toString().equals(""));
- testBuffer.append("more stuff");
- assertEquals("Didn't clone shared buffer 2", "This is a test buffer", sharedStr
- );
- assertEquals("Wrong contents", "more stuff", testBuffer.toString());
- try {
- testBuffer.delete(-5, 2);
- } catch (IndexOutOfBoundsException e) {
- }
- assertEquals("Wrong contents 2",
- "more stuff", testBuffer.toString());
- }
-
- /**
- * @tests java.lang.StringBuffer#deleteCharAt(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "deleteCharAt",
- args = {int.class}
- )
- public void test_deleteCharAtI() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.deleteCharAt(int)
- testBuffer.deleteCharAt(3);
- assertEquals("Deleted incorrect char",
- "Thi is a test buffer", testBuffer.toString());
- try {
- testBuffer.deleteCharAt(testBuffer.length() + 1);
- fail("StringIndexOutOfBoundsException was not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
-
- try {
- testBuffer.deleteCharAt(-1);
- fail("StringIndexOutOfBoundsException was not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer#ensureCapacity(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ensureCapacity",
- args = {int.class}
- )
- @KnownFailure("Google TODO 1481226")
- public void test_ensureCapacityI() {
- // Test for method void java.lang.StringBuffer.ensureCapacity(int)
- StringBuffer sb = new StringBuffer(10);
-
- sb.ensureCapacity(-2);
- assertEquals("Failed to increase capacity.", 10, sb.capacity());
-
- sb.ensureCapacity(100);
- assertTrue("Failed to increase capacity", sb.capacity() >= 100);
-
- try {
- sb.ensureCapacity(Integer.MAX_VALUE);
- fail("OutOfMemoryError should be thrown.");
- } catch(java.lang.OutOfMemoryError oome) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer#getChars(int, int, char[], int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't check exceptions.",
- method = "getChars",
- args = {int.class, int.class, char[].class, int.class}
- )
- public void test_getCharsII$CI() {
- // Test for method void java.lang.StringBuffer.getChars(int, int, char
- // [], int)
-
- char[] buf = new char[10];
- testBuffer.getChars(4, 8, buf, 2);
- assertTrue("Returned incorrect chars", new String(buf, 2, 4)
- .equals(testBuffer.toString().substring(4, 8)));
-
- StringBuffer buf2 = new StringBuffer("");
- try {
- buf2.getChars(-1, 0, new char[5], 2);
- fail("IndexOutOfBoundsException is not thrown.");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- buf2.getChars(0, -1, new char[5], 2);
- fail("IndexOutOfBoundsException is not thrown.");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- buf2.getChars(0, -1, new char[5], 2);
- fail("IndexOutOfBoundsException is not thrown.");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- buf2.getChars(2, 1, new char[5], 2);
- fail("IndexOutOfBoundsException is not thrown.");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- buf2.getChars(0, 6, new char[5], 2);
- fail("IndexOutOfBoundsException is not thrown.");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- buf2.getChars(0, 6, new char[10], 5);
- fail("IndexOutOfBoundsException is not thrown.");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer#insert(int, char[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, char[].class}
- )
- public void test_insertI$C() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.insert(int, char [])
- char buf[] = new char[4];
- "char".getChars(0, 4, buf, 0);
- testBuffer.insert(15, buf);
- assertEquals("Insert test failed",
- "This is a test charbuffer", testBuffer.toString());
-
- boolean exception = false;
- StringBuffer buf1 = new StringBuffer("abcd");
- try {
- buf1.insert(-1, (char[]) null);
- } catch (StringIndexOutOfBoundsException e) {
- exception = true;
- } catch (NullPointerException e) {
- }
- assertTrue("Should throw StringIndexOutOfBoundsException", exception);
- }
-
- /**
- * @tests java.lang.StringBuffer#insert(int, char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, char[].class, int.class, int.class}
- )
- public void test_insertI$CII() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.insert(int, char [], int, int)
- char[] c = new char[] { 'n', 'o', 't', ' ' };
- testBuffer.insert(8, c, 0, 4);
- assertEquals("This is not a test buffer", testBuffer.toString());
-
- StringBuffer buf1 = new StringBuffer("abcd");
- try {
- buf1.insert(-1, (char[]) null, 0, 0);
- fail("Should throw StringIndexOutOfBoundsException");
- } catch (StringIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- testBuffer.insert(testBuffer.length() - 1, c, -1, 1);
- } catch (StringIndexOutOfBoundsException e) {
- //expected
- }
-
- }
-
- /**
- * @tests java.lang.StringBuffer#insert(int, char)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IndexOutOfBoundsException is not verified.",
- method = "insert",
- args = {int.class, char.class}
- )
- public void test_insertIC() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.insert(int, char)
- testBuffer.insert(15, 'T');
- assertEquals("Insert test failed",
- "This is a test Tbuffer", testBuffer.toString());
- }
-
- /**
- * @tests java.lang.StringBuffer#insert(int, double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, double.class}
- )
- public void test_insertID() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.insert(int, double)
- testBuffer.insert(15, Double.MAX_VALUE);
- assertTrue("Insert test failed", testBuffer.toString().equals(
- "This is a test " + Double.MAX_VALUE + "buffer"));
- try {
- testBuffer.insert(-1, Double.MAX_VALUE);
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
-
- try {
- testBuffer.insert(testBuffer.length() + 1, Double.MAX_VALUE);
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer#insert(int, float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, float.class}
- )
- public void test_insertIF() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.insert(int, float)
- testBuffer.insert(15, Float.MAX_VALUE);
- String testBufferString = testBuffer.toString();
- String expectedResult = "This is a test "
- + String.valueOf(Float.MAX_VALUE) + "buffer";
- assertTrue("Insert test failed, got: " + "\'" + testBufferString + "\'"
- + " but wanted: " + "\'" + expectedResult + "\'",
- testBufferString.equals(expectedResult));
-
- try {
- testBuffer.insert(-1, Float.MAX_VALUE);
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
-
- try {
- testBuffer.insert(testBuffer.length() + 1, Float.MAX_VALUE);
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer#insert(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, int.class}
- )
- public void test_insertII() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.insert(int, int)
- testBuffer.insert(15, 100);
- assertEquals("Insert test failed",
- "This is a test 100buffer", testBuffer.toString());
-
- try {
- testBuffer.insert(-1, Integer.MAX_VALUE);
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
-
- try {
- testBuffer.insert(testBuffer.length() + 1, Integer.MAX_VALUE);
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer#insert(int, long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, long.class}
- )
- public void test_insertIJ() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.insert(int, long)
- testBuffer.insert(15, 88888888888888888L);
- assertEquals("Insert test failed",
- "This is a test 88888888888888888buffer", testBuffer.toString());
-
- try {
- testBuffer.insert(-1, Long.MAX_VALUE);
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
-
- try {
- testBuffer.insert(testBuffer.length() + 1, Long.MAX_VALUE);
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer#insert(int, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, java.lang.Object.class}
- )
- public void test_insertILjava_lang_Object() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.insert(int, java.lang.Object)
- Object obj1 = new Object();
- testBuffer.insert(15, obj1);
- assertTrue("Insert test failed", testBuffer.toString().equals(
- "This is a test " + obj1.toString() + "buffer"));
-
- try {
- testBuffer.insert(-1, obj1);
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
-
- try {
- testBuffer.insert(testBuffer.length() + 1, obj1);
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer#insert(int, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, java.lang.String.class}
- )
- public void test_insertILjava_lang_String() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.insert(int, java.lang.String)
-
- testBuffer.insert(15, "STRING ");
- assertEquals("Insert test failed",
- "This is a test STRING buffer", testBuffer.toString());
-
- try {
- testBuffer.insert(-1, "");
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
-
- try {
- testBuffer.insert(testBuffer.length() + 1, "");
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer#insert(int, boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, boolean.class}
- )
- public void test_insertIZ() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.insert(int, boolean)
- testBuffer.insert(15, true);
- assertEquals("Insert test failed",
- "This is a test truebuffer", testBuffer.toString());
- try {
- testBuffer.insert(testBuffer.length() + 1, true);
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
-
- try {
- testBuffer.insert(-1, true);
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer#length()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "length",
- args = {}
- )
- public void test_length() {
- // Test for method int java.lang.StringBuffer.length()
- assertEquals("Incorrect length returned", 21, testBuffer.length());
- }
-
- /**
- * @tests java.lang.StringBuffer#replace(int, int, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "replace",
- args = {int.class, int.class, java.lang.String.class}
- )
- public void test_replaceIILjava_lang_String() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.replace(int, int, java.lang.String)
- testBuffer.replace(5, 9, "is a replaced");
- assertTrue("Replace failed, wanted: " + "\'"
- + "This is a replaced test buffer" + "\'" + " but got: " + "\'"
- + testBuffer.toString() + "\'", testBuffer.toString().equals(
- "This is a replaced test buffer"));
- assertEquals("insert1", "text", new StringBuffer().replace(0, 0, "text")
- .toString());
- assertEquals("insert2", "123text", new StringBuffer("123").replace(3, 3, "text")
- .toString());
- assertEquals("insert2", "1text23", new StringBuffer("123").replace(1, 1, "text")
- .toString());
-
- try {
- testBuffer.replace(-1, 0, "text");
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
-
- try {
- testBuffer.replace(0, -1, "text");
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
-
- try {
- testBuffer.replace(2, 1, "text");
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
-
- try {
- testBuffer.replace(testBuffer.length() + 1, testBuffer.length() + 1,
- "text");
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException sioobe) {
- //expected
- }
- }
-
- private String writeString(String in) {
- StringBuffer result = new StringBuffer();
- result.append("\"");
- for (int i = 0; i < in.length(); i++) {
- result.append(" 0x" + Integer.toHexString(in.charAt(i)));
- }
- result.append("\"");
- return result.toString();
- }
-
- private void reverseTest(String id, String org, String rev, String back) {
- // create non-shared StringBuffer
- StringBuffer sb = new StringBuffer(org);
- sb.reverse();
- String reversed = sb.toString();
- assertTrue("reversed surrogate " + id + ": " + writeString(reversed),
- reversed.equals(rev));
- // create non-shared StringBuffer
- sb = new StringBuffer(reversed);
- sb.reverse();
- reversed = sb.toString();
- assertTrue("reversed surrogate " + id + "a: " + writeString(reversed),
- reversed.equals(back));
-
- // test algorithm when StringBuffer is shared
- sb = new StringBuffer(org);
- String copy = sb.toString();
- assertEquals(org, copy);
- sb.reverse();
- reversed = sb.toString();
- assertTrue("reversed surrogate " + id + ": " + writeString(reversed),
- reversed.equals(rev));
- sb = new StringBuffer(reversed);
- copy = sb.toString();
- assertEquals(rev, copy);
- sb.reverse();
- reversed = sb.toString();
- assertTrue("reversed surrogate " + id + "a: " + writeString(reversed),
- reversed.equals(back));
-
- }
-
- /**
- * @tests java.lang.StringBuffer#reverse()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reverse",
- args = {}
- )
- public void test_reverse() {
- // Test for method java.lang.StringBuffer
- // java.lang.StringBuffer.reverse()
- String org;
- org = "a";
- reverseTest("0", org, org, org);
-
- org = "ab";
- reverseTest("1", org, "ba", org);
-
- org = "abcdef";
- reverseTest("2", org, "fedcba", org);
-
- org = "abcdefg";
- reverseTest("3", org, "gfedcba", org);
-
- }
-
- /**
- * @tests java.lang.StringBuffer#setCharAt(int, char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setCharAt",
- args = {int.class, char.class}
- )
- public void test_setCharAtIC() {
- // Test for method void java.lang.StringBuffer.setCharAt(int, char)
- StringBuffer s = new StringBuffer("HelloWorld");
- s.setCharAt(4, 'Z');
- assertEquals("Returned incorrect char", 'Z', s.charAt(4));
-
- try {
- s.setCharAt(-1, 'Z');
- fail("IndexOutOfBoundsException is not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
- try {
- s.setCharAt(s.length() + 1, 'Z');
- fail("IndexOutOfBoundsException is not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer#setLength(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IndexOutOfBoundsException is not verified.",
- method = "setLength",
- args = {int.class}
- )
- public void test_setLengthI() {
- // Test for method void java.lang.StringBuffer.setLength(int)
- testBuffer.setLength(1000);
- assertEquals("Failed to increase length", 1000, testBuffer.length());
- assertTrue("Increase in length trashed buffer", testBuffer.toString()
- .startsWith("This is a test buffer"));
- testBuffer.setLength(2);
- assertEquals("Failed to decrease length", 2, testBuffer.length());
- assertEquals("Decrease in length failed",
- "Th", testBuffer.toString());
- }
-
- /**
- * @tests java.lang.StringBuffer#substring(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "substring",
- args = {int.class}
- )
- public void test_substringI() {
- // Test for method java.lang.String
- // java.lang.StringBuffer.substring(int)
- assertEquals("Returned incorrect substring", "is a test buffer",
- testBuffer.substring(5));
-
- try {
- testBuffer.substring(testBuffer.length() + 1);
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException oobe) {
- //expected
- }
-
- try {
- testBuffer.substring(-1);
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException oobe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer#substring(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "substring",
- args = {int.class, int.class}
- )
- public void test_substringII() {
- // Test for method java.lang.String
- // java.lang.StringBuffer.substring(int, int)
- assertEquals("Returned incorrect substring", "is",
- testBuffer.substring(5, 7));
-
- try {
- testBuffer.substring(-1, testBuffer.length());
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException oobe) {
- //expected
- }
-
- try {
- testBuffer.substring(0, -1);
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException oobe) {
- //expected
- }
-
- try {
- testBuffer.substring(2, 1);
- fail("StringIndexOutOfBoundsException is not thrown.");
- } catch(StringIndexOutOfBoundsException oobe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.lang.StringBuffer.toString()
- assertEquals("Incorrect string value returned", "This is a test buffer", testBuffer.toString()
- );
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "subSequence",
- args = {int.class, int.class}
- )
- public void test_subSequence() {
-
- assertEquals("Incorrect substring returned", " is",
- testBuffer.subSequence(4, 7));
- assertEquals("Incorrect substring returned", "test buffer",
- testBuffer.subSequence(10, 21));
- assertEquals("not identical", "This is a test buffer",
- testBuffer.subSequence(0, testBuffer.length()));
-
- try {
- testBuffer.subSequence(0, Integer.MAX_VALUE);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
-
- try {
- testBuffer.subSequence(Integer.MAX_VALUE, testBuffer.length());
- fail("IndexOutOfBoundsException was not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
-
- try {
- testBuffer.subSequence(-1, testBuffer.length());
- fail("IndexOutOfBoundsException was not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
- }
-
- @Override
- protected void setUp() {
- testBuffer = new StringBuffer("This is a test buffer");
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBufferTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBufferTest.java
deleted file mode 100644
index 79b87fc..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBufferTest.java
+++ /dev/null
@@ -1,718 +0,0 @@
-/* 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.Serializable;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(StringBuffer.class)
-public class StringBufferTest extends TestCase {
-
- /**
- * @tests java.lang.StringBuffer#setLength(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IndexOutOfBoundsException.",
- method = "setLength",
- args = {int.class}
- )
- public void test_setLengthI() {
- // Regression for HARMONY-90
- StringBuffer buffer = new StringBuffer("abcde");
- try {
- buffer.setLength(-1);
- fail("Assert 0: IndexOutOfBoundsException must be thrown");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- /**
- * @tests StringBuffer.StringBuffer(CharSequence);
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StringBuffer",
- args = {java.lang.CharSequence.class}
- )
- public void test_constructorLjava_lang_CharSequence() {
- String str = "Test string";
- StringBuffer sb = new StringBuffer((CharSequence) str);
- assertEquals(str.length(), sb.length());
-
- try {
- new StringBuffer((CharSequence) null);
- fail("Assert 0: NPE must be thrown.");
- } catch (NullPointerException e) {}
-
- assertEquals("Assert 1: must equal 'abc'.", "abc", new StringBuffer((CharSequence)"abc").toString());
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "trimToSize",
- args = {}
- )
- public void test_trimToSize() {
- StringBuffer buffer = new StringBuffer(25);
- buffer.append("abc");
- int origCapacity = buffer.capacity();
- buffer.trimToSize();
- int trimCapacity = buffer.capacity();
- assertTrue("Assert 0: capacity must be smaller.", trimCapacity < origCapacity);
- assertEquals("Assert 1: length must still be 3", 3, buffer.length());
- assertEquals("Assert 2: value must still be 'abc'.", "abc", buffer.toString());
- }
-
- /**
- * @tests java.lang.StringBuffer.append(CharSequence)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {java.lang.CharSequence.class}
- )
- public void test_appendLjava_lang_CharSequence() {
- StringBuffer sb = new StringBuffer();
- assertSame(sb, sb.append((CharSequence) "ab"));
- assertEquals("ab", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append((CharSequence) "cd"));
- assertEquals("cd", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append((CharSequence) null));
- assertEquals("null", sb.toString());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {java.lang.StringBuffer.class}
- )
- public void test_appendLStringBuffer() {
- StringBuffer originalSB = new StringBuffer();
- StringBuffer sb1 = new StringBuffer("append1");
- StringBuffer sb2 = new StringBuffer("append2");
- originalSB.append(sb1);
- assertEquals(sb1.toString(), originalSB.toString());
- originalSB.append(sb2);
- assertEquals(sb1.toString() + sb2.toString(), originalSB.toString());
- originalSB.append((StringBuffer) null);
- assertEquals(sb1.toString() + sb2.toString() + "null",
- originalSB.toString());
- }
-
- /**
- * @tests java.lang.StringBuffer.append(CharSequence, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {java.lang.CharSequence.class, int.class, int.class}
- )
- @SuppressWarnings("cast")
- public void test_appendLjava_lang_CharSequenceII() {
- StringBuffer sb = new StringBuffer();
- assertSame(sb, sb.append((CharSequence) "ab", 0, 2));
- assertEquals("ab", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append((CharSequence) "cd", 0, 2));
- assertEquals("cd", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append((CharSequence) "abcd", 0, 2));
- assertEquals("ab", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append((CharSequence) "abcd", 2, 4));
- assertEquals("cd", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append((CharSequence) null, 0, 2));
- assertEquals("nu", sb.toString());
-
- try {
- sb.append((CharSequence) "abcd", -1, 2);
- fail("IndexOutOfBoundsException was thrown.");
- } catch(IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer.append(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ArrayIndexOutOfBoundsException.",
- method = "append",
- args = {char[].class, int.class, int.class}
- )
- public void test_append$CII_2() {
- StringBuffer obj = new StringBuffer();
- try {
- obj.append(new char[0], -1, -1);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer.append(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "append",
- args = {char[].class, int.class, int.class}
- )
- public void test_append$CII_3() throws Exception {
- StringBuffer obj = new StringBuffer();
- try {
- obj.append((char[]) null, -1, -1);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer.insert(int, CharSequence)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, java.lang.CharSequence.class}
- )
- public void test_insertILjava_lang_CharSequence() {
- final String fixture = "0000";
- StringBuffer sb = new StringBuffer(fixture);
- assertSame(sb, sb.insert(0, (CharSequence) "ab"));
- assertEquals("ab0000", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuffer(fixture);
- assertSame(sb, sb.insert(2, (CharSequence) "ab"));
- assertEquals("00ab00", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuffer(fixture);
- assertSame(sb, sb.insert(4, (CharSequence) "ab"));
- assertEquals("0000ab", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuffer(fixture);
- assertSame(sb, sb.insert(4, (CharSequence) null));
- assertEquals("0000null", sb.toString());
- assertEquals(8, sb.length());
-
- try {
- sb = new StringBuffer(fixture);
- sb.insert(-1, (CharSequence) "ab");
- fail("no IOOBE, negative index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuffer(fixture);
- sb.insert(5, (CharSequence) "ab");
- fail("no IOOBE, index too large index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer.insert(int, CharSequence, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, java.lang.CharSequence.class, int.class, int.class}
- )
- @SuppressWarnings("cast")
- public void test_insertILjava_lang_CharSequenceII() {
- final String fixture = "0000";
- StringBuffer sb = new StringBuffer(fixture);
- assertSame(sb, sb.insert(0, (CharSequence) "ab", 0, 2));
- assertEquals("ab0000", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuffer(fixture);
- assertSame(sb, sb.insert(0, (CharSequence) "ab", 0, 1));
- assertEquals("a0000", sb.toString());
- assertEquals(5, sb.length());
-
- sb = new StringBuffer(fixture);
- assertSame(sb, sb.insert(2, (CharSequence) "ab", 0, 2));
- assertEquals("00ab00", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuffer(fixture);
- assertSame(sb, sb.insert(2, (CharSequence) "ab", 0, 1));
- assertEquals("00a00", sb.toString());
- assertEquals(5, sb.length());
-
- sb = new StringBuffer(fixture);
- assertSame(sb, sb.insert(4, (CharSequence) "ab", 0, 2));
- assertEquals("0000ab", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuffer(fixture);
- assertSame(sb, sb.insert(4, (CharSequence) "ab", 0, 1));
- assertEquals("0000a", sb.toString());
- assertEquals(5, sb.length());
-
- sb = new StringBuffer(fixture);
- assertSame(sb, sb.insert(4, (CharSequence) null, 0, 2));
- assertEquals("0000nu", sb.toString());
- assertEquals(6, sb.length());
-
- try {
- sb = new StringBuffer(fixture);
- sb.insert(-1, (CharSequence) "ab", 0, 2);
- fail("no IOOBE, negative index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuffer(fixture);
- sb.insert(5, (CharSequence) "ab", 0, 2);
- fail("no IOOBE, index too large index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuffer(fixture);
- sb.insert(5, (CharSequence) "ab", -1, 2);
- fail("no IOOBE, negative offset");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuffer(fixture);
- sb.insert(5, new char[] { 'a', 'b' }, 0, -1);
- fail("no IOOBE, negative length");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuffer(fixture);
- sb.insert(5, new char[] { 'a', 'b' }, 0, 3);
- fail("no IOOBE, too long");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer.insert(int, char)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ArrayIndexOutOfBoundsException.",
- method = "insert",
- args = {int.class, char.class}
- )
- public void test_insertIC() {
- StringBuffer obj = new StringBuffer();
- try {
- obj.insert(-1, ' ');
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer.appendCodePoint(int)'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "appendCodePoint",
- args = {int.class}
- )
- public void test_appendCodePointI() {
- StringBuffer sb = new StringBuffer();
- sb.appendCodePoint(0x10000);
- assertEquals("\uD800\uDC00", sb.toString());
- sb.append("fixture");
- assertEquals("\uD800\uDC00fixture", sb.toString());
- sb.appendCodePoint(0x00010FFFF);
- assertEquals("\uD800\uDC00fixture\uDBFF\uDFFF", sb.toString());
- }
-
- /**
- * @tests java.lang.StringBuffer.codePointAt(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "codePointAt",
- args = {int.class}
- )
- public void test_codePointAtI() {
- StringBuffer sb = new StringBuffer("abc");
- assertEquals('a', sb.codePointAt(0));
- assertEquals('b', sb.codePointAt(1));
- assertEquals('c', sb.codePointAt(2));
-
- sb = new StringBuffer("\uD800\uDC00");
- assertEquals(0x10000, sb.codePointAt(0));
- assertEquals('\uDC00', sb.codePointAt(1));
-
- try {
- sb.codePointAt(-1);
- fail("No IOOBE on negative index.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.codePointAt(sb.length());
- fail("No IOOBE on index equal to length.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.codePointAt(sb.length() + 1);
- fail("No IOOBE on index greater than length.");
- } catch (IndexOutOfBoundsException e) {
-
- }
- }
-
- /**
- * @tests java.lang.StringBuffer.codePointBefore(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "codePointBefore",
- args = {int.class}
- )
- public void test_codePointBeforeI() {
- StringBuffer sb = new StringBuffer("abc");
- assertEquals('a', sb.codePointBefore(1));
- assertEquals('b', sb.codePointBefore(2));
- assertEquals('c', sb.codePointBefore(3));
-
- sb = new StringBuffer("\uD800\uDC00");
- assertEquals(0x10000, sb.codePointBefore(2));
- assertEquals('\uD800', sb.codePointBefore(1));
-
- try {
- sb.codePointBefore(0);
- fail("No IOOBE on zero index.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.codePointBefore(-1);
- fail("No IOOBE on negative index.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.codePointBefore(sb.length() + 1);
- fail("No IOOBE on index greater than length.");
- } catch (IndexOutOfBoundsException e) {
-
- }
- }
-
- /**
- * @tests java.lang.StringBuffer.codePointCount(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "codePointCount",
- args = {int.class, int.class}
- )
- public void test_codePointCountII() {
- assertEquals(1, new StringBuffer("\uD800\uDC00").codePointCount(0, 2));
- assertEquals(1, new StringBuffer("\uD800\uDC01").codePointCount(0, 2));
- assertEquals(1, new StringBuffer("\uD801\uDC01").codePointCount(0, 2));
- assertEquals(1, new StringBuffer("\uDBFF\uDFFF").codePointCount(0, 2));
-
- assertEquals(3, new StringBuffer("a\uD800\uDC00b").codePointCount(0, 4));
- assertEquals(4, new StringBuffer("a\uD800\uDC00b\uD800").codePointCount(0, 5));
-
- StringBuffer sb = new StringBuffer("abc");
- try {
- sb.codePointCount(-1, 2);
- fail("No IOOBE for negative begin index.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.codePointCount(0, 4);
- fail("No IOOBE for end index that's too large.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.codePointCount(3, 2);
- fail("No IOOBE for begin index larger than end index.");
- } catch (IndexOutOfBoundsException e) {
-
- }
- }
-
- /**
- * @tests java.lang.StringBuffer.getChars(int, int, char[], int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IndexOutOfBoundsException, NullPointerException.",
- method = "getChars",
- args = {int.class, int.class, char[].class, int.class}
- )
- public void test_getCharsII$CI() {
- StringBuffer obj = new StringBuffer();
- try {
- obj.getChars(0, 0, new char[0], -1);
-// TODO(Fixed) According to spec this should be IndexOutOfBoundsException.
-// fail("ArrayIndexOutOfBoundsException expected");
-// } catch (ArrayIndexOutOfBoundsException e) {
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- obj.getChars(0, 0, null, -1);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.StringBuffer.offsetByCodePoints(int, int)'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "offsetByCodePoints",
- args = {int.class, int.class}
- )
- public void test_offsetByCodePointsII() {
- int result = new StringBuffer("a\uD800\uDC00b").offsetByCodePoints(0, 2);
- assertEquals(3, result);
-
- result = new StringBuffer("abcd").offsetByCodePoints(3, -1);
- assertEquals(2, result);
-
- result = new StringBuffer("a\uD800\uDC00b").offsetByCodePoints(0, 3);
- assertEquals(4, result);
-
- result = new StringBuffer("a\uD800\uDC00b").offsetByCodePoints(3, -1);
- assertEquals(1, result);
-
- result = new StringBuffer("a\uD800\uDC00b").offsetByCodePoints(3, 0);
- assertEquals(3, result);
-
- result = new StringBuffer("\uD800\uDC00bc").offsetByCodePoints(3, 0);
- assertEquals(3, result);
-
- result = new StringBuffer("a\uDC00bc").offsetByCodePoints(3, -1);
- assertEquals(2, result);
-
- result = new StringBuffer("a\uD800bc").offsetByCodePoints(3, -1);
- assertEquals(2, result);
-
- StringBuffer sb = new StringBuffer("abc");
- try {
- sb.offsetByCodePoints(-1, 1);
- fail("No IOOBE for negative index.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.offsetByCodePoints(0, 4);
- fail("No IOOBE for offset that's too large.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.offsetByCodePoints(3, -4);
- fail("No IOOBE for offset that's too small.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.offsetByCodePoints(3, 1);
- fail("No IOOBE for index that's too large.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.offsetByCodePoints(4, -1);
- fail("No IOOBE for index that's too large.");
- } catch (IndexOutOfBoundsException e) {
-
- }
- }
-
- /**
- * @tests {@link java.lang.StringBuffer#indexOf(String, int)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "indexOf",
- args = {java.lang.String.class, int.class}
- )
- @SuppressWarnings("nls")
- public void test_IndexOfStringInt() {
- final String fixture = "0123456789";
- StringBuffer sb = new StringBuffer(fixture);
- assertEquals(0, sb.indexOf("0"));
- assertEquals(0, sb.indexOf("012"));
- assertEquals(-1, sb.indexOf("02"));
- assertEquals(8, sb.indexOf("89"));
-
- assertEquals(0, sb.indexOf("0"), 0);
- assertEquals(0, sb.indexOf("012"), 0);
- assertEquals(-1, sb.indexOf("02"), 0);
- assertEquals(8, sb.indexOf("89"), 0);
-
- assertEquals(-1, sb.indexOf("0"), 5);
- assertEquals(-1, sb.indexOf("012"), 5);
- assertEquals(-1, sb.indexOf("02"), 0);
- assertEquals(8, sb.indexOf("89"), 5);
-
- try {
- sb.indexOf(null, 0);
- fail("Should throw a NullPointerExceptionE");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * @tests {@link java.lang.StringBuffer#lastIndexOf(String, int)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lastIndexOf",
- args = {java.lang.String.class, int.class}
- )
- @SuppressWarnings("nls")
- public void test_lastIndexOfLjava_lang_StringI() {
- final String fixture = "0123456789";
- StringBuffer sb = new StringBuffer(fixture);
- assertEquals(0, sb.lastIndexOf("0"));
- assertEquals(0, sb.lastIndexOf("012"));
- assertEquals(-1, sb.lastIndexOf("02"));
- assertEquals(8, sb.lastIndexOf("89"));
-
- assertEquals(0, sb.lastIndexOf("0"), 0);
- assertEquals(0, sb.lastIndexOf("012"), 0);
- assertEquals(-1, sb.lastIndexOf("02"), 0);
- assertEquals(8, sb.lastIndexOf("89"), 0);
-
- assertEquals(-1, sb.lastIndexOf("0"), 5);
- assertEquals(-1, sb.lastIndexOf("012"), 5);
- assertEquals(-1, sb.lastIndexOf("02"), 0);
- assertEquals(8, sb.lastIndexOf("89"), 5);
-
- try {
- sb.lastIndexOf(null, 0);
- fail("Should throw a NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- // comparator for StringBuffer objects
- private static final SerializableAssert STRING_BUFFER_COMPARATOR = new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
-
- StringBuffer init = (StringBuffer) initial;
- StringBuffer desr = (StringBuffer) deserialized;
-
- // serializable fields are: 'count', 'shared', 'value'
- // serialization of 'shared' is not verified
- // 'count' + 'value' should result in required string
- assertEquals("toString", init.toString(), desr.toString());
- }
- };
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new StringBuffer("0123456789"),
- STRING_BUFFER_COMPARATOR);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new StringBuffer("0123456789"),
- STRING_BUFFER_COMPARATOR);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBuilderTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBuilderTest.java
deleted file mode 100644
index 0243fdb..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBuilderTest.java
+++ /dev/null
@@ -1,2191 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.Serializable;
-import java.util.Arrays;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(StringBuilder.class)
-public class StringBuilderTest extends TestCase {
-
- /**
- * @tests java.lang.StringBuilder.StringBuilder()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StringBuilder",
- args = {}
- )
- public void test_Constructor() {
- StringBuilder sb = new StringBuilder();
- assertNotNull(sb);
- assertEquals(16, sb.capacity());
- }
-
- /**
- * @tests java.lang.StringBuilder.StringBuilder(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StringBuilder",
- args = {int.class}
- )
- public void test_ConstructorI() {
- StringBuilder sb = new StringBuilder(24);
- assertNotNull(sb);
- assertEquals(24, sb.capacity());
-
- try {
- new StringBuilder(-1);
- fail("no exception");
- } catch (NegativeArraySizeException e) {
- // Expected
- }
-
- assertNotNull(new StringBuilder(0));
- }
-
- /**
- * @tests java.lang.StringBuilder.StringBuilder(CharSequence)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StringBuilder",
- args = {java.lang.CharSequence.class}
- )
- @SuppressWarnings("cast")
- public void test_ConstructorLjava_lang_CharSequence() {
- StringBuilder sb = new StringBuilder((CharSequence) "fixture");
- assertEquals("fixture", sb.toString());
- assertEquals("fixture".length() + 16, sb.capacity());
-
- sb = new StringBuilder((CharSequence) new StringBuffer("fixture"));
- assertEquals("fixture", sb.toString());
- assertEquals("fixture".length() + 16, sb.capacity());
-
- try {
- new StringBuilder((CharSequence) null);
- fail("no NPE");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.StringBuilder(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StringBuilder",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- StringBuilder sb = new StringBuilder("fixture");
- assertEquals("fixture", sb.toString());
- assertEquals("fixture".length() + 16, sb.capacity());
-
- try {
- new StringBuilder((String) null);
- fail("no NPE");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.append(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {boolean.class}
- )
- public void test_appendZ() {
- StringBuilder sb = new StringBuilder();
- assertSame(sb, sb.append(true));
- assertEquals("true", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(false));
- assertEquals("false", sb.toString());
- }
-
- /**
- * @tests java.lang.StringBuilder.append(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {char.class}
- )
- public void test_appendC() {
- StringBuilder sb = new StringBuilder();
- assertSame(sb, sb.append('a'));
- assertEquals("a", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append('b'));
- assertEquals("b", sb.toString());
- }
-
- /**
- * @tests java.lang.StringBuilder.append(char[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {char[].class}
- )
- public void test_append$C() {
- StringBuilder sb = new StringBuilder();
- assertSame(sb, sb.append(new char[] { 'a', 'b' }));
- assertEquals("ab", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(new char[] { 'c', 'd' }));
- assertEquals("cd", sb.toString());
- try {
- sb.append((char[]) null);
- fail("no NPE");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.append(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {char[].class, int.class, int.class}
- )
- public void test_append$CII() {
- StringBuilder sb = new StringBuilder();
- assertSame(sb, sb.append(new char[] { 'a', 'b' }, 0, 2));
- assertEquals("ab", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(new char[] { 'c', 'd' }, 0, 2));
- assertEquals("cd", sb.toString());
-
- sb.setLength(0);
- assertSame(sb, sb.append(new char[] { 'a', 'b', 'c', 'd' }, 0, 2));
- assertEquals("ab", sb.toString());
-
- sb.setLength(0);
- assertSame(sb, sb.append(new char[] { 'a', 'b', 'c', 'd' }, 2, 2));
- assertEquals("cd", sb.toString());
-
- sb.setLength(0);
- assertSame(sb, sb.append(new char[] { 'a', 'b', 'c', 'd' }, 2, 0));
- assertEquals("", sb.toString());
-
- try {
- sb.append((char[]) null, 0, 2);
- fail("no NPE");
- } catch (NullPointerException e) {
- // Expected
- }
-
- try {
- sb.append(new char[] { 'a', 'b', 'c', 'd' }, -1, 2);
- fail("no IOOBE, negative offset");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb.append(new char[] { 'a', 'b', 'c', 'd' }, 0, -1);
- fail("no IOOBE, negative length");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb.append(new char[] { 'a', 'b', 'c', 'd' }, 2, 3);
- fail("no IOOBE, offset and length overflow");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.append(CharSequence)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {java.lang.CharSequence.class}
- )
- public void test_appendLjava_lang_CharSequence() {
- StringBuilder sb = new StringBuilder();
- assertSame(sb, sb.append((CharSequence) "ab"));
- assertEquals("ab", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append((CharSequence) "cd"));
- assertEquals("cd", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append((CharSequence) null));
- assertEquals("null", sb.toString());
- }
-
- /**
- * @tests java.lang.StringBuilder.append(CharSequence, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {java.lang.CharSequence.class, int.class, int.class}
- )
- @SuppressWarnings("cast")
- public void test_appendLjava_lang_CharSequenceII() {
- StringBuilder sb = new StringBuilder();
- assertSame(sb, sb.append((CharSequence) "ab", 0, 2));
- assertEquals("ab", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append((CharSequence) "cd", 0, 2));
- assertEquals("cd", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append((CharSequence) "abcd", 0, 2));
- assertEquals("ab", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append((CharSequence) "abcd", 2, 4));
- assertEquals("cd", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append((CharSequence) null, 0, 2));
- assertEquals("nu", sb.toString());
-
- try {
- sb.append((CharSequence) "abcd", -1, 2);
- fail("IndexOutOfBoundsException was thrown.");
- } catch(IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- sb.append((CharSequence) "abcd", 0, 5);
- fail("IndexOutOfBoundsException was thrown.");
- } catch(IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- sb.append((CharSequence) "abcd", 2, 1);
- fail("IndexOutOfBoundsException was thrown.");
- } catch(IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.append(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {double.class}
- )
- public void test_appendD() {
- StringBuilder sb = new StringBuilder();
- assertSame(sb, sb.append(1D));
- assertEquals(String.valueOf(1D), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(0D));
- assertEquals(String.valueOf(0D), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(-1D));
- assertEquals(String.valueOf(-1D), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(Double.NaN));
- assertEquals(String.valueOf(Double.NaN), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(Double.NEGATIVE_INFINITY));
- assertEquals(String.valueOf(Double.NEGATIVE_INFINITY), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(Double.POSITIVE_INFINITY));
- assertEquals(String.valueOf(Double.POSITIVE_INFINITY), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(Double.MIN_VALUE));
- assertEquals(String.valueOf(Double.MIN_VALUE), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(Double.MAX_VALUE));
- assertEquals(String.valueOf(Double.MAX_VALUE), sb.toString());
- }
-
- /**
- * @tests java.lang.StringBuilder.append(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {float.class}
- )
- public void test_appendF() {
- StringBuilder sb = new StringBuilder();
- assertSame(sb, sb.append(1F));
- assertEquals(String.valueOf(1F), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(0F));
- assertEquals(String.valueOf(0F), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(-1F));
- assertEquals(String.valueOf(-1F), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(Float.NaN));
- assertEquals(String.valueOf(Float.NaN), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(Float.NEGATIVE_INFINITY));
- assertEquals(String.valueOf(Float.NEGATIVE_INFINITY), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(Float.POSITIVE_INFINITY));
- assertEquals(String.valueOf(Float.POSITIVE_INFINITY), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(Float.MIN_VALUE));
- assertEquals(String.valueOf(Float.MIN_VALUE), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(Float.MAX_VALUE));
- assertEquals(String.valueOf(Float.MAX_VALUE), sb.toString());
- }
-
- /**
- * @tests java.lang.StringBuilder.append(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {int.class}
- )
- public void test_appendI() {
- StringBuilder sb = new StringBuilder();
- assertSame(sb, sb.append(1));
- assertEquals(String.valueOf(1), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(0));
- assertEquals(String.valueOf(0), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(-1));
- assertEquals(String.valueOf(-1), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(Integer.MIN_VALUE));
- assertEquals(String.valueOf(Integer.MIN_VALUE), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(Integer.MAX_VALUE));
- assertEquals(String.valueOf(Integer.MAX_VALUE), sb.toString());
- }
-
- /**
- * @tests java.lang.StringBuilder.append(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {long.class}
- )
- public void test_appendL() {
- StringBuilder sb = new StringBuilder();
- assertSame(sb, sb.append(1L));
- assertEquals(String.valueOf(1L), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(0L));
- assertEquals(String.valueOf(0L), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(-1L));
- assertEquals(String.valueOf(-1L), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(Integer.MIN_VALUE));
- assertEquals(String.valueOf(Integer.MIN_VALUE), sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(Integer.MAX_VALUE));
- assertEquals(String.valueOf(Integer.MAX_VALUE), sb.toString());
- }
-
- /**
- * @tests java.lang.StringBuilder.append(Object)'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {java.lang.Object.class}
- )
- public void test_appendLjava_lang_Object() {
- StringBuilder sb = new StringBuilder();
- assertSame(sb, sb.append(Fixture.INSTANCE));
- assertEquals(Fixture.INSTANCE.toString(), sb.toString());
-
- sb.setLength(0);
- assertSame(sb, sb.append((Object) null));
- assertEquals("null", sb.toString());
- }
-
- /**
- * @tests java.lang.StringBuilder.append(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {java.lang.String.class}
- )
- public void test_appendLjava_lang_String() {
- StringBuilder sb = new StringBuilder();
- assertSame(sb, sb.append("ab"));
- assertEquals("ab", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append("cd"));
- assertEquals("cd", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append((String) null));
- assertEquals("null", sb.toString());
- }
-
- /**
- * @tests java.lang.StringBuilder.append(StringBuffer)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {java.lang.StringBuffer.class}
- )
- public void test_appendLjava_lang_StringBuffer() {
- StringBuilder sb = new StringBuilder();
- assertSame(sb, sb.append(new StringBuffer("ab")));
- assertEquals("ab", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append(new StringBuffer("cd")));
- assertEquals("cd", sb.toString());
- sb.setLength(0);
- assertSame(sb, sb.append((StringBuffer) null));
- assertEquals("null", sb.toString());
- }
-
- /**
- * @tests java.lang.StringBuilder.appendCodePoint(int)'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "appendCodePoint",
- args = {int.class}
- )
- public void test_appendCodePointI() {
- StringBuilder sb = new StringBuilder();
- sb.appendCodePoint(0x10000);
- assertEquals("\uD800\uDC00", sb.toString());
- sb.append("fixture");
- assertEquals("\uD800\uDC00fixture", sb.toString());
- sb.appendCodePoint(0x00010FFFF);
- assertEquals("\uD800\uDC00fixture\uDBFF\uDFFF", sb.toString());
- }
-
- /**
- * @tests java.lang.StringBuilder.capacity()'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "capacity",
- args = {}
- )
- public void test_capacity() {
- StringBuilder sb = new StringBuilder();
- assertEquals(16, sb.capacity());
- sb.append("0123456789ABCDEF0123456789ABCDEF");
- assertTrue(sb.capacity() > 16);
- }
-
- /**
- * @tests java.lang.StringBuilder.charAt(int)'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "charAt",
- args = {int.class}
- )
- public void test_charAtI() {
- final String fixture = "0123456789";
- StringBuilder sb = new StringBuilder(fixture);
- for (int i = 0; i < fixture.length(); i++) {
- assertEquals((char) ('0' + i), sb.charAt(i));
- }
-
- try {
- sb.charAt(-1);
- fail("no IOOBE, negative index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb.charAt(fixture.length());
- fail("no IOOBE, equal to length");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- sb.charAt(fixture.length() + 1);
- fail("no IOOBE, greater than length");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.codePointAt(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "codePointAt",
- args = {int.class}
- )
- public void test_codePointAtI() {
- StringBuilder sb = new StringBuilder("abc");
- assertEquals('a', sb.codePointAt(0));
- assertEquals('b', sb.codePointAt(1));
- assertEquals('c', sb.codePointAt(2));
-
- sb = new StringBuilder("\uD800\uDC00");
- assertEquals(0x10000, sb.codePointAt(0));
- assertEquals('\uDC00', sb.codePointAt(1));
-
- sb = new StringBuilder();
- sb.append("abc");
- try {
- sb.codePointAt(-1);
- fail("No IOOBE on negative index.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.codePointAt(sb.length());
- fail("No IOOBE on index equal to length.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.codePointAt(sb.length() + 1);
- fail("No IOOBE on index greater than length.");
- } catch (IndexOutOfBoundsException e) {
-
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.codePointBefore(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "codePointBefore",
- args = {int.class}
- )
- public void test_codePointBeforeI() {
- StringBuilder sb = new StringBuilder("abc");
- assertEquals('a', sb.codePointBefore(1));
- assertEquals('b', sb.codePointBefore(2));
- assertEquals('c', sb.codePointBefore(3));
-
- sb = new StringBuilder("\uD800\uDC00");
- assertEquals(0x10000, sb.codePointBefore(2));
- assertEquals('\uD800', sb.codePointBefore(1));
-
- sb = new StringBuilder();
- sb.append("abc");
-
- try {
- sb.codePointBefore(0);
- fail("No IOOBE on zero index.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.codePointBefore(-1);
- fail("No IOOBE on negative index.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.codePointBefore(sb.length() + 1);
- fail("No IOOBE on index greater than length.");
- } catch (IndexOutOfBoundsException e) {
-
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.codePointCount(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "codePointCount",
- args = {int.class, int.class}
- )
- public void test_codePointCountII() {
- assertEquals(1, new StringBuilder("\uD800\uDC00").codePointCount(0, 2));
- assertEquals(1, new StringBuilder("\uD800\uDC01").codePointCount(0, 2));
- assertEquals(1, new StringBuilder("\uD801\uDC01").codePointCount(0, 2));
- assertEquals(1, new StringBuilder("\uDBFF\uDFFF").codePointCount(0, 2));
-
- assertEquals(3, new StringBuilder("a\uD800\uDC00b").codePointCount(0, 4));
- assertEquals(4, new StringBuilder("a\uD800\uDC00b\uD800").codePointCount(0, 5));
-
- StringBuilder sb = new StringBuilder();
- sb.append("abc");
- try {
- sb.codePointCount(-1, 2);
- fail("No IOOBE for negative begin index.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.codePointCount(0, 4);
- fail("No IOOBE for end index that's too large.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.codePointCount(3, 2);
- fail("No IOOBE for begin index larger than end index.");
- } catch (IndexOutOfBoundsException e) {
-
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.delete(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "delete",
- args = {int.class, int.class}
- )
- public void test_deleteII() {
- final String fixture = "0123456789";
- StringBuilder sb = new StringBuilder(fixture);
- assertSame(sb, sb.delete(0, 0));
- assertEquals(fixture, sb.toString());
- assertSame(sb, sb.delete(5, 5));
- assertEquals(fixture, sb.toString());
- assertSame(sb, sb.delete(0, 1));
- assertEquals("123456789", sb.toString());
- assertEquals(9, sb.length());
- assertSame(sb, sb.delete(0, sb.length()));
- assertEquals("", sb.toString());
- assertEquals(0, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.delete(0, 11));
- assertEquals("", sb.toString());
- assertEquals(0, sb.length());
-
- try {
- new StringBuilder(fixture).delete(-1, 2);
- fail("no SIOOBE, negative start");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- new StringBuilder(fixture).delete(11, 12);
- fail("no SIOOBE, start too far");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- new StringBuilder(fixture).delete(13, 12);
- fail("no SIOOBE, start larger than end");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.deleteCharAt(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "deleteCharAt",
- args = {int.class}
- )
- public void test_deleteCharAtI() {
- final String fixture = "0123456789";
- StringBuilder sb = new StringBuilder(fixture);
- assertSame(sb, sb.deleteCharAt(0));
- assertEquals("123456789", sb.toString());
- assertEquals(9, sb.length());
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.deleteCharAt(5));
- assertEquals("012346789", sb.toString());
- assertEquals(9, sb.length());
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.deleteCharAt(9));
- assertEquals("012345678", sb.toString());
- assertEquals(9, sb.length());
-
- try {
- new StringBuilder(fixture).deleteCharAt(-1);
- fail("no SIOOBE, negative index");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- new StringBuilder(fixture).deleteCharAt(fixture.length());
- fail("no SIOOBE, index equals length");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- new StringBuilder(fixture).deleteCharAt(fixture.length() + 1);
- fail("no SIOOBE, index exceeds length");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.ensureCapacity(int)'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ensureCapacity",
- args = {int.class}
- )
- public void test_ensureCapacityI() {
- StringBuilder sb = new StringBuilder(5);
- assertEquals(5, sb.capacity());
- sb.ensureCapacity(10);
- assertEquals(12, sb.capacity());
- sb.ensureCapacity(26);
- assertEquals(26, sb.capacity());
- sb.ensureCapacity(55);
- assertEquals(55, sb.capacity());
- }
-
- /**
- * @tests java.lang.StringBuilder.getChars(int, int, char[], int)'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getChars",
- args = {int.class, int.class, char[].class, int.class}
- )
- public void test_getCharsII$CI() {
- final String fixture = "0123456789";
- StringBuilder sb = new StringBuilder(fixture);
- char[] dst = new char[10];
- sb.getChars(0, 10, dst, 0);
- assertTrue(Arrays.equals(fixture.toCharArray(), dst));
-
- Arrays.fill(dst, '\0');
- sb.getChars(0, 5, dst, 0);
- char[] fixtureChars = new char[10];
- fixture.getChars(0, 5, fixtureChars, 0);
- assertTrue(Arrays.equals(fixtureChars, dst));
-
- Arrays.fill(dst, '\0');
- Arrays.fill(fixtureChars, '\0');
- sb.getChars(0, 5, dst, 5);
- fixture.getChars(0, 5, fixtureChars, 5);
- assertTrue(Arrays.equals(fixtureChars, dst));
-
- Arrays.fill(dst, '\0');
- Arrays.fill(fixtureChars, '\0');
- sb.getChars(5, 10, dst, 1);
- fixture.getChars(5, 10, fixtureChars, 1);
- assertTrue(Arrays.equals(fixtureChars, dst));
-
- try {
- sb.getChars(0, 10, null, 0);
- fail("no NPE");
- } catch (NullPointerException e) {
- // Expected
- }
-
- try {
- sb.getChars(-1, 10, dst, 0);
- fail("no IOOBE, srcBegin negative");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb.getChars(0, 10, dst, -1);
- fail("no IOOBE, dstBegin negative");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb.getChars(5, 4, dst, 0);
- fail("no IOOBE, srcBegin > srcEnd");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb.getChars(0, 11, dst, 0);
- fail("no IOOBE, srcEnd > length");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb.getChars(0, 10, dst, 5);
- fail("no IOOBE, dstBegin and src size too large for what's left in dst");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.indexOf(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "indexOf",
- args = {java.lang.String.class}
- )
- public void test_indexOfLjava_lang_String() {
- final String fixture = "0123456789";
- StringBuilder sb = new StringBuilder(fixture);
- assertEquals(0, sb.indexOf("0"));
- assertEquals(0, sb.indexOf("012"));
- assertEquals(-1, sb.indexOf("02"));
- assertEquals(8, sb.indexOf("89"));
-
- try {
- sb.indexOf(null);
- fail("no NPE");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.indexOf(String, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "indexOf",
- args = {java.lang.String.class, int.class}
- )
- public void test_IndexOfStringInt() {
- final String fixture = "0123456789";
- StringBuilder sb = new StringBuilder(fixture);
- assertEquals(0, sb.indexOf("0"));
- assertEquals(0, sb.indexOf("012"));
- assertEquals(-1, sb.indexOf("02"));
- assertEquals(8, sb.indexOf("89"));
-
- assertEquals(0, sb.indexOf("0"), 0);
- assertEquals(0, sb.indexOf("012"), 0);
- assertEquals(-1, sb.indexOf("02"), 0);
- assertEquals(8, sb.indexOf("89"), 0);
-
- assertEquals(-1, sb.indexOf("0"), 5);
- assertEquals(-1, sb.indexOf("012"), 5);
- assertEquals(-1, sb.indexOf("02"), 0);
- assertEquals(8, sb.indexOf("89"), 5);
-
- try {
- sb.indexOf(null, 0);
- fail("no NPE");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.insert(int, boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, boolean.class}
- )
- public void test_insertIZ() {
- final String fixture = "0000";
- StringBuilder sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, true));
- assertEquals("true0000", sb.toString());
- assertEquals(8, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, false));
- assertEquals("false0000", sb.toString());
- assertEquals(9, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(2, false));
- assertEquals("00false00", sb.toString());
- assertEquals(9, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(4, false));
- assertEquals("0000false", sb.toString());
- assertEquals(9, sb.length());
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(-1, false);
- fail("no SIOOBE, negative index");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(5, false);
- fail("no SIOOBE, index too large index");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.insert(int, char)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IndexOutOfBoundsException is not verified.",
- method = "insert",
- args = {int.class, char.class}
- )
- public void test_insertIC() {
- final String fixture = "0000";
- StringBuilder sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, 'a'));
- assertEquals("a0000", sb.toString());
- assertEquals(5, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, 'b'));
- assertEquals("b0000", sb.toString());
- assertEquals(5, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(2, 'b'));
- assertEquals("00b00", sb.toString());
- assertEquals(5, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(4, 'b'));
- assertEquals("0000b", sb.toString());
- assertEquals(5, sb.length());
-
- // FIXME this fails on Sun JRE 5.0_5
-// try {
-// sb = new StringBuilder(fixture);
-// sb.insert(-1, 'a');
-// fail("no SIOOBE, negative index");
-// } catch (StringIndexOutOfBoundsException e) {
-// // Expected
-// }
-
- /*
- * FIXME This fails on Sun JRE 5.0_5, but that seems like a bug, since
- * the 'insert(int, char[]) behaves this way.
- */
-// try {
-// sb = new StringBuilder(fixture);
-// sb.insert(5, 'a');
-// fail("no SIOOBE, index too large index");
-// } catch (StringIndexOutOfBoundsException e) {
-// // Expected
-// }
- }
-
- /**
- * @tests java.lang.StringBuilder.insert(int, char)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ArrayIndexOutOfBoundsException.",
- method = "insert",
- args = {int.class, char.class}
- )
- public void test_insertIC_2() {
- StringBuilder obj = new StringBuilder();
- try {
- obj.insert(-1, '?');
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- // expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.insert(int, char[])'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, char[].class}
- )
- public void test_insertI$C() {
- final String fixture = "0000";
- StringBuilder sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, new char[] { 'a', 'b' }));
- assertEquals("ab0000", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(2, new char[] { 'a', 'b' }));
- assertEquals("00ab00", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(4, new char[] { 'a', 'b' }));
- assertEquals("0000ab", sb.toString());
- assertEquals(6, sb.length());
-
- /*
- * TODO This NPE is the behavior on Sun's JRE 5.0_5, but it's
- * undocumented. The assumption is that this method behaves like
- * String.valueOf(char[]), which does throw a NPE too, but that is also
- * undocumented.
- */
-
- try {
- sb.insert(0, (char[]) null);
- fail("no NPE");
- } catch (NullPointerException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(-1, new char[] { 'a', 'b' });
- fail("no SIOOBE, negative index");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(5, new char[] { 'a', 'b' });
- fail("no SIOOBE, index too large index");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.insert(int, char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, char[].class, int.class, int.class}
- )
- public void test_insertI$CII() {
- final String fixture = "0000";
- StringBuilder sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, new char[] { 'a', 'b' }, 0, 2));
- assertEquals("ab0000", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, new char[] { 'a', 'b' }, 0, 1));
- assertEquals("a0000", sb.toString());
- assertEquals(5, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(2, new char[] { 'a', 'b' }, 0, 2));
- assertEquals("00ab00", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(2, new char[] { 'a', 'b' }, 0, 1));
- assertEquals("00a00", sb.toString());
- assertEquals(5, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(4, new char[] { 'a', 'b' }, 0, 2));
- assertEquals("0000ab", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(4, new char[] { 'a', 'b' }, 0, 1));
- assertEquals("0000a", sb.toString());
- assertEquals(5, sb.length());
-
- /*
- * TODO This NPE is the behavior on Sun's JRE 5.0_5, but it's
- * undocumented. The assumption is that this method behaves like
- * String.valueOf(char[]), which does throw a NPE too, but that is also
- * undocumented.
- */
-
- try {
- sb.insert(0, (char[]) null, 0, 2);
- fail("no NPE");
- } catch (NullPointerException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(-1, new char[] { 'a', 'b' }, 0, 2);
- fail("no SIOOBE, negative index");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(5, new char[] { 'a', 'b' }, 0, 2);
- fail("no SIOOBE, index too large index");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(5, new char[] { 'a', 'b' }, -1, 2);
- fail("no SIOOBE, negative offset");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(5, new char[] { 'a', 'b' }, 0, -1);
- fail("no SIOOBE, negative length");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(5, new char[] { 'a', 'b' }, 0, 3);
- fail("no SIOOBE, too long");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.insert(int, CharSequence)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, java.lang.CharSequence.class}
- )
- public void test_insertILjava_lang_CharSequence() {
- final String fixture = "0000";
- StringBuilder sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, (CharSequence) "ab"));
- assertEquals("ab0000", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(2, (CharSequence) "ab"));
- assertEquals("00ab00", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(4, (CharSequence) "ab"));
- assertEquals("0000ab", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(4, (CharSequence) null));
- assertEquals("0000null", sb.toString());
- assertEquals(8, sb.length());
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(-1, (CharSequence) "ab");
- fail("no IOOBE, negative index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(5, (CharSequence) "ab");
- fail("no IOOBE, index too large index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.insert(int, CharSequence, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, java.lang.CharSequence.class, int.class, int.class}
- )
- @SuppressWarnings("cast")
- public void test_insertILjava_lang_CharSequenceII() {
- final String fixture = "0000";
- StringBuilder sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, (CharSequence) "ab", 0, 2));
- assertEquals("ab0000", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, (CharSequence) "ab", 0, 1));
- assertEquals("a0000", sb.toString());
- assertEquals(5, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(2, (CharSequence) "ab", 0, 2));
- assertEquals("00ab00", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(2, (CharSequence) "ab", 0, 1));
- assertEquals("00a00", sb.toString());
- assertEquals(5, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(4, (CharSequence) "ab", 0, 2));
- assertEquals("0000ab", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(4, (CharSequence) "ab", 0, 1));
- assertEquals("0000a", sb.toString());
- assertEquals(5, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(4, (CharSequence) null, 0, 2));
- assertEquals("0000nu", sb.toString());
- assertEquals(6, sb.length());
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(-1, (CharSequence) "ab", 0, 2);
- fail("no IOOBE, negative index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(5, (CharSequence) "ab", 0, 2);
- fail("no IOOBE, index too large index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(5, (CharSequence) "ab", -1, 2);
- fail("no IOOBE, negative offset");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(5, new char[] { 'a', 'b' }, 0, -1);
- fail("no IOOBE, negative length");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(5, new char[] { 'a', 'b' }, 0, 3);
- fail("no IOOBE, too long");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.insert(int, double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, double.class}
- )
- public void test_insertID() {
- final String fixture = "0000";
- StringBuilder sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, -1D));
- assertEquals("-1.00000", sb.toString());
- assertEquals(8, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, 0D));
- assertEquals("0.00000", sb.toString());
- assertEquals(7, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(2, 1D));
- assertEquals("001.000", sb.toString());
- assertEquals(7, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(4, 2D));
- assertEquals("00002.0", sb.toString());
- assertEquals(7, sb.length());
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(-1, 1D);
- fail("no IOOBE, negative index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(5, 1D);
- fail("no IOOBE, index too large index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.insert(int, float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, float.class}
- )
- public void test_insertIF() {
- final String fixture = "0000";
- StringBuilder sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, -1F));
- assertEquals("-1.00000", sb.toString());
- assertEquals(8, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, 0F));
- assertEquals("0.00000", sb.toString());
- assertEquals(7, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(2, 1F));
- assertEquals("001.000", sb.toString());
- assertEquals(7, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(4, 2F));
- assertEquals("00002.0", sb.toString());
- assertEquals(7, sb.length());
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(-1, 1F);
- fail("no IOOBE, negative index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(5, 1F);
- fail("no IOOBE, index too large index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.insert(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, int.class}
- )
- public void test_insertII() {
- final String fixture = "0000";
- StringBuilder sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, -1));
- assertEquals("-10000", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, 0));
- assertEquals("00000", sb.toString());
- assertEquals(5, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(2, 1));
- assertEquals("00100", sb.toString());
- assertEquals(5, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(4, 2));
- assertEquals("00002", sb.toString());
- assertEquals(5, sb.length());
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(-1, 1);
- fail("no IOOBE, negative index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(5, 1);
- fail("no IOOBE, index too large index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.insert(int, long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, long.class}
- )
- public void test_insertIJ() {
- final String fixture = "0000";
- StringBuilder sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, -1L));
- assertEquals("-10000", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, 0L));
- assertEquals("00000", sb.toString());
- assertEquals(5, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(2, 1L));
- assertEquals("00100", sb.toString());
- assertEquals(5, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(4, 2L));
- assertEquals("00002", sb.toString());
- assertEquals(5, sb.length());
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(-1, 1L);
- fail("no IOOBE, negative index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(5, 1L);
- fail("no IOOBE, index too large index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.insert(int, Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, java.lang.Object.class}
- )
- public void test_insertILjava_lang_Object() {
- final String fixture = "0000";
- StringBuilder sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, Fixture.INSTANCE));
- assertEquals("fixture0000", sb.toString());
- assertEquals(11, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(2, Fixture.INSTANCE));
- assertEquals("00fixture00", sb.toString());
- assertEquals(11, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(4, Fixture.INSTANCE));
- assertEquals("0000fixture", sb.toString());
- assertEquals(11, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(4, (Object) null));
- assertEquals("0000null", sb.toString());
- assertEquals(8, sb.length());
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(-1, Fixture.INSTANCE);
- fail("no IOOBE, negative index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(5, Fixture.INSTANCE);
- fail("no IOOBE, index too large index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.insert(int, String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insert",
- args = {int.class, java.lang.String.class}
- )
- public void test_insertILjava_lang_String() {
- final String fixture = "0000";
- StringBuilder sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(0, "fixture"));
- assertEquals("fixture0000", sb.toString());
- assertEquals(11, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(2, "fixture"));
- assertEquals("00fixture00", sb.toString());
- assertEquals(11, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(4, "fixture"));
- assertEquals("0000fixture", sb.toString());
- assertEquals(11, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.insert(4, (Object) null));
- assertEquals("0000null", sb.toString());
- assertEquals(8, sb.length());
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(-1, "fixture");
- fail("no IOOBE, negative index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.insert(5, "fixture");
- fail("no IOOBE, index too large index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.lastIndexOf(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lastIndexOf",
- args = {java.lang.String.class}
- )
- public void test_lastIndexOfLjava_lang_String() {
- final String fixture = "0123456789";
- StringBuilder sb = new StringBuilder(fixture);
- assertEquals(0, sb.lastIndexOf("0"));
- assertEquals(0, sb.lastIndexOf("012"));
- assertEquals(-1, sb.lastIndexOf("02"));
- assertEquals(8, sb.lastIndexOf("89"));
-
- try {
- sb.lastIndexOf(null);
- fail("no NPE");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.lastIndexOf(String, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lastIndexOf",
- args = {java.lang.String.class, int.class}
- )
- public void test_lastIndexOfLjava_lang_StringI() {
- final String fixture = "0123456789";
- StringBuilder sb = new StringBuilder(fixture);
- assertEquals(0, sb.lastIndexOf("0"));
- assertEquals(0, sb.lastIndexOf("012"));
- assertEquals(-1, sb.lastIndexOf("02"));
- assertEquals(8, sb.lastIndexOf("89"));
-
- assertEquals(0, sb.lastIndexOf("0"), 0);
- assertEquals(0, sb.lastIndexOf("012"), 0);
- assertEquals(-1, sb.lastIndexOf("02"), 0);
- assertEquals(8, sb.lastIndexOf("89"), 0);
-
- assertEquals(-1, sb.lastIndexOf("0"), 5);
- assertEquals(-1, sb.lastIndexOf("012"), 5);
- assertEquals(-1, sb.lastIndexOf("02"), 0);
- assertEquals(8, sb.lastIndexOf("89"), 5);
-
- try {
- sb.lastIndexOf(null, 0);
- fail("no NPE");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.length()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "length",
- args = {}
- )
- public void test_length() {
- StringBuilder sb = new StringBuilder();
- assertEquals(0, sb.length());
- sb.append("0000");
- assertEquals(4, sb.length());
- }
-
- /**
- * @tests java.lang.StringBuilder.offsetByCodePoints(int, int)'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "offsetByCodePoints",
- args = {int.class, int.class}
- )
- public void test_offsetByCodePointsII() {
- int result = new StringBuilder("a\uD800\uDC00b").offsetByCodePoints(0, 2);
- assertEquals(3, result);
-
- result = new StringBuilder("abcd").offsetByCodePoints(3, -1);
- assertEquals(2, result);
-
- result = new StringBuilder("a\uD800\uDC00b").offsetByCodePoints(0, 3);
- assertEquals(4, result);
-
- result = new StringBuilder("a\uD800\uDC00b").offsetByCodePoints(3, -1);
- assertEquals(1, result);
-
- result = new StringBuilder("a\uD800\uDC00b").offsetByCodePoints(3, 0);
- assertEquals(3, result);
-
- result = new StringBuilder("\uD800\uDC00bc").offsetByCodePoints(3, 0);
- assertEquals(3, result);
-
- result = new StringBuilder("a\uDC00bc").offsetByCodePoints(3, -1);
- assertEquals(2, result);
-
- result = new StringBuilder("a\uD800bc").offsetByCodePoints(3, -1);
- assertEquals(2, result);
-
- StringBuilder sb = new StringBuilder();
- sb.append("abc");
- try {
- sb.offsetByCodePoints(-1, 1);
- fail("No IOOBE for negative index.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.offsetByCodePoints(0, 4);
- fail("No IOOBE for offset that's too large.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.offsetByCodePoints(3, -4);
- fail("No IOOBE for offset that's too small.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.offsetByCodePoints(3, 1);
- fail("No IOOBE for index that's too large.");
- } catch (IndexOutOfBoundsException e) {
-
- }
-
- try {
- sb.offsetByCodePoints(4, -1);
- fail("No IOOBE for index that's too large.");
- } catch (IndexOutOfBoundsException e) {
-
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.replace(int, int, String)'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "replace",
- args = {int.class, int.class, java.lang.String.class}
- )
- public void test_replaceIILjava_lang_String() {
- final String fixture = "0000";
- StringBuilder sb = new StringBuilder(fixture);
- assertSame(sb, sb.replace(1, 3, "11"));
- assertEquals("0110", sb.toString());
- assertEquals(4, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.replace(1, 2, "11"));
- assertEquals("01100", sb.toString());
- assertEquals(5, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.replace(4, 5, "11"));
- assertEquals("000011", sb.toString());
- assertEquals(6, sb.length());
-
- sb = new StringBuilder(fixture);
- assertSame(sb, sb.replace(4, 6, "11"));
- assertEquals("000011", sb.toString());
- assertEquals(6, sb.length());
-
- // FIXME Undocumented NPE in Sun's JRE 5.0_5
- try {
- sb.replace(1, 2, null);
- fail("No NPE");
- } catch (NullPointerException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.replace(-1, 2, "11");
- fail("No SIOOBE, negative start");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.replace(5, 2, "11");
- fail("No SIOOBE, start > length");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb = new StringBuilder(fixture);
- sb.replace(3, 2, "11");
- fail("No SIOOBE, start > end");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- // Regression for HARMONY-348
- StringBuilder buffer = new StringBuilder("1234567");
- buffer.replace(2, 6, "XXX");
- assertEquals("12XXX7",buffer.toString());
- }
-
- /**
- * @tests java.lang.StringBuilder.reverse()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reverse",
- args = {}
- )
- public void test_reverse() {
- final String fixture = "0123456789";
- StringBuilder sb = new StringBuilder(fixture);
- assertSame(sb, sb.reverse());
- assertEquals("9876543210", sb.toString());
-
- sb = new StringBuilder("012345678");
- assertSame(sb, sb.reverse());
- assertEquals("876543210", sb.toString());
-
- sb.setLength(1);
- assertSame(sb, sb.reverse());
- assertEquals("8", sb.toString());
-
- sb.setLength(0);
- assertSame(sb, sb.reverse());
- assertEquals("", sb.toString());
- }
-
- /**
- * @tests java.lang.StringBuilder.setCharAt(int, char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setCharAt",
- args = {int.class, char.class}
- )
- public void test_setCharAtIC() {
- final String fixture = "0000";
- StringBuilder sb = new StringBuilder(fixture);
- sb.setCharAt(0, 'A');
- assertEquals("A000", sb.toString());
- sb.setCharAt(1, 'B');
- assertEquals("AB00", sb.toString());
- sb.setCharAt(2, 'C');
- assertEquals("ABC0", sb.toString());
- sb.setCharAt(3, 'D');
- assertEquals("ABCD", sb.toString());
-
- try {
- sb.setCharAt(-1, 'A');
- fail("No IOOBE, negative index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb.setCharAt(4, 'A');
- fail("No IOOBE, index == length");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb.setCharAt(5, 'A');
- fail("No IOOBE, index > length");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.setLength(int)'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setLength",
- args = {int.class}
- )
- public void test_setLengthI() {
- final String fixture = "0123456789";
- StringBuilder sb = new StringBuilder(fixture);
- sb.setLength(5);
- assertEquals(5, sb.length());
- assertEquals("01234", sb.toString());
- sb.setLength(6);
- assertEquals(6, sb.length());
- assertEquals("01234\0", sb.toString());
- sb.setLength(0);
- assertEquals(0, sb.length());
- assertEquals("", sb.toString());
-
- try {
- sb.setLength(-1);
- fail("No IOOBE, negative length.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.subSequence(int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "subSequence",
- args = {int.class, int.class}
- )
- public void test_subSequenceII() {
- final String fixture = "0123456789";
- StringBuilder sb = new StringBuilder(fixture);
- CharSequence ss = sb.subSequence(0, 5);
- assertEquals("01234", ss.toString());
-
- ss = sb.subSequence(0, 0);
- assertEquals("", ss.toString());
-
- try {
- sb.subSequence(-1, 1);
- fail("No IOOBE, negative start.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb.subSequence(0, -1);
- fail("No IOOBE, negative end.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb.subSequence(0, fixture.length() + 1);
- fail("No IOOBE, end > length.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb.subSequence(3, 2);
- fail("No IOOBE, start > end.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.substring(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "substring",
- args = {int.class}
- )
- public void test_substringI() {
- final String fixture = "0123456789";
- StringBuilder sb = new StringBuilder(fixture);
- String ss = sb.substring(0);
- assertEquals(fixture, ss);
-
- ss = sb.substring(10);
- assertEquals("", ss);
-
- try {
- sb.substring(-1);
- fail("No SIOOBE, negative start.");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb.substring(0, -1);
- fail("No SIOOBE, negative end.");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb.substring(fixture.length() + 1);
- fail("No SIOOBE, start > length.");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.substring(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "substring",
- args = {int.class, int.class}
- )
- public void test_substringII() {
- final String fixture = "0123456789";
- StringBuilder sb = new StringBuilder(fixture);
- String ss = sb.substring(0, 5);
- assertEquals("01234", ss);
-
- ss = sb.substring(0, 0);
- assertEquals("", ss);
-
- try {
- sb.substring(-1, 1);
- fail("No SIOOBE, negative start.");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb.substring(0, -1);
- fail("No SIOOBE, negative end.");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb.substring(0, fixture.length() + 1);
- fail("No SIOOBE, end > length.");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- sb.substring(3, 2);
- fail("No SIOOBE, start > end.");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.toString()'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- final String fixture = "0123456789";
- StringBuilder sb = new StringBuilder(fixture);
- assertEquals(fixture, sb.toString());
- }
-
- /**
- * @tests java.lang.StringBuilder.trimToSize()'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "trimToSize",
- args = {}
- )
- public void test_trimToSize() {
- final String fixture = "0123456789";
- StringBuilder sb = new StringBuilder(fixture);
- assertTrue(sb.capacity() > fixture.length());
- assertEquals(fixture.length(), sb.length());
- assertEquals(fixture, sb.toString());
- int prevCapacity = sb.capacity();
- sb.trimToSize();
- assertTrue(prevCapacity > sb.capacity());
- assertEquals(fixture.length(), sb.length());
- assertEquals(fixture, sb.toString());
- }
-
- // comparator for StringBuilder objects
- private static final SerializableAssert STRING_BILDER_COMPARATOR = new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
-
- StringBuilder init = (StringBuilder) initial;
- StringBuilder desr = (StringBuilder) deserialized;
-
- assertEquals("toString", init.toString(), desr.toString());
- }
- };
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization.",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new StringBuilder("0123456789"),
- STRING_BILDER_COMPARATOR);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new StringBuilder("0123456789"),
- STRING_BILDER_COMPARATOR);
- }
-
- private static final class Fixture {
- static final Fixture INSTANCE = new Fixture();
-
- private Fixture() {
- super();
- }
-
- @Override
- public String toString() {
- return "fixture";
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringIndexOutOfBoundsExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringIndexOutOfBoundsExceptionTest.java
deleted file mode 100644
index 2adf610..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringIndexOutOfBoundsExceptionTest.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(StringIndexOutOfBoundsException.class)
-public class StringIndexOutOfBoundsExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.StringIndexOutOfBoundsException#StringIndexOutOfBoundsException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StringIndexOutOfBoundsException",
- args = {}
- )
- public void test_Constructor() {
- StringIndexOutOfBoundsException e = new StringIndexOutOfBoundsException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.StringIndexOutOfBoundsException#StringIndexOutOfBoundsException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StringIndexOutOfBoundsException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- StringIndexOutOfBoundsException e = new StringIndexOutOfBoundsException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StringIndexOutOfBoundsException",
- args = {int.class}
- )
- public void test_ConstructorLint() {
- StringIndexOutOfBoundsException e = new StringIndexOutOfBoundsException(0);
- assertTrue(e.getMessage().contains("0"));
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringTest.java
deleted file mode 100644
index 6c995bb..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringTest.java
+++ /dev/null
@@ -1,704 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.UnsupportedEncodingException;
-import java.lang.reflect.Constructor;
-
-@TestTargetClass(String.class)
-public class StringTest extends TestCase {
-
- private static String newString(int start, int len, char[] data) {
- return new String(data, start,len);
- }
-
- /**
- * @tests java.lang.String#String()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {}
- )
- public void test_Constructor() {
- assertEquals("Created incorrect string", "", new String());
- }
-
- /**
- * @tests java.lang.String#String(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {byte[].class}
- )
- public void test_Constructor$B() {
- assertEquals("Failed to create string", "HelloWorld", new String(
- "HelloWorld".getBytes()));
- }
-
- /**
- * @tests java.lang.String#String(byte[], int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {byte[].class, int.class}
- )
- @SuppressWarnings("deprecation")
- public void test_Constructor$BI() {
- String s = new String(new byte[] { 65, 66, 67, 68, 69 }, 0);
- assertEquals("Incorrect string returned: " + s, "ABCDE", s);
- s = new String(new byte[] { 65, 66, 67, 68, 69 }, 1);
- assertFalse("Did not use nonzero hibyte", s.equals("ABCDE"));
- }
-
- /**
- * @tests java.lang.String#String(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {byte[].class, int.class, int.class}
- )
- public void test_Constructor$BII() {
- byte[] hwba = "HelloWorld".getBytes();
- assertEquals("Failed to create string", "HelloWorld", new String(hwba,
- 0, hwba.length));
-
- try {
- new String(new byte[0], 0, Integer.MAX_VALUE);
- fail("No IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * @tests java.lang.String#String(byte[], int, int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "IndexOutOfBoundsException is not verified.",
- method = "String",
- args = {byte[].class, int.class, int.class, int.class}
- )
- @SuppressWarnings("deprecation")
- public void test_Constructor$BIII() {
- String s = new String(new byte[] { 65, 66, 67, 68, 69 }, 0, 1, 3);
- assertEquals("Incorrect string returned: " + s, "BCD", s);
- s = new String(new byte[] { 65, 66, 67, 68, 69 }, 1, 0, 5);
- assertFalse("Did not use nonzero hibyte", s.equals("ABCDE"));
- }
-
- /**
- * @tests java.lang.String#String(byte[], int, int, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {byte[].class, int.class, int.class, java.lang.String.class}
- )
- public void test_Constructor$BIILjava_lang_String() throws Exception {
- String s = new String(new byte[] { 65, 66, 67, 68, 69 }, 0, 5, "8859_1");
- assertEquals("Incorrect string returned: " + s, "ABCDE", s);
-
- try {
- new String(new byte[] { 65, 66, 67, 68, 69 }, 0, 5, "");
- fail("Should throw UnsupportedEncodingException");
- } catch (UnsupportedEncodingException e) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.String#String(byte[], java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "UnsupportedEncodingException is not verified.",
- method = "String",
- args = {byte[].class, java.lang.String.class}
- )
- public void test_Constructor$BLjava_lang_String() throws Exception {
- String s = new String(new byte[] { 65, 66, 67, 68, 69 }, "8859_1");
- assertEquals("Incorrect string returned: " + s, "ABCDE", s);
- }
-
- /**
- * @tests java.lang.String#String(char[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {char[].class}
- )
- public void test_Constructor$C() {
- assertEquals("Failed Constructor test", "World", new String(new char[] {
- 'W', 'o', 'r', 'l', 'd' }));
- }
-
- /**
- * @tests java.lang.String#String(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {char[].class, int.class, int.class}
- )
- public void test_Constructor$CII() throws Exception {
- char[] buf = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
- String s = new String(buf, 0, buf.length);
- assertEquals("Incorrect string created", "HelloWorld", s);
-
- try {
- new String(new char[0], 0, Integer.MAX_VALUE);
- fail("No IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * @tests java.lang.String#String(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- String s = new String("Hello World");
- assertEquals("Failed to construct correct string", "Hello World", s);
- }
-
- /**
- * @tests java.lang.String#String(java.lang.StringBuffer)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {java.lang.StringBuffer.class}
- )
- public void test_ConstructorLjava_lang_StringBuffer() {
- StringBuffer sb = new StringBuffer();
- sb.append("HelloWorld");
- assertEquals("Created incorrect string", "HelloWorld", new String(sb));
- }
-
- /**
- * @tests java.lang.String#String(java.lang.StringBuilder)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {java.lang.StringBuilder.class}
- )
- public void test_ConstructorLjava_lang_StringBuilder() {
- StringBuilder sb = new StringBuilder(32);
- sb.append("HelloWorld");
- assertEquals("HelloWorld", new String(sb));
-
- try {
- new String((StringBuilder) null);
- fail("No NPE");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @tests java.lang.String#String(int[],int,int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "String",
- args = {int[].class, int.class, int.class}
- )
- public void test_Constructor$III() {
- assertEquals("HelloWorld", new String(new int[] { 'H', 'e', 'l', 'l',
- 'o', 'W', 'o', 'r', 'l', 'd' }, 0, 10));
- assertEquals("Hello", new String(new int[] { 'H', 'e', 'l', 'l', 'o',
- 'W', 'o', 'r', 'l', 'd' }, 0, 5));
- assertEquals("World", new String(new int[] { 'H', 'e', 'l', 'l', 'o',
- 'W', 'o', 'r', 'l', 'd' }, 5, 5));
- assertEquals("", new String(new int[] { 'H', 'e', 'l', 'l', 'o', 'W',
- 'o', 'r', 'l', 'd' }, 5, 0));
-
- assertEquals("\uD800\uDC00", new String(new int[] { 0x010000 }, 0, 1));
- assertEquals("\uD800\uDC00a\uDBFF\uDFFF", new String(new int[] {
- 0x010000, 'a', 0x010FFFF }, 0, 3));
-
- try {
- new String((int[]) null, 0, 1);
- fail("No NPE");
- } catch (NullPointerException e) {
- }
-
- try {
- new String(new int[] { 'a', 'b' }, -1, 2);
- fail("No IOOBE, negative offset");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- new String(new int[] { 'a', 'b' }, 0, -1);
- fail("No IOOBE, negative count");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- new String(new int[] { 'a', 'b' }, 0, -1);
- fail("No IOOBE, negative count");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- new String(new int[] { 'a', 'b' }, 0, 3);
- fail("No IOOBE, too large");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * @tests java.lang.String#contentEquals(CharSequence)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "contentEquals",
- args = {java.lang.CharSequence.class}
- )
- public void test_contentEqualsLjava_lang_CharSequence() {
- String s = "abc";
- assertTrue(s.contentEquals((CharSequence) new StringBuffer("abc")));
- assertFalse(s.contentEquals((CharSequence) new StringBuffer("def")));
- assertFalse(s.contentEquals((CharSequence) new StringBuffer("ghij")));
-
- s = newString(1, 3, "_abc_".toCharArray());
- assertTrue(s.contentEquals((CharSequence) new StringBuffer("abc")));
- assertFalse(s.contentEquals((CharSequence) new StringBuffer("def")));
- assertFalse(s.contentEquals((CharSequence) new StringBuffer("ghij")));
-
- try {
- s.contentEquals((CharSequence) null);
- fail("No NPE");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @tests java.lang.String#contentEquals(StringBuffer)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "contentEquals",
- args = {java.lang.StringBuffer.class}
- )
- @SuppressWarnings("nls")
- public void test_boolean_contentEquals_StringBuffer() {
- String s = "abc";
- assertTrue(s.contentEquals(new StringBuffer("abc")));
- assertFalse(s.contentEquals(new StringBuffer("def")));
- assertFalse(s.contentEquals(new StringBuffer("ghij")));
-
- s = newString(1, 3, "_abc_".toCharArray());
- assertTrue(s.contentEquals(new StringBuffer("abc")));
- assertFalse(s.contentEquals(new StringBuffer("def")));
- assertFalse(s.contentEquals(new StringBuffer("ghij")));
-
- try {
- s.contentEquals((StringBuffer) null);
- fail("Should throw a NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.lang.String#contains(CharSequence)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "contains",
- args = {java.lang.CharSequence.class}
- )
- @SuppressWarnings("cast")
- public void test_containsLjava_lang_CharSequence() {
- String s = "abcdefghijklmnopqrstuvwxyz";
- assertTrue(s.contains((CharSequence) new StringBuffer("abc")));
- assertTrue(s.contains((CharSequence) new StringBuffer("def")));
- assertFalse(s.contains((CharSequence) new StringBuffer("ac")));
-
- s = newString(1, 26, "_abcdefghijklmnopqrstuvwxyz_".toCharArray());
- assertTrue(s.contains((CharSequence) new StringBuffer("abc")));
- assertTrue(s.contains((CharSequence) new StringBuffer("def")));
- assertFalse(s.contains((CharSequence) new StringBuffer("ac")));
-
- try {
- s.contentEquals((CharSequence) null);
- fail("No NPE");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @tests java.lang.String.offsetByCodePoints(int, int)'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "offsetByCodePoints",
- args = {int.class, int.class}
- )
- public void test_offsetByCodePointsII() {
- int result = new String("a\uD800\uDC00b").offsetByCodePoints(0, 2);
- assertEquals(3, result);
-
- result = new String("abcd").offsetByCodePoints(3, -1);
- assertEquals(2, result);
-
- result = new String("a\uD800\uDC00b").offsetByCodePoints(0, 3);
- assertEquals(4, result);
-
- result = new String("a\uD800\uDC00b").offsetByCodePoints(3, -1);
- assertEquals(1, result);
-
- result = new String("a\uD800\uDC00b").offsetByCodePoints(3, 0);
- assertEquals(3, result);
-
- result = new String("\uD800\uDC00bc").offsetByCodePoints(3, 0);
- assertEquals(3, result);
-
- result = new String("a\uDC00bc").offsetByCodePoints(3, -1);
- assertEquals(2, result);
-
- result = new String("a\uD800bc").offsetByCodePoints(3, -1);
- assertEquals(2, result);
-
- result = newString(2, 4, "__a\uD800\uDC00b__".toCharArray())
- .offsetByCodePoints(0, 2);
- assertEquals(3, result);
-
- result = newString(2, 4, "__abcd__".toCharArray()).offsetByCodePoints(
- 3, -1);
- assertEquals(2, result);
-
- result = newString(2, 4, "__a\uD800\uDC00b__".toCharArray())
- .offsetByCodePoints(0, 3);
- assertEquals(4, result);
-
- result = newString(2, 4, "__a\uD800\uDC00b__".toCharArray())
- .offsetByCodePoints(3, -1);
- assertEquals(1, result);
-
- result = newString(2, 4, "__a\uD800\uDC00b__".toCharArray())
- .offsetByCodePoints(3, 0);
- assertEquals(3, result);
-
- result = newString(2, 4, "__\uD800\uDC00bc__".toCharArray())
- .offsetByCodePoints(3, 0);
- assertEquals(3, result);
-
- result = newString(2, 4, "__a\uDC00bc__".toCharArray())
- .offsetByCodePoints(3, -1);
- assertEquals(2, result);
-
- result = newString(2, 4, "__a\uD800bc__".toCharArray())
- .offsetByCodePoints(3, -1);
- assertEquals(2, result);
-
- String s = "abc";
- try {
- s.offsetByCodePoints(-1, 1);
- fail("No IOOBE for negative index.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.offsetByCodePoints(0, 4);
- fail("No IOOBE for offset that's too large.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.offsetByCodePoints(3, -4);
- fail("No IOOBE for offset that's too small.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.offsetByCodePoints(3, 1);
- fail("No IOOBE for index that's too large.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.offsetByCodePoints(4, -1);
- fail("No IOOBE for index that's too large.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- s = newString(2,3,"__abc__".toCharArray());
- try {
- s.offsetByCodePoints(-1, 1);
- fail("No IOOBE for negative index.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.offsetByCodePoints(0, 4);
- fail("No IOOBE for offset that's too large.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.offsetByCodePoints(3, -4);
- fail("No IOOBE for offset that's too small.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.offsetByCodePoints(3, 1);
- fail("No IOOBE for index that's too large.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.offsetByCodePoints(4, -1);
- fail("No IOOBE for index that's too large.");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.codePointAt(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "codePointAt",
- args = {int.class}
- )
- public void test_codePointAtI() {
- String s = "abc";
- assertEquals('a', s.codePointAt(0));
- assertEquals('b', s.codePointAt(1));
- assertEquals('c', s.codePointAt(2));
-
- s = newString(2,3,"__abc__".toCharArray());
- assertEquals('a', s.codePointAt(0));
- assertEquals('b', s.codePointAt(1));
- assertEquals('c', s.codePointAt(2));
-
- s = "\uD800\uDC00";
- assertEquals(0x10000, s.codePointAt(0));
- assertEquals('\uDC00', s.codePointAt(1));
-
- s = newString(2,2,"__\uD800\uDC00__".toCharArray());
- assertEquals(0x10000, s.codePointAt(0));
- assertEquals('\uDC00', s.codePointAt(1));
-
- s = "abc";
- try {
- s.codePointAt(-1);
- fail("No IOOBE on negative index.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.codePointAt(s.length());
- fail("No IOOBE on index equal to length.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.codePointAt(s.length() + 1);
- fail("No IOOBE on index greater than length.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- s = newString(2,3,"__abc__".toCharArray());
- try {
- s.codePointAt(-1);
- fail("No IOOBE on negative index.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.codePointAt(s.length());
- fail("No IOOBE on index equal to length.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.codePointAt(s.length() + 1);
- fail("No IOOBE on index greater than length.");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.codePointBefore(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "codePointBefore",
- args = {int.class}
- )
- public void test_codePointBeforeI() {
- String s = "abc";
- assertEquals('a', s.codePointBefore(1));
- assertEquals('b', s.codePointBefore(2));
- assertEquals('c', s.codePointBefore(3));
-
- s = newString(2,3,"__abc__".toCharArray());
- assertEquals('a', s.codePointBefore(1));
- assertEquals('b', s.codePointBefore(2));
- assertEquals('c', s.codePointBefore(3));
-
- s = "\uD800\uDC00";
- assertEquals(0x10000, s.codePointBefore(2));
- assertEquals('\uD800', s.codePointBefore(1));
-
- s = newString(2,2,"__\uD800\uDC00__".toCharArray());
- assertEquals(0x10000, s.codePointBefore(2));
- assertEquals('\uD800', s.codePointBefore(1));
-
- s = "abc";
- try {
- s.codePointBefore(0);
- fail("No IOOBE on zero index.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.codePointBefore(-1);
- fail("No IOOBE on negative index.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.codePointBefore(s.length() + 1);
- fail("No IOOBE on index greater than length.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- s = newString(2,3,"__abc__".toCharArray());
- try {
- s.codePointBefore(0);
- fail("No IOOBE on zero index.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.codePointBefore(-1);
- fail("No IOOBE on negative index.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.codePointBefore(s.length() + 1);
- fail("No IOOBE on index greater than length.");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * @tests java.lang.StringBuilder.codePointCount(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "codePointCount",
- args = {int.class, int.class}
- )
- public void test_codePointCountII() {
- assertEquals(1, "\uD800\uDC00".codePointCount(0, 2));
- assertEquals(1, "\uD800\uDC01".codePointCount(0, 2));
- assertEquals(1, "\uD801\uDC01".codePointCount(0, 2));
- assertEquals(1, "\uDBFF\uDFFF".codePointCount(0, 2));
-
- assertEquals(3, "a\uD800\uDC00b".codePointCount(0, 4));
- assertEquals(4, "a\uD800\uDC00b\uD800".codePointCount(0, 5));
-
- assertEquals(1, newString(2,2,"__\uD800\uDC00__".toCharArray()).codePointCount(0, 2));
- assertEquals(1, newString(2,2,"__\uD800\uDC01__".toCharArray()).codePointCount(0, 2));
- assertEquals(1, newString(2,2,"__\uD801\uDC01__".toCharArray()).codePointCount(0, 2));
- assertEquals(1, newString(2,2,"__\uDBFF\uDFFF__".toCharArray()).codePointCount(0, 2));
-
- assertEquals(3, newString(2,4,"__a\uD800\uDC00b__".toCharArray()).codePointCount(0, 4));
- assertEquals(4, newString(2,5,"__a\uD800\uDC00b\uD800__".toCharArray()).codePointCount(0, 5));
-
- String s = "abc";
- try {
- s.codePointCount(-1, 2);
- fail("No IOOBE for negative begin index.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.codePointCount(0, 4);
- fail("No IOOBE for end index that's too large.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.codePointCount(3, 2);
- fail("No IOOBE for begin index larger than end index.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- s = newString(2, 3, "__abc__".toCharArray());
- try {
- s.codePointCount(-1, 2);
- fail("No IOOBE for negative begin index.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.codePointCount(0, 4);
- fail("No IOOBE for end index that's too large.");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- s.codePointCount(3, 2);
- fail("No IOOBE for begin index larger than end index.");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SystemTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SystemTest.java
deleted file mode 100644
index 2c65f52..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SystemTest.java
+++ /dev/null
@@ -1,1236 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PrintStream;
-import java.nio.channels.Channel;
-import java.nio.channels.spi.SelectorProvider;
-import java.security.Permission;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Vector;
-
-@TestTargetClass(System.class)
-public class SystemTest extends junit.framework.TestCase {
-
- static boolean flag = false;
-
- static boolean ranFinalize = false;
-
- /**
- * @tests java.lang.System#setIn(java.io.InputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setIn",
- args = {java.io.InputStream.class}
- )
- public void test_setInLjava_io_InputStream() {
- InputStream orgIn = System.in;
- InputStream in = new ByteArrayInputStream(new byte[0]);
- System.setIn(in);
- assertTrue("in not set", System.in == in);
- System.setIn(orgIn);
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if(perm.getName().equals("setIO")) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
-
- try {
- System.setIn(in);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.System#setOut(java.io.PrintStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setOut",
- args = {java.io.PrintStream.class}
- )
- public void test_setOutLjava_io_PrintStream() {
- PrintStream orgOut = System.out;
- PrintStream out = new PrintStream(new ByteArrayOutputStream());
- System.setOut(out);
- assertTrue("out not set", System.out == out);
- System.setOut(orgOut);
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if(perm.getName().equals("setIO")) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
-
- try {
- System.setOut(out);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.System#setErr(java.io.PrintStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setErr",
- args = {java.io.PrintStream.class}
- )
- public void test_setErrLjava_io_PrintStream() {
- PrintStream orgErr = System.err;
- PrintStream err = new PrintStream(new ByteArrayOutputStream());
- System.setErr(err);
- assertTrue("err not set", System.err == err);
- System.setErr(orgErr);
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if(perm.getName().equals("setIO")) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
-
- try {
- System.setErr(err);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.System#arraycopy(java.lang.Object, int,
- * java.lang.Object, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "arraycopy",
- args = {java.lang.Object.class, int.class, java.lang.Object.class,
- int.class, int.class}
- )
- public void test_arraycopyLjava_lang_ObjectILjava_lang_ObjectII() {
- // Test for method void java.lang.System.arraycopy(java.lang.Object,
- // int, java.lang.Object, int, int)
- Integer a[] = new Integer[20];
- Integer b[] = new Integer[20];
- int i = 0;
- while (i < a.length) {
- a[i] = new Integer(i);
- ++i;
- }
- System.arraycopy(a, 0, b, 0, a.length);
- for (i = 0; i < a.length; i++)
- assertTrue("Copied elements incorrectly", a[i].equals(b[i]));
-
- /* Non primitive array types don't need to be identical */
- String[] source1 = new String[] { "element1" };
- Object[] dest1 = new Object[1];
- System.arraycopy(source1, 0, dest1, 0, dest1.length);
- assertTrue("Invalid copy 1", dest1[0] == source1[0]);
-
- char[][] source = new char[][] { { 'H', 'e', 'l', 'l', 'o' },
- { 'W', 'o', 'r', 'l', 'd' } };
- char[][] dest = new char[2][];
- System.arraycopy(source, 0, dest, 0, dest.length);
- assertTrue("Invalid copy 2", dest[0] == source[0]
- && dest[1] == source[1]);
-
- try {
- // copy from non array object into Object array
- System.arraycopy(new Object(), 0, b, 0, 0);
- fail("ArrayStoreException is not thrown.");
- } catch(ArrayStoreException ase) {
- //expected
- }
-
- try {
- // copy from Object array into non array object
- System.arraycopy(a, 0, new Object(), 0, 0);
- fail("ArrayStoreException is not thrown.");
- } catch(ArrayStoreException ase) {
- //expected
- }
-
- try {
- // copy from primitive array into object array
- System.arraycopy(new char[] {'a'}, 0, new String[1], 0, 1);
- fail("ArrayStoreException is not thrown.");
- } catch(ArrayStoreException ase) {
- //expected
- }
-
- try {
- // copy from object array into primitive array
- System.arraycopy(new String[] {"a"}, 0, new char[1], 0, 1);
- fail("ArrayStoreException is not thrown.");
- } catch(ArrayStoreException ase) {
- //expected
- }
-
- try {
- // copy from primitive array into an array of another primitive type
- System.arraycopy(new char[] {'a'}, 0, new int[1], 0, 1);
- fail("ArrayStoreException is not thrown.");
- } catch(ArrayStoreException ase) {
- //expected
- }
-
- try {
- // copy from object array into an array of another Object type
- System.arraycopy(new Character[] {'a'}, 0, new Integer[1], 0, 1);
- fail("ArrayStoreException is not thrown.");
- } catch(ArrayStoreException ase) {
- //expected
- }
-
- try {
- // copy from null into an array of a primitive type
- System.arraycopy(null, 0, new int[1], 0, 1);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- try {
- // copy from a primitive array into null
- System.arraycopy(new int[]{'1'}, 0, null, 0, 1);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- try {
- System.arraycopy(a, a.length + 1, b, 0, 1);
- fail("IndexOutOfBoundsException is not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
-
- try {
- System.arraycopy(a, -1, b, 0, 1);
- fail("IndexOutOfBoundsException is not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
-
- try {
- System.arraycopy(a, 0, b, -1, 1);
- fail("IndexOutOfBoundsException is not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
-
- try {
- System.arraycopy(a, 0, b, 0, -1);
- fail("IndexOutOfBoundsException is not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
-
- try {
- System.arraycopy(a, 11, b, 0, 10);
- fail("IndexOutOfBoundsException is not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
-
- try {
- System.arraycopy(a, Integer.MAX_VALUE, b, 0, 10);
- fail("IndexOutOfBoundsException is not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
-
- try {
- System.arraycopy(a, 0, b, Integer.MAX_VALUE, 10);
- fail("IndexOutOfBoundsException is not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
-
- try {
- System.arraycopy(a, 0, b, 10, Integer.MAX_VALUE);
- fail("IndexOutOfBoundsException is not thrown.");
- } catch(IndexOutOfBoundsException ioobe) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.System#currentTimeMillis()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "currentTimeMillis",
- args = {}
- )
- public void test_currentTimeMillis() {
- // Test for method long java.lang.System.currentTimeMillis()
- try {
- long firstRead = System.currentTimeMillis();
- try {
- Thread.sleep(150);
- } catch (InterruptedException e) {
- }
- long secondRead = System.currentTimeMillis();
- assertTrue("Incorrect times returned: " + firstRead + ", "
- + secondRead, firstRead < secondRead);
- } catch (Exception e) {
- fail("Exception during test: " + e.toString());
- }
- }
-
- /**
- * @tests java.lang.System#exit(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies SecurityException.",
- method = "exit",
- args = {int.class}
- )
- public void test_exitI() {
- SecurityManager sm = new SecurityManager() {
-
- final String forbidenPermissionName = "user.dir";
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals(forbidenPermissionName)) {
- throw new SecurityException();
- }
- }
-
- public void checkExit(int status) {
- if(status == -1)
- throw new SecurityException();
- }
-
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- System.exit(-1);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.System#getProperties()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getProperties",
- args = {}
- )
- public void test_getProperties() {
-
- // Test for method java.util.Properties java.lang.System.getProperties()
- /* String[] props = { "java.version", "java.vendor", "java.vendor.url",
- "java.home", "java.vm.specification.version",
- "java.vm.specification.vendor", "java.vm.specification.name",
- "java.vm.version", "java.vm.vendor", "java.vm.name",
- "java.specification.name", "java.specification.vendor",
- "java.specification.name", "java.class.version",
- "java.class.path", "java.ext.dirs", "os.name", "os.arch",
- "os.version", "file.separator", "path.separator",
- "line.separator", "user.name", "user.home", "user.dir", };
- */
-
- String [] props = {"java.vendor.url",
- "java.class.path", "user.home",
- "java.class.version", "os.version",
- "java.vendor", "user.dir",
- /*"user.timezone",*/ "path.separator",
- "os.name", "os.arch",
- "line.separator", "file.separator",
- "user.name", "java.version", "java.home" };
-
- /* Available properties.
- String [] props = {"java.boot.class.path", "java.class.path",
- "java.class.version", "java.compiler", "java.ext.dirs",
- "java.home", "java.io.tmpdir", "java.library.path",
- "java.vendor", "java.vendor.url", "java.version",
- "java.vm.name", "java.vm.specification.name",
- "java.vm.specification.vendor", "java.vm.specification.version",
- "java.vm.vendor", "java.vm.version", "java.specification.name",
- "java.specification.vendor", "java.specification.version",
- "os.arch", "os.name", "os.version", "user.home", "user.name",
- "user.dir", "file.separator", "line.separator",
- "path.separator", "java.runtime.name", "java.runtime.version",
- "java.vm.vendor.url", "file.encoding","user.language",
- "user.region"};
- */
-
- Properties p = System.getProperties();
- assertTrue(p.size() > 0);
-
- // Ensure spec'ed properties are non-null. See System.getProperties()
- // spec.
-
- for (int i = 0; i < props.length; i++) {
- assertNotNull("There is no property among returned properties: "
- + props[i], p.getProperty(props[i]));
- assertNotNull("System property is null: " + props[i],
- System.getProperty(props[i]));
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkPropertiesAccess() {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
-
- try {
- System.getProperties();
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.System#getProperty(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getProperty",
- args = {java.lang.String.class}
- )
- public void test_getPropertyLjava_lang_String() {
- // Test for method java.lang.String
- // java.lang.System.getProperty(java.lang.String)
- assertTrue("Failed to return correct property value", System
- .getProperty("line.separator").indexOf("\n", 0) >= 0);
-
- boolean is8859_1 = true;
- String encoding = System.getProperty("file.encoding");
- byte[] bytes = new byte[128];
- char[] chars = new char[128];
- for (int i = 0; i < bytes.length; i++) {
- bytes[i] = (byte) (i + 128);
- chars[i] = (char) (i + 128);
- }
- String charResult = new String(bytes);
- byte[] byteResult = new String(chars).getBytes();
- if (charResult.length() == 128 && byteResult.length == 128) {
- for (int i = 0; i < bytes.length; i++) {
- if (charResult.charAt(i) != (char) (i + 128)
- || byteResult[i] != (byte) (i + 128))
- is8859_1 = false;
- }
- } else
- is8859_1 = false;
- String[] possibles = new String[] { "ISO8859_1", "8859_1", "ISO8859-1",
- "ISO-8859-1", "ISO_8859-1", "ISO_8859-1:1978", "ISO-IR-100",
- "LATIN1", "CSISOLATIN1" };
- boolean found8859_1 = false;
- for (int i = 0; i < possibles.length; i++) {
- if (possibles[i].equals(encoding)) {
- found8859_1 = true;
- break;
- }
- }
- assertTrue("Wrong encoding: " + encoding, !is8859_1 || found8859_1);
-
- try {
- System.getProperty(null);
- fail("NullPointerException should be thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- try {
- System.getProperty("");
- fail("IllegalArgumentException should be thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- @SuppressWarnings("unused")
- public void checkPropertyAccess(String key) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
-
- try {
- System.getProperty("user.name");
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.System#getProperty(java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getProperty",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_getPropertyLjava_lang_StringLjava_lang_String() {
- // Test for method java.lang.String
- // java.lang.System.getProperty(java.lang.String, java.lang.String)
- assertTrue("Failed to return correct property value: "
- + System.getProperty("line.separator", "99999"), System
- .getProperty("line.separator", "99999").indexOf("\n", 0) >= 0);
- assertEquals("Failed to return correct property value", "bogus", System
- .getProperty("bogus.prop", "bogus"));
-
- try {
- System.getProperty(null, "0.0");
- fail("NullPointerException should be thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- try {
- System.getProperty("", "0");
- fail("IllegalArgumentException should be thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- @SuppressWarnings("unused")
- public void checkPropertyAccess(String key) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
-
- try {
- System.getProperty("java.version", "0");
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.System#setProperty(java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setProperty",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_setPropertyLjava_lang_StringLjava_lang_String() {
- // Test for method java.lang.String
- // java.lang.System.setProperty(java.lang.String, java.lang.String)
-
- assertNull("Failed to return null", System.setProperty("testing",
- "value1"));
- assertTrue("Failed to return old value", System.setProperty("testing",
- "value2") == "value1");
- assertTrue("Failed to find value",
- System.getProperty("testing") == "value2");
-
- boolean exception = false;
- try {
- System.setProperty("", "default");
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue("Expected IllegalArgumentException", exception);
- }
-
- /**
- * @tests java.lang.System#getSecurityManager()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Doesn't check positive functionality.",
- method = "getSecurityManager",
- args = {}
- )
- public void test_getSecurityManager() {
- // Test for method java.lang.SecurityManager
- // java.lang.System.getSecurityManager()
- assertNull("Returned incorrect SecurityManager", System
- .getSecurityManager());
- }
-
- /**
- * @tests java.lang.System#identityHashCode(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "identityHashCode",
- args = {java.lang.Object.class}
- )
- public void test_identityHashCodeLjava_lang_Object() {
- // Test for method int
- // java.lang.System.identityHashCode(java.lang.Object)
- Object o = new Object();
- String s = "Gabba";
- assertEquals("Nonzero returned for null",
- 0, System.identityHashCode(null));
- assertTrue("Nonequal has returned for Object", System
- .identityHashCode(o) == o.hashCode());
- assertTrue("Same as usual hash returned for String", System
- .identityHashCode(s) != s.hashCode());
- }
-
- /**
- * @throws IOException
- * @tests java.lang.System#inheritedChannel()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "inheritedChannel",
- args = {}
- )
- public void test_inheritedChannel() throws IOException {
- Channel iChannel = System.inheritedChannel();
- assertNull("Incorrect value of channel", iChannel);
- SelectorProvider sp = SelectorProvider.provider();
- assertEquals("Incorrect value of channel",
- sp.inheritedChannel(), iChannel);
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if(perm.getName().equals("inheritedChannel")) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
-
- try {
- System.inheritedChannel();
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.System#runFinalization()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "runFinalization",
- args = {}
- )
- public void test_runFinalization() {
- // Test for method void java.lang.System.runFinalization()
-
- flag = true;
- createInstance();
- int count = 10;
- // the gc below likely bogosifies the test, but will have to do for
- // the moment
- while (!ranFinalize && count-- > 0) {
- System.gc();
- System.runFinalization();
- }
- assertTrue("Failed to run finalization", ranFinalize);
- }
-
- /**
- * @tests java.lang.System#runFinalizersOnExit(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "runFinalizersOnExit",
- args = {boolean.class}
- )
- @SuppressWarnings("deprecation")
- public void test_runFinalizersOnExitZ() {
- // Can we call the method at least?
- try {
- System.runFinalizersOnExit(false);
- } catch (Throwable t) {
- fail("Failed to set runFinalizersOnExit");
- }
-
- try {
- System.runFinalizersOnExit(true);
- } catch (Throwable t) {
- fail("Failed to set runFinalizersOnExit");
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkExit(int status) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
-
- try {
- System.runFinalizersOnExit(true);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.System#setProperties(java.util.Properties)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setProperties",
- args = {java.util.Properties.class}
- )
- public void test_setPropertiesLjava_util_Properties() {
- // Test for method void
- // java.lang.System.setProperties(java.util.Properties)
-
- Properties orgProps = System.getProperties();
- java.util.Properties tProps = new java.util.Properties();
- tProps.put("test.prop", "this is a test property");
- tProps.put("bogus.prop", "bogus");
- System.setProperties(tProps);
- try {
- assertEquals("Failed to set properties", "this is a test property", System.getProperties()
- .getProperty("test.prop"));
- } finally {
- // restore the original properties
- System.setProperties(orgProps);
- }
- }
-
- //Regression Test for Harmony-2356
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getenv",
- args = {}
- )
- public void testEnvUnmodifiable() {
- Map map = System.getenv();
- try {
- map.containsKey(null);
- fail("Should throw NullPointerExcepiton.");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- map.containsKey(new Integer(10));
- fail("Should throw ClassCastException.");
- } catch (ClassCastException e) {
- // expected
- }
-
- try {
- map.containsValue(null);
- fail("Should throw NullPointerExcepiton.");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- map.containsValue(new Integer(10));
- fail("Should throw ClassCastException.");
- } catch (ClassCastException e) {
- // expected
- }
-
- try {
- map.get(null);
- fail("Should throw NullPointerExcepiton.");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- map.get(new Integer(10));
- fail("Should throw ClassCastException.");
- } catch (ClassCastException e) {
- // expected
- }
-
- try {
- map.put(null, "AAA");
- fail("Should throw UnsupportedOperationExcepiton.");
- } catch (UnsupportedOperationException e) {
- // expected
- }
-
- try {
- map.put("AAA", new Integer(10));
- fail("Should throw UnsupportedOperationException.");
- } catch (UnsupportedOperationException e) {
- // expected
- }
-
- try {
- map.put("AAA", "BBB");
- fail("Should throw UnsupportedOperationException.");
- } catch (UnsupportedOperationException e) {
- // expected
- }
-
- try {
- map.clear();
- fail("Should throw UnsupportedOperationException.");
- } catch (UnsupportedOperationException e) {
- // expected
- }
-
- try {
- map.remove(null);
- fail("Should throw UnsupportedOperationException.");
- } catch (UnsupportedOperationException e) {
- // expected
- }
-
- }
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setSecurityManager",
- args = {java.lang.SecurityManager.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSecurityManager",
- args = {}
- )
- })
- public void test_setSecurityManagerLjava_lang_SecurityManager() {
- assertEquals("Incorrect SecurityManager",
- null, System.getSecurityManager());
- try {
- SecurityManager localManager = new MockSecurityManager();
- System.setSecurityManager(localManager);
- assertEquals("Incorrect SecurityManager",
- localManager, System.getSecurityManager());
- } finally {
- System.setSecurityManager(null);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clearProperty",
- args = {java.lang.String.class}
- )
- public void test_clearProperty() {
- System.setProperty("test", "value");
- System.clearProperty("test");
- assertNull("Property was not deleted.", System.getProperty("test"));
-
- try {
- System.clearProperty(null);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- try {
- System.clearProperty("");
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals("test")) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- System.clearProperty("test");
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "gc",
- args = {}
- )
- public void test_gc() {
- Runtime rt = Runtime.getRuntime();
- Vector<StringBuffer> vec = new Vector<StringBuffer>();
- long beforeTest = rt.freeMemory();
- while(rt.freeMemory() < beforeTest * 2/3) {
- vec.add(new StringBuffer(1000));
- }
- vec = null;
- long beforeGC = rt.freeMemory();
- System.gc();
- long afterGC = rt.freeMemory();
- assertTrue("memory was not released after calling System.gc()." +
- "before gc: " + beforeGC + "; after gc: " + afterGC,
- beforeGC < afterGC);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getenv",
- args = {}
- )
- public void test_getenv() {
-
- // String[] props = { "PATH", "HOME", "USER"};
- // only PATH of these three exists on android
- String[] props = { "PATH" };
-
- Map<String,String> envMap = System.getenv();
- assertFalse("environment map is empty.", envMap.isEmpty());
- assertTrue("env map contains less than 3 keys.",
- props.length < envMap.keySet().size());
- for(int i = 0; i < props.length; i++) {
- assertNotNull("There is no property: " + props[i],
- envMap.get(props[i]));
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if(perm.getName().equals("getenv.*")) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
-
- try {
- System.getenv();
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getenv",
- args = {java.lang.String.class}
- )
- public void test_getenvLString() {
-
- assertNotNull("PATH environment variable is not found",
- System.getenv("PATH"));
-
- assertNull("Doesn't return NULL for non existent property",
- System.getenv("nonexistent.property"));
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if(perm.getName().equals("getenv.PATH")) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
-
- try {
- System.getenv("PATH");
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- try {
- System.getenv(null);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "load",
- args = {java.lang.String.class}
- )
- public void test_load() {
- try {
- new TestLibrary().checkString();
- fail("UnsatisfiedLinkError was not thrown.");
- } catch(UnsatisfiedLinkError e) {
- //expected
- }
-
- try {
- System.load("nonExistentLibrary");
- fail("UnsatisfiedLinkError was not thrown.");
- } catch(UnsatisfiedLinkError ule) {
- //expected
- }
-
- try {
- System.load(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
-
- }
-
- public void checkLink(String lib) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- System.load("libTestLibrary.so");
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "loadLibrary",
- args = {java.lang.String.class}
- )
- public void test_loadLibrary() {
-
- try {
- System.loadLibrary("nonExistentLibrary");
- fail("UnsatisfiedLinkError was not thrown.");
- } catch(UnsatisfiedLinkError ule) {
- //expected
- }
-
- try {
- System.loadLibrary(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkLink(String lib) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- System.loadLibrary("libTestLibrary.so");
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "mapLibraryName",
- args = {java.lang.String.class}
- )
- public void test_mapLibraryName() {
- assertEquals("libname.so", System.mapLibraryName("name"));
-
- try {
- System.mapLibraryName(null);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nanoTime",
- args = {}
- )
- public void test_nanoTime() {
- long sleepTime = 5000;
- long beginTime = System.nanoTime();
- try {
- Thread.sleep(sleepTime);
- } catch(Exception e) {
- fail("Unknown exception was thrown.");
- }
- long endTime = System.nanoTime();
- assertTrue((endTime - beginTime) > sleepTime * 1000000);
- }
-
- @Override
- protected void setUp() {
- flag = false;
- ranFinalize = false;
- }
-
- protected SystemTest createInstance() {
- return new SystemTest("FT");
- }
-
- @Override
- protected void finalize() {
- if (flag)
- ranFinalize = true;
- }
-
- public SystemTest() {
- }
-
- public SystemTest(String name) {
- super(name);
- }
-
- private class MockSecurityManager extends SecurityManager {
- @Override
- public void checkPermission(Permission perm) {
- if (perm.equals(new RuntimePermission("inheritedChannel")))
- throw new SecurityException("Incorrect permission");
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestAnnotation.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestAnnotation.java
deleted file mode 100644
index 45d16ad..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestAnnotation.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-
-@Retention(RetentionPolicy.RUNTIME)
-public @interface TestAnnotation {
- String value();
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestAssertions.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestAssertions.java
deleted file mode 100644
index 12bb964..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestAssertions.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-public class TestAssertions {
- boolean isTrue = false;
-
- TestAssertions() {
-
- }
-
- public void test() throws AssertionError {
- assert (isTrue == true);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestAssertions1.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestAssertions1.java
deleted file mode 100644
index 73bbfa7..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestAssertions1.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-public class TestAssertions1 {
- boolean isTrue = true;
-
- TestAssertions1() {
-
- }
-
- public void test() throws AssertionError {
- assert (isTrue == false);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass1.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass1.java
deleted file mode 100644
index d47adc0..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass1.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-public class TestClass1 {
- static TestClass2 tc = new TestClass2(0);
-
- TestClass1() {
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass1B.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass1B.java
deleted file mode 100644
index e87cf3d..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass1B.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-public class TestClass1B {
- static TestClass2 tc = new TestClass2(0);
-
- TestClass1B() {
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass1C.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass1C.java
deleted file mode 100644
index d1adb03..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass1C.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-public class TestClass1C {
- static TestClass2 tc = new TestClass2(0);
-
- TestClass1C() {
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass2.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass2.java
deleted file mode 100644
index a44e4d5..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass2.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-public class TestClass2 {
-
- public TestClass2(int i) throws IllegalArgumentException {
- throw new IllegalArgumentException();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass3.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass3.java
deleted file mode 100644
index 21ebb38..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass3.java
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-public class TestClass3 {
- private TestClass3() {}
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass4.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass4.java
deleted file mode 100644
index e69de29..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestClass4.java
+++ /dev/null
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestLibrary.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestLibrary.java
deleted file mode 100644
index 2748223..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TestLibrary.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-class TestLibrary {
- private native String printName();
-
- boolean checkString() {
- if(printName().equals("TestLibrary"))
- return true;
- return false;
- }
-
- TestLibrary() {
- InputStream in = TestLibrary.class.getResourceAsStream("/libTestLibrary.so");
- try {
- File tmp = File.createTempFile("libTestLibrary", "so");
- tmp.deleteOnExit();
- FileOutputStream out = new FileOutputStream(tmp);
- while (in.available() > 0) {
- out.write(in.read()); // slow
- }
- in.close();
- out.close();
- Runtime.getRuntime().load(tmp.getAbsolutePath());
- } catch (FileNotFoundException e) {
- } catch (IOException e) {
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadDeathTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadDeathTest.java
deleted file mode 100644
index abb52c1..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadDeathTest.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(ThreadDeath.class)
-public class ThreadDeathTest extends junit.framework.TestCase {
-
- /**
- * @tests java.lang.ThreadDeath#ThreadDeath()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ThreadDeath",
- args = {}
- )
- public void test_Constructor() {
- ThreadDeath td = new ThreadDeath();
- assertNull(td.getCause());
- assertNull(td.getMessage());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadGroupTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadGroupTest.java
deleted file mode 100644
index 7e8030a..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadGroupTest.java
+++ /dev/null
@@ -1,1920 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.security.Permission;
-import java.util.Vector;
-
-@TestTargetClass(ThreadGroup.class)
-public class ThreadGroupTest extends junit.framework.TestCase implements Thread.UncaughtExceptionHandler {
-
- class MyThread extends Thread {
- public volatile int heartBeat = 0;
-
- public MyThread(ThreadGroup group, String name)
- throws SecurityException, IllegalThreadStateException {
- super(group, name);
- }
-
- @Override
- public void run() {
- while (true) {
- heartBeat++;
- try {
- Thread.sleep(50);
- } catch (InterruptedException e) {
- break;
- }
- }
- }
-
- public boolean isActivelyRunning() {
- long MAX_WAIT = 100;
- return isActivelyRunning(MAX_WAIT);
- }
-
- public boolean isActivelyRunning(long maxWait) {
- int beat = heartBeat;
- long start = System.currentTimeMillis();
- do {
- Thread.yield();
- int beat2 = heartBeat;
- if (beat != beat2) {
- return true;
- }
- } while (System.currentTimeMillis() - start < maxWait);
- return false;
- }
-
- }
-
- private ThreadGroup rootThreadGroup = null;
-
- private ThreadGroup initialThreadGroup = null;
-
- /**
- * @tests java.lang.ThreadGroup#ThreadGroup(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ThreadGroup",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.lang.ThreadGroup(java.lang.String)
-
- // Unfortunately we have to use other APIs as well as we test the
- // constructor
-
- ThreadGroup newGroup = null;
- ThreadGroup initial = getInitialThreadGroup();
- final String name = "Test name";
- newGroup = new ThreadGroup(name);
- assertTrue(
- "Has to be possible to create a subgroup of current group using simple constructor",
- newGroup.getParent() == initial);
- assertTrue("Name has to be correct", newGroup.getName().equals(name));
-
- // cleanup
- newGroup.destroy();
-
- newGroup = new ThreadGroup("");
- assertEquals("", newGroup.getName());
-
- newGroup = new ThreadGroup(null);
- assertNull(newGroup.getName());
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new ThreadGroup(name);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.ThreadGroup#ThreadGroup(java.lang.ThreadGroup,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ThreadGroup",
- args = {java.lang.ThreadGroup.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_ThreadGroupLjava_lang_String() {
- // Test for method java.lang.ThreadGroup(java.lang.ThreadGroup,
- // java.lang.String)
-
- // Unfortunately we have to use other APIs as well as we test the
- // constructor
-
- ThreadGroup newGroup = null;
-
- try {
- newGroup = new ThreadGroup(null, null);
- } catch (NullPointerException e) {
- }
- assertNull("Can't create a ThreadGroup with a null parent",
- newGroup);
-
- newGroup = new ThreadGroup(getInitialThreadGroup(), null);
- assertTrue("Has to be possible to create a subgroup of current group",
- newGroup.getParent() == Thread.currentThread().getThreadGroup());
-
- // Lets start all over
- newGroup.destroy();
-
- newGroup = new ThreadGroup(getRootThreadGroup(), "a name here");
- assertTrue("Has to be possible to create a subgroup of root group",
- newGroup.getParent() == getRootThreadGroup());
-
- // Lets start all over
- newGroup.destroy();
-
- try {
- newGroup = new ThreadGroup(newGroup, "a name here");
- } catch (IllegalThreadStateException e) {
- newGroup = null;
- }
-
- assertNull("Can't create a subgroup of a destroyed group",
- newGroup);
-
- try {
- new ThreadGroup(null, "name");
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- try {
- new ThreadGroup(newGroup, null);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new ThreadGroup(getRootThreadGroup(), "a name here");
- fail("SecurityException was not thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.ThreadGroup#activeCount()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "activeCount",
- args = {}
- )
- public void test_activeCount() {
- // Test for method int java.lang.ThreadGroup.activeCount()
- ThreadGroup tg = new ThreadGroup("activeCount");
- Thread t1 = new Thread(tg, new Runnable() {
- public void run() {
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- }
- }
- });
- int beforeCount = tg.activeCount();
- t1.start();
- int afterCount = tg.activeCount();
- assertTrue("count of active threads should be increased",
- (afterCount - beforeCount) == 1);
- t1.interrupt();
- try {
- t1.join();
- } catch (InterruptedException e) {
- }
- // cleanup
- tg.destroy();
- }
-
- /**
- * @tests java.lang.ThreadGroup#activeGroupCount()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "activeGroupCount",
- args = {}
- )
- public void test_activeGroupCount() {
-
- ThreadGroup tg = new ThreadGroup("group count");
- assertEquals("Incorrect number of groups",
- 0, tg.activeGroupCount());
- Thread t1 = new Thread(tg, new Runnable() {
- public void run() {
-
- }
- });
- assertEquals("Incorrect number of groups",
- 0, tg.activeGroupCount());
- t1.start();
- assertEquals("Incorrect number of groups",
- 0, tg.activeGroupCount());
- new ThreadGroup(tg, "test group 1");
- assertEquals("Incorrect number of groups",
- 1, tg.activeGroupCount());
- new ThreadGroup(tg, "test group 2");
- assertEquals("Incorrect number of groups",
- 2, tg.activeGroupCount());
- }
-
- /**
- * @tests java.lang.ThreadGroup#allowThreadSuspension(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "allowThreadSuspension",
- args = {boolean.class}
- )
- @SuppressWarnings("deprecation")
- public void test_allowThreadSuspensionZ() {
- ThreadGroup tg = new ThreadGroup("thread suspension");
- assertTrue("Thread suspention can not be changed",
- tg.allowThreadSuspension(false));
- assertTrue("Thread suspention can not be changed",
- tg.allowThreadSuspension(true));
- }
-
- /**
- * @tests java.lang.ThreadGroup#checkAccess()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkAccess",
- args = {}
- )
- public void test_checkAccess() {
- // Test for method void java.lang.ThreadGroup.checkAccess()
-
- final ThreadGroup originalCurrent = getInitialThreadGroup();
- ThreadGroup testRoot = new ThreadGroup(originalCurrent, "Test group");
-
- SecurityManager currentManager = System.getSecurityManager();
- boolean passed = true;
-
- try {
- if (currentManager != null) {
- testRoot.checkAccess();
- }
- } catch (SecurityException se) {
- passed = false;
- }
-
- assertTrue("CheckAccess is no-op with no SecurityManager", passed);
-
- testRoot.destroy();
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- testRoot.checkAccess();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "enumerate",
- args = {java.lang.Thread[].class}
- )
- public void test_enumerateLThreadArray() {
- int numThreads = initialThreadGroup.activeCount();
- Thread[] listOfThreads = new Thread[numThreads];
-
- int countThread = initialThreadGroup.enumerate(listOfThreads);
- assertEquals(numThreads, countThread);
- assertEquals(Thread.currentThread(), listOfThreads[0]);
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- initialThreadGroup.enumerate(listOfThreads);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "enumerate",
- args = {java.lang.Thread[].class, boolean.class}
- )
- public void test_enumerateLThreadArrayLZ() {
- int numThreads = initialThreadGroup.activeCount();
- Thread[] listOfThreads = new Thread[numThreads];
-
- int countThread = initialThreadGroup.enumerate(listOfThreads, false);
- assertEquals(numThreads, countThread);
- assertEquals(Thread.currentThread(), listOfThreads[0]);
-
- countThread = initialThreadGroup.enumerate(listOfThreads, true);
- assertEquals(numThreads, countThread);
- assertEquals(Thread.currentThread(), listOfThreads[0]);
-
- ThreadGroup subGroup = new ThreadGroup(initialThreadGroup, "Test Group 1");
- int subThreadsCount = 3;
- Vector<MyThread> subThreads = populateGroupsWithThreads(subGroup,
- subThreadsCount);
-
- countThread = initialThreadGroup.enumerate(listOfThreads, true);
- assertEquals(numThreads, countThread);
- assertEquals(Thread.currentThread(), listOfThreads[0]);
-
- for(MyThread thr:subThreads) {
- thr.start();
- }
- // lets give them some time to start
- try {
- Thread.sleep(500);
- } catch (InterruptedException ie) {
- fail("Should not be interrupted");
- }
-
- int numThreads2 = initialThreadGroup.activeCount();
- listOfThreads = new Thread[numThreads2];
-
- assertEquals(numThreads + subThreadsCount, numThreads2);
-
- countThread = initialThreadGroup.enumerate(listOfThreads, true);
- assertEquals(numThreads2, countThread);
- assertEquals(Thread.currentThread(), listOfThreads[0]);
-
- for(MyThread thr:subThreads) {
- thr.interrupt();
- }
- // lets give them some time to die
- try {
- Thread.sleep(500);
- } catch (InterruptedException ie) {
- fail("Should not be interrupted");
- }
-
- int numThreads3 = initialThreadGroup.activeCount();
- listOfThreads = new Thread[numThreads3];
-
- assertEquals(numThreads, numThreads3);
-
- countThread = initialThreadGroup.enumerate(listOfThreads, false);
- assertEquals(numThreads3, countThread);
- assertEquals(Thread.currentThread(), listOfThreads[0]);
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- initialThreadGroup.enumerate(listOfThreads, true);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "enumerate",
- args = {java.lang.ThreadGroup[].class}
- )
- public void test_enumerateLThreadGroupArray() {
- int numGroupThreads = initialThreadGroup.activeGroupCount();
- ThreadGroup[] listOfGroups = new ThreadGroup[numGroupThreads];
-
- int countGroupThread = initialThreadGroup.enumerate(listOfGroups);
- assertEquals(numGroupThreads, countGroupThread);
-
- ThreadGroup[] listOfGroups1 = new ThreadGroup[numGroupThreads + 1];
- countGroupThread = initialThreadGroup.enumerate(listOfGroups1);
- assertEquals(numGroupThreads, countGroupThread);
- assertNull(listOfGroups1[listOfGroups1.length - 1]);
-
- ThreadGroup[] listOfGroups2 = new ThreadGroup[numGroupThreads - 1];
- countGroupThread = initialThreadGroup.enumerate(listOfGroups2);
- assertEquals(numGroupThreads - 1, countGroupThread);
-
- ThreadGroup thrGroup1 = new ThreadGroup("Test Group 1");
- countGroupThread = thrGroup1.enumerate(listOfGroups);
- assertEquals(0, countGroupThread);
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- initialThreadGroup.enumerate(listOfGroups);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "enumerate",
- args = {java.lang.ThreadGroup[].class, boolean.class}
- )
- public void test_enumerateLThreadGroupArrayLZ() {
- ThreadGroup thrGroup = new ThreadGroup("Test Group 1");
- Vector<MyThread> subThreads = populateGroupsWithThreads(thrGroup, 3);
- int numGroupThreads = thrGroup.activeGroupCount();
- ThreadGroup[] listOfGroups = new ThreadGroup[numGroupThreads];
-
- assertEquals(0, thrGroup.enumerate(listOfGroups, true));
- assertEquals(0, thrGroup.enumerate(listOfGroups, false));
-
- for(MyThread thr:subThreads) {
- thr.start();
- }
-
- numGroupThreads = thrGroup.activeGroupCount();
- listOfGroups = new ThreadGroup[numGroupThreads];
-
- assertEquals(0, thrGroup.enumerate(listOfGroups, true));
- assertEquals(0, thrGroup.enumerate(listOfGroups, false));
-
- ThreadGroup subGroup1 = new ThreadGroup(thrGroup, "Test Group 2");
- Vector<MyThread> subThreads1 = populateGroupsWithThreads(subGroup1, 3);
- numGroupThreads = thrGroup.activeGroupCount();
- listOfGroups = new ThreadGroup[numGroupThreads];
-
- assertEquals(1, thrGroup.enumerate(listOfGroups, true));
- assertEquals(1, thrGroup.enumerate(listOfGroups, false));
-
- for(MyThread thr:subThreads1) {
- thr.start();
- }
- numGroupThreads = thrGroup.activeGroupCount();
- listOfGroups = new ThreadGroup[numGroupThreads];
-
- assertEquals(1, thrGroup.enumerate(listOfGroups, true));
- assertEquals(1, thrGroup.enumerate(listOfGroups, false));
-
- for(MyThread thr:subThreads) {
- thr.interrupt();
- }
-
- ThreadGroup subGroup2 = new ThreadGroup(subGroup1, "Test Group 3");
- Vector<MyThread> subThreads2 = populateGroupsWithThreads(subGroup2, 3);
- numGroupThreads = thrGroup.activeGroupCount();
- listOfGroups = new ThreadGroup[numGroupThreads];
-
- assertEquals(2, thrGroup.enumerate(listOfGroups, true));
- assertEquals(1, thrGroup.enumerate(listOfGroups, false));
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- thrGroup.enumerate(listOfGroups, true);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.ThreadGroup#destroy()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "destroy",
- args = {}
- )
- public void test_destroy() {
- // Test for method void java.lang.ThreadGroup.destroy()
-
- final ThreadGroup originalCurrent = getInitialThreadGroup();
- ThreadGroup testRoot = new ThreadGroup(originalCurrent, "Test group");
- final int DEPTH = 4;
- final Vector<ThreadGroup> subgroups = buildRandomTreeUnder(testRoot, DEPTH);
-
- // destroy them all
- testRoot.destroy();
-
- for (int i = 0; i < subgroups.size(); i++) {
- ThreadGroup child = subgroups.elementAt(i);
- assertEquals("Destroyed child can't have children", 0, child
- .activeCount());
- boolean passed = false;
- try {
- child.destroy();
- } catch (IllegalThreadStateException e) {
- passed = true;
- }
-
- assertTrue("Destroyed child can't be destroyed again", passed);
- }
-
- testRoot = new ThreadGroup(originalCurrent, "Test group (daemon)");
- testRoot.setDaemon(true);
-
- ThreadGroup child = new ThreadGroup(testRoot, "daemon child");
-
- // If we destroy the last daemon's child, the daemon should get destroyed
- // as well
- child.destroy();
-
- boolean passed = false;
- try {
- child.destroy();
- } catch (IllegalThreadStateException e) {
- passed = true;
- }
-
- assertTrue("Daemon should have been destroyed already", passed);
-
- passed = false;
- try {
- testRoot.destroy();
- } catch (IllegalThreadStateException e) {
- passed = true;
- }
-
- assertTrue("Daemon parent should have been destroyed automatically",
- passed);
-
- assertTrue(
- "Destroyed daemon's child should not be in daemon's list anymore",
- !arrayIncludes(groups(testRoot), child));
- assertTrue("Destroyed daemon should not be in parent's list anymore",
- !arrayIncludes(groups(originalCurrent), testRoot));
-
- testRoot = new ThreadGroup(originalCurrent, "Test group (daemon)");
- testRoot.setDaemon(true);
- Thread noOp = new Thread(testRoot, null, "no-op thread") {
- @Override
- public void run() {
- }
- };
- noOp.start();
-
- // Wait for the no-op thread to run inside daemon ThreadGroup
- try {
- noOp.join();
- } catch (InterruptedException ie) {
- fail("Should not be interrupted");
- }
-
-
- passed = false;
- try {
- child.destroy();
- } catch (IllegalThreadStateException e) {
- passed = true;
- }
-
- assertTrue(
- "Daemon group should have been destroyed already when last thread died",
- passed);
-
- testRoot = new ThreadGroup(originalCurrent, "Test group (daemon)");
- noOp = new Thread(testRoot, null, "no-op thread") {
- @Override
- public void run() {
- try {
- Thread.sleep(500);
- } catch (InterruptedException ie) {
- fail("Should not be interrupted");
- }
- }
- };
-
- // Has to execute the next lines in an interval < the sleep interval of
- // the no-op thread
- noOp.start();
- passed = false;
- try {
- testRoot.destroy();
- } catch (IllegalThreadStateException its) {
- passed = true;
- }
- assertTrue("Can't destroy a ThreadGroup that has threads", passed);
-
- // But after the thread dies, we have to be able to destroy the thread
- // group
- try {
- noOp.join();
- } catch (InterruptedException ie) {
- fail("Should not be interrupted");
- }
-
- passed = true;
- try {
- testRoot.destroy();
- } catch (IllegalThreadStateException its) {
- passed = false;
- }
- assertTrue(
- "Should be able to destroy a ThreadGroup that has no threads",
- passed);
-
- ThreadGroup tg = new ThreadGroup("ThreadGroup");
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- originalCurrent.destroy();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.ThreadGroup#destroy()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies IllegalThreadStateException.",
- method = "destroy",
- args = {}
- )
- public void test_destroy_subtest0() {
- ThreadGroup group1 = new ThreadGroup("test_destroy_subtest0");
- group1.destroy();
- try {
- new Thread(group1, "test_destroy_subtest0");
- fail("should throw IllegalThreadStateException");
- } catch (IllegalThreadStateException e) {
- }
- }
-
- /**
- * @tests java.lang.ThreadGroup#getMaxPriority()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMaxPriority",
- args = {}
- )
- public void test_getMaxPriority() {
- // Test for method int java.lang.ThreadGroup.getMaxPriority()
- final ThreadGroup originalCurrent = getInitialThreadGroup();
- ThreadGroup testRoot = new ThreadGroup(originalCurrent, "Test group");
-
- boolean passed = true;
- try {
- testRoot.setMaxPriority(Thread.MIN_PRIORITY);
- } catch (IllegalArgumentException iae) {
- passed = false;
- }
- assertTrue("Should be able to set priority", passed);
-
- assertTrue("New value should be the same as we set", testRoot
- .getMaxPriority() == Thread.MIN_PRIORITY);
-
- testRoot.destroy();
-
- }
-
- /**
- * @tests java.lang.ThreadGroup#getName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getName",
- args = {}
- )
- public void test_getName() {
- // Test for method java.lang.String java.lang.ThreadGroup.getName()
- final ThreadGroup originalCurrent = getInitialThreadGroup();
- final String name = "Test group";
- final ThreadGroup testRoot = new ThreadGroup(originalCurrent, name);
-
- assertTrue("Setting a name&getting does not work", testRoot.getName()
- .equals(name));
-
- testRoot.destroy();
-
- }
-
- /**
- * @tests java.lang.ThreadGroup#getParent()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getParent",
- args = {}
- )
- public void test_getParent() {
- // Test for method java.lang.ThreadGroup
- // java.lang.ThreadGroup.getParent()
- final ThreadGroup originalCurrent = getInitialThreadGroup();
- ThreadGroup testRoot = new ThreadGroup(originalCurrent, "Test group");
-
- assertTrue("Parent is wrong", testRoot.getParent() == originalCurrent);
-
- // Create some groups, nested some levels.
- final int TOTAL_DEPTH = 5;
- ThreadGroup current = testRoot;
- Vector<ThreadGroup> groups = new Vector<ThreadGroup>();
- // To maintain the invariant that a thread in the Vector is parent
- // of the next one in the collection (and child of the previous one)
- groups.addElement(testRoot);
-
- for (int i = 0; i < TOTAL_DEPTH; i++) {
- current = new ThreadGroup(current, "level " + i);
- groups.addElement(current);
- }
-
- // Now we walk the levels down, checking if parent is ok
- for (int i = 1; i < groups.size(); i++) {
- current = groups.elementAt(i);
- ThreadGroup previous = groups.elementAt(i - 1);
- assertTrue("Parent is wrong", current.getParent() == previous);
- }
-
- final ThreadGroup[] checkAccessGroup = new ThreadGroup[1];
- class SecurityManagerImpl extends MutableSecurityManager {
- @Override
- public void checkAccess(ThreadGroup group) {
- checkAccessGroup[0] = group;
- }
- }
- SecurityManagerImpl sm = new SecurityManagerImpl();
- //add permission to allow reset of security manager
- sm.addPermission(MutableSecurityManager.SET_SECURITY_MANAGER);
-
- ThreadGroup parent;
- try {
- // To see if it checks Thread creation with our SecurityManager
- System.setSecurityManager(sm);
- parent = testRoot.getParent();
- } finally {
- // restore original, no side-effects
- System.setSecurityManager(null);
- }
- assertTrue("checkAccess with incorrect group",
- checkAccessGroup[0] == parent);
-
- testRoot.destroy();
- }
-
- /**
- * @tests java.lang.ThreadGroup#interrupt()
- */
- private static boolean interrupted = false;
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "interrupt",
- args = {}
- )
- public void test_interrupt() {
-
- Thread.setDefaultUncaughtExceptionHandler(this);
- ThreadGroup tg = new ThreadGroup("interrupt");
- Thread t1 = new Thread(tg, new Runnable() {
- public void run() {
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- fail("ok");
- }
- }
- });
- assertFalse("Incorrect state of thread", interrupted);
- t1.start();
- assertFalse("Incorrect state of thread", interrupted);
- t1.interrupt();
- try {
- t1.join();
- } catch (InterruptedException e) {
- }
- assertTrue("Incorrect state of thread", interrupted);
- tg.destroy();
-
- ThreadGroup threadGroup = new ThreadGroup("securityCheck");
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- threadGroup.interrupt();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.ThreadGroup#isDaemon()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isDaemon",
- args = {}
- )
- public void test_isDaemon() {
- // Test for method boolean java.lang.ThreadGroup.isDaemon()
- daemonTests();
- }
-
- /**
- * @tests java.lang.ThreadGroup#isDestroyed()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isDestroyed",
- args = {}
- )
- public void test_isDestroyed() {
- final ThreadGroup originalCurrent = getInitialThreadGroup();
- final ThreadGroup testRoot = new ThreadGroup(originalCurrent,
- "Test group");
- assertFalse("Test group is not destroyed yet",
- testRoot.isDestroyed());
- testRoot.destroy();
- assertTrue("Test group already destroyed",
- testRoot.isDestroyed());
- }
-
- /**
- * @tests java.lang.ThreadGroup#list()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "list",
- args = {}
- )
- public void test_list() {
- // Test for method void java.lang.ThreadGroup.list()
-
- final ThreadGroup originalCurrent = getInitialThreadGroup();
- // wipeSideEffectThreads destroy all side effect of threads created in
- // java.lang.Thread
- boolean result = wipeSideEffectThreads(originalCurrent);
- if (result == false) {
- fail("wipe threads in test_list() not successful");
- }
- final ThreadGroup testRoot = new ThreadGroup(originalCurrent,
- "Test group");
-
- // First save the original System.out
- java.io.PrintStream originalOut = System.out;
-
- try {
- java.io.ByteArrayOutputStream contentsStream = new java.io.ByteArrayOutputStream(
- 100);
- java.io.PrintStream newOut = new java.io.PrintStream(contentsStream);
-
- // We have to "redirect" System.out to test the method 'list'
- System.setOut(newOut);
-
- originalCurrent.list();
-
- /*
- * The output has to look like this
- *
- * java.lang.ThreadGroup[name=main,maxpri=10] Thread[main,5,main]
- * java.lang.ThreadGroup[name=Test group,maxpri=10]
- *
- */
-
- String contents = new String(contentsStream.toByteArray());
- boolean passed = (contents.indexOf("ThreadGroup[name=main") != -1) &&
- (contents.indexOf("Thread[") != -1) &&
- (contents.indexOf("ThreadGroup[name=Test group") != -1);
- assertTrue("'list()' does not print expected contents. "
- + "Result from list: "
- + contents, passed);
- // Do proper cleanup
- testRoot.destroy();
-
- } finally {
- // No matter what, we need to restore the original System.out
- System.setOut(originalOut);
- }
-
- }
-
- /**
- * @tests java.lang.ThreadGroup#parentOf(java.lang.ThreadGroup)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "parentOf",
- args = {java.lang.ThreadGroup.class}
- )
- public void test_parentOfLjava_lang_ThreadGroup() {
- // Test for method boolean
- // java.lang.ThreadGroup.parentOf(java.lang.ThreadGroup)
- final ThreadGroup originalCurrent = getInitialThreadGroup();
- final ThreadGroup testRoot = new ThreadGroup(originalCurrent,
- "Test group");
- final int DEPTH = 4;
- buildRandomTreeUnder(testRoot, DEPTH);
-
- final ThreadGroup[] allChildren = allGroups(testRoot);
- for (ThreadGroup element : allChildren) {
- assertTrue("Have to be parentOf all children", testRoot
- .parentOf(element));
- }
-
- assertTrue("Have to be parentOf itself", testRoot.parentOf(testRoot));
-
- testRoot.destroy();
- assertTrue("Parent can't have test group as subgroup anymore",
- !arrayIncludes(groups(testRoot.getParent()), testRoot));
-
- try {
- System.setSecurityManager(new MutableSecurityManager(MutableSecurityManager.SET_SECURITY_MANAGER));
- assertTrue("Should not be parent", !testRoot
- .parentOf(originalCurrent));
- } finally {
- System.setSecurityManager(null);
- }
- }
-
- /**
- * @tests java.lang.ThreadGroup#resume()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "resume",
- args = {}
- )
- @SuppressWarnings("deprecation")
- @AndroidOnly("Thread.resume is implemented on some RI")
- public void test_resume() throws OutOfMemoryError {
- // Test for method void java.lang.ThreadGroup.resume()
- final ThreadGroup originalCurrent = getInitialThreadGroup();
-
- final ThreadGroup testRoot = new ThreadGroup(originalCurrent,
- "Test group");
- final int DEPTH = 2;
- buildRandomTreeUnder(testRoot, DEPTH);
-
- final int THREADS_PER_GROUP = 2;
- final Vector<MyThread> threads = populateGroupsWithThreads(testRoot,
- THREADS_PER_GROUP);
- try {
- for (int i = 0; i < threads.size(); i++) {
- Thread t = threads.elementAt(i);
- t.start();
- }
- } catch (OutOfMemoryError e) {
- for (int i = 0; i < threads.size(); i++) {
- Thread t = threads.elementAt(i);
- t.interrupt();
- }
- throw e;
- }
-
- try {
- testRoot.resume();
- fail("Thread.resume() is not supported and throws an UOE on Android.");
- } catch (UnsupportedOperationException e) {
- // expected
- }
-
-
- for (int i = 0; i < threads.size(); i++) {
- MyThread t = threads.elementAt(i);
- t.interrupt();
- }
-
- // Make sure we do cleanup before returning
- testRoot.destroy();
-
- assertEquals("Method destroy must have problems",
- 0, testRoot.activeCount());
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- originalCurrent.resume();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.ThreadGroup#setDaemon(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setDaemon",
- args = {boolean.class}
- )
- public void test_setDaemonZ() {
- // Test for method void java.lang.ThreadGroup.setDaemon(boolean)
- daemonTests();
-
- final ThreadGroup testRoot = new ThreadGroup("Test group");
-
- testRoot.setDaemon(true);
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
-
- try {
- new ThreadGroup("");
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.ThreadGroup#setMaxPriority(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setMaxPriority",
- args = {int.class}
- )
- public void test_setMaxPriorityI() {
- // Test for method void java.lang.ThreadGroup.setMaxPriority(int)
- final ThreadGroup originalCurrent = getInitialThreadGroup();
- ThreadGroup testRoot = new ThreadGroup(originalCurrent, "Test group");
-
- boolean passed;
-
- // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- int currentMax = testRoot.getMaxPriority();
- testRoot.setMaxPriority(Thread.MAX_PRIORITY + 1);
- passed = testRoot.getMaxPriority() == currentMax;
- assertTrue(
- "setMaxPriority: Any value higher than the current one is ignored. Before: "
- + currentMax + " , after: " + testRoot.getMaxPriority(),
- passed);
-
- // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- currentMax = testRoot.getMaxPriority();
- testRoot.setMaxPriority(Thread.MIN_PRIORITY - 1);
- passed = testRoot.getMaxPriority() == Thread.MIN_PRIORITY;
- assertTrue(
- "setMaxPriority: Any value smaller than MIN_PRIORITY is adjusted to MIN_PRIORITY. Before: "
- + currentMax + " , after: " + testRoot.getMaxPriority(),
- passed);
-
- // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- testRoot.destroy();
- testRoot = new ThreadGroup(originalCurrent, "Test group");
-
- // Create some groups, nested some levels. Each level will have maxPrio
- // 1 unit smaller than the parent's. However, there can't be a group
- // with priority < Thread.MIN_PRIORITY
- final int TOTAL_DEPTH = testRoot.getMaxPriority() - Thread.MIN_PRIORITY
- - 2;
- ThreadGroup current = testRoot;
- for (int i = 0; i < TOTAL_DEPTH; i++) {
- current = new ThreadGroup(current, "level " + i);
- }
-
- // Now we walk the levels down, changing the maxPrio and later verifying
- // that the value is indeed 1 unit smaller than the parent's maxPrio.
- int maxPrio, parentMaxPrio;
- current = testRoot;
-
- // To maintain the invariant that when we are to modify a child,
- // its maxPriority is always 1 unit smaller than its parent's.
- // We have to set it for the root manually, and the loop does the rest
- // for all the other sub-levels
- current.setMaxPriority(current.getParent().getMaxPriority() - 1);
-
- for (int i = 0; i < TOTAL_DEPTH; i++) {
- maxPrio = current.getMaxPriority();
- parentMaxPrio = current.getParent().getMaxPriority();
-
- ThreadGroup[] children = groups(current);
- assertEquals("Can only have 1 subgroup", 1, children.length);
- current = children[0];
- assertTrue(
- "Had to be 1 unit smaller than parent's priority in iteration="
- + i + " checking->" + current,
- maxPrio == parentMaxPrio - 1);
- current.setMaxPriority(maxPrio - 1);
-
- // The next test is sort of redundant, since in next iteration it
- // will be the parent tGroup, so the test will be done.
- assertTrue("Had to be possible to change max priority", current
- .getMaxPriority() == maxPrio - 1);
- }
-
- assertTrue(
- "Priority of leaf child group has to be much smaller than original root group",
- current.getMaxPriority() == testRoot.getMaxPriority()
- - TOTAL_DEPTH);
-
- testRoot.destroy();
-
- // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- passed = true;
- testRoot = new ThreadGroup(originalCurrent, "Test group");
- try {
- testRoot.setMaxPriority(Thread.MAX_PRIORITY);
- } catch (IllegalArgumentException iae) {
- passed = false;
- }
- assertTrue(
- "Max Priority = Thread.MAX_PRIORITY should be possible if the test is run with default system ThreadGroup as root",
- passed);
- testRoot.destroy();
-
- // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- passed = true;
- testRoot = new ThreadGroup(originalCurrent, "Test group");
- System.setSecurityManager(new MutableSecurityManager(MutableSecurityManager.SET_SECURITY_MANAGER));
- try {
- try {
- testRoot.setMaxPriority(Thread.MIN_PRIORITY);
- } catch (IllegalArgumentException iae) {
- passed = false;
- }
- } finally {
- System.setSecurityManager(null);
- }
- assertTrue(
- "Min Priority = Thread.MIN_PRIORITY should be possible, always",
- passed);
- testRoot.destroy();
-
- try {
- System.setSecurityManager(new MutableSecurityManager(MutableSecurityManager.SET_SECURITY_MANAGER));
- originalCurrent.setMaxPriority(Thread.MAX_PRIORITY);
- } finally {
- System.setSecurityManager(null);
- }
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
-
- try {
- testRoot.setMaxPriority(Thread.MAX_PRIORITY);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.ThreadGroup#stop()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "stop",
- args = {}
- )
- @AndroidOnly("stop() method not implemented. throws UnsupportedOperationException.")
- @SuppressWarnings("deprecation")
- public void test_stop() throws OutOfMemoryError {
- // Test for method void java.lang.ThreadGroup.stop()
- final ThreadGroup originalCurrent = getInitialThreadGroup();
-
- final ThreadGroup testRoot = new ThreadGroup(originalCurrent,
- "Test group");
- final int DEPTH = 2;
- buildRandomTreeUnder(testRoot, DEPTH);
-
- final int THREADS_PER_GROUP = 2;
- final Vector<MyThread> threads = populateGroupsWithThreads(testRoot,
- THREADS_PER_GROUP);
-
- try {
- for (int i = 0; i < threads.size(); i++) {
- Thread t = threads.elementAt(i);
- t.start();
- }
- } catch (OutOfMemoryError e) {
- for (int i = 0; i < threads.size(); i++) {
- Thread t = threads.elementAt(i);
- t.interrupt();
- }
- throw e;
- }
-
- // Now that they are all running, let's stop the ThreadGroup
- try {
- testRoot.stop();
- fail("Thread.stop() is not supported and throws an UOE on Android.");
- } catch (UnsupportedOperationException e) {
- // expected
- }
-
- for (int i = 0; i < threads.size(); i++) {
- Thread t = threads.elementAt(i);
- t.interrupt();
- }
-
- // To make sure that even if we fail, we exit in a clean state
- testRoot.destroy();
-
- assertEquals("Method destroy (or wipeAllThreads) must have problems",
- 0, testRoot.activeCount());
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
-
- try {
- originalCurrent.stop();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.ThreadGroup#suspend()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "suspend",
- args = {}
- )
- @AndroidOnly("suspend() method not implemented. throws UnsupportedOperationException.")
- @SuppressWarnings("deprecation")
- public void test_suspend() throws OutOfMemoryError {
- // Test for method void java.lang.ThreadGroup.suspend()
- final ThreadGroup originalCurrent = getInitialThreadGroup();
-
- final ThreadGroup testRoot = new ThreadGroup(originalCurrent,
- "Test group");
- final int DEPTH = 2;
- buildRandomTreeUnder(testRoot, DEPTH);
-
- final int THREADS_PER_GROUP = 2;
- final Vector<MyThread> threads = populateGroupsWithThreads(testRoot,
- THREADS_PER_GROUP);
-
- try {
- for (int i = 0; i < threads.size(); i++) {
- Thread t = threads.elementAt(i);
- t.start();
- }
- } catch (OutOfMemoryError e) {
- for (int i = 0; i < threads.size(); i++) {
- Thread t = threads.elementAt(i);
- t.interrupt();
- }
- throw e;
- }
-
- try {
- testRoot.suspend();
- fail("Thread.suspend() is not supported and throws an UOE on Android.");
- } catch (UnsupportedOperationException e) {
- // expected
- }
-
- for (int i = 0; i < threads.size(); i++) {
- Thread t = threads.elementAt(i);
- t.interrupt();
- }
- // Make sure we cleanup before returning from the method
- testRoot.destroy();
-
- assertEquals("Method destroy (or wipeAllThreads) must have problems",
- 0, testRoot.activeCount());
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- originalCurrent.suspend();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.ThreadGroup#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.lang.ThreadGroup.toString()
- final ThreadGroup originalCurrent = getInitialThreadGroup();
- final String tGroupName = "Test group";
-
- // Our own subclass
- class MyThreadGroup extends ThreadGroup {
- // Have to define a constructor since there's no default one
- public MyThreadGroup(ThreadGroup parent, String name) {
- super(parent, name);
- }
- }
- ;
-
- ThreadGroup testRoot = new MyThreadGroup(originalCurrent, tGroupName);
- final String toString = testRoot.toString();
-
- StringBuffer expectedResult = new StringBuffer();
- expectedResult.append(testRoot.getClass().getName());
- expectedResult.append("[name=");
- expectedResult.append(tGroupName);
- expectedResult.append(",maxpri=");
- expectedResult.append(testRoot.getMaxPriority());
- expectedResult.append("]");
-
- String expectedValue = expectedResult.toString();
-
- assertTrue("toString does not follow the Java language spec.", toString
- .equals(expectedValue));
-
- testRoot.destroy();
- }
-
- /**
- * @tests java.lang.ThreadGroup#uncaughtException(java.lang.Thread,
- * java.lang.Throwable)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "uncaughtException",
- args = {java.lang.Thread.class, java.lang.Throwable.class}
- )
- @SuppressWarnings("deprecation")
- public void test_uncaughtExceptionLjava_lang_ThreadLjava_lang_Throwable() {
- // Test for method void
- // java.lang.ThreadGroup.uncaughtException(java.lang.Thread,
- // java.lang.Throwable)
-
- final ThreadGroup originalCurrent = getInitialThreadGroup();
-
- // indices for the array defined below
- final int TEST_DEATH = 0;
- final int TEST_OTHER = 1;
- final int TEST_EXCEPTION_IN_UNCAUGHT = 2;
- final int TEST_OTHER_THEN_DEATH = 3;
- final int TEST_FORCING_THROW_THREAD_DEATH = 4;
- final int TEST_KILLING = 5;
- final int TEST_DEATH_AFTER_UNCAUGHT = 6;
-
- final boolean[] passed = new boolean[] { false, false, false, false,
- false, false, false };
-
- ThreadGroup testRoot;
- Thread thread;
-
- // Our own exception class
- class TestException extends RuntimeException {
- private static final long serialVersionUID = 1L;
- }
-
- // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- // - - - - - - -
- testRoot = new ThreadGroup(originalCurrent,
- "Test Forcing a throw of ThreadDeath") {
- @Override
- public void uncaughtException(Thread t, Throwable e) {
- if (e instanceof ThreadDeath) {
- passed[TEST_FORCING_THROW_THREAD_DEATH] = true;
- }
- // always forward, any exception
- super.uncaughtException(t, e);
- }
- };
-
- // Test if a Thread tells its ThreadGroup about ThreadDeath
- thread = new Thread(testRoot, null, "suicidal thread") {
- @Override
- public void run() {
- throw new ThreadDeath();
- }
- };
- thread.start();
- try {
- thread.join();
- } catch (InterruptedException ie) {
- fail("Should not have been interrupted");
- }
- testRoot.destroy();
- assertTrue(
- "Any thread should notify its ThreadGroup about its own death, even if suicide:"
- + testRoot, passed[TEST_FORCING_THROW_THREAD_DEATH]);
- // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- // - - - - - - -
-
- testRoot = new ThreadGroup(originalCurrent, "Test ThreadDeath") {
- @Override
- public void uncaughtException(Thread t, Throwable e) {
- passed[TEST_DEATH] = false;
- // always forward, any exception
- super.uncaughtException(t, e);
- }
- };
-
- // Test if a Thread tells its ThreadGroup about ThreadDeath
- passed[TEST_DEATH] = true;
- thread = new Thread(testRoot, null, "no-op thread");
- thread.start();
- try {
- thread.join();
- } catch (InterruptedException ie) {
- fail("Should not have been interrupted");
- }
- testRoot.destroy();
- assertTrue("A thread should not call uncaughtException when it dies:"
- + testRoot, passed[TEST_DEATH]);
- // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- // - - - - - - -
-
- testRoot = new ThreadGroup(originalCurrent, "Test other Exception") {
- @Override
- public void uncaughtException(Thread t, Throwable e) {
- if (e instanceof TestException) {
- passed[TEST_OTHER] = true;
- } else {
- // only forward exceptions other than our test
- super.uncaughtException(t, e);
- }
- }
- };
-
- // Test if a Thread tells its ThreadGroup about an Exception
- thread = new Thread(testRoot, null, "no-op thread") {
- @Override
- public void run() {
- throw new TestException();
- }
- };
- thread.start();
- try {
- thread.join();
- } catch (InterruptedException ie) {
- fail("Should not have been interrupted");
- }
- testRoot.destroy();
- assertTrue(
- "Any thread should notify its ThreadGroup about an uncaught exception:"
- + testRoot, passed[TEST_OTHER]);
- // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- // - - - - - - -
-
- // Our own uncaught exception class
- class UncaughtException extends TestException {
- private static final long serialVersionUID = 1L;
- }
-
- testRoot = new ThreadGroup(originalCurrent,
- "Test Exception in uncaught exception") {
- @Override
- public void uncaughtException(Thread t, Throwable e) {
- if (e instanceof TestException) {
- passed[TEST_EXCEPTION_IN_UNCAUGHT] = true;
- // Let's simulate an error inside our uncaughtException
- // method.
- // This should be no-op according to the spec
- throw new UncaughtException();
- }
- // only forward exceptions other than our test
- super.uncaughtException(t, e);
- }
- };
-
- // Test if an Exception in uncaughtException is really a no-op
- thread = new Thread(testRoot, null, "no-op thread") {
- @Override
- public void run() {
- try {
- throw new TestException();
- } catch (UncaughtException ue) {
- // any exception in my ThreadGroup's uncaughtException must
- // not be propagated.
- // If it gets propagated and we detected that, the test failed
- passed[TEST_EXCEPTION_IN_UNCAUGHT] = false;
- }
- }
- };
- thread.start();
- try {
- thread.join();
- } catch (InterruptedException ie) {
- fail("Should not have been interrupted");
- }
- testRoot.destroy();
- assertTrue(
- "Any uncaughtException in uncaughtException should be no-op:"
- + testRoot, passed[TEST_EXCEPTION_IN_UNCAUGHT]);
- // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- // - - - - - - -
-
- // This is a mix of 2 of the tests above. It is assumed that ThreadDeath
- // and any random exception do work , tested separately. Now we test
- // if after an uncaughtException is forwarded to the ThreadGroup and
- // the Thread dies, if ThreadDeath is also forwarded. It should be
- // (so that a ThreadGroup can know its Thread died)
- testRoot = new ThreadGroup(originalCurrent,
- "Test Uncaught followed by ThreadDeath") {
- @Override
- public void uncaughtException(Thread t, Throwable e) {
- if (e instanceof ThreadDeath) {
- passed[TEST_DEATH_AFTER_UNCAUGHT] = true;
- }
- if (e instanceof TestException) {
- passed[TEST_OTHER_THEN_DEATH] = true;
- } else {
- // only forward exceptions other than our test
- super.uncaughtException(t, e);
- }
- }
- };
-
- // Test if a Thread tells its ThreadGroup about an Exception and also
- // ThreadDeath
- thread = new Thread(testRoot, null, "no-op thread") {
- @Override
- public void run() {
- throw new TestException();
- }
- };
- thread.start();
- try {
- thread.join();
- } catch (InterruptedException ie) {
- fail("Should not have been interrupted");
- }
- testRoot.destroy();
- }
-
- /*
- * @see java.lang.Thread.UncaughtExceptionHandler#uncaughtException(java.lang.Thread, java.lang.Throwable)
- */
- public void uncaughtException(Thread t, Throwable e) {
- interrupted = true;
- Thread.setDefaultUncaughtExceptionHandler(null);
- }
-
- @Override
- protected void setUp() {
- initialThreadGroup = Thread.currentThread().getThreadGroup();
- rootThreadGroup = initialThreadGroup;
- while (rootThreadGroup.getParent() != null) {
- rootThreadGroup = rootThreadGroup.getParent();
- }
- }
-
- @Override
- protected void tearDown() {
- try {
- // Give the threads a chance to die.
- Thread.sleep(50);
- } catch (InterruptedException e) {
- }
- }
-
- private Thread[] threads(ThreadGroup parent) {
- // No API to get the count of immediate children only ?
- int count = parent.activeCount();
- Thread[] all = new Thread[count];
- int actualSize = parent.enumerate(all, false);
- Thread[] result;
- if (actualSize == all.length) {
- result = all;
- } else {
- result = new Thread[actualSize];
- System.arraycopy(all, 0, result, 0, actualSize);
- }
-
- return result;
-
- }
-
- private ThreadGroup getInitialThreadGroup() {
- return initialThreadGroup;
- }
-
- private ThreadGroup[] allGroups(ThreadGroup parent) {
- int count = parent.activeGroupCount();
- ThreadGroup[] all = new ThreadGroup[count];
- parent.enumerate(all, true);
- return all;
- }
-
- private void daemonTests() {
- // Test for method void java.lang.ThreadGroup.setDaemon(boolean)
-
- final ThreadGroup originalCurrent = getInitialThreadGroup();
- final ThreadGroup testRoot = new ThreadGroup(originalCurrent,
- "Test group");
-
- testRoot.setDaemon(true);
- assertTrue("Setting daemon&getting does not work", testRoot.isDaemon());
-
- testRoot.setDaemon(false);
- assertTrue("Setting daemon&getting does not work", !testRoot.isDaemon());
-
- testRoot.destroy();
- }
-
- private boolean wipeAllThreads(final ThreadGroup aGroup) {
- boolean ok = true;
- Thread[] threads = threads(aGroup);
- for (Thread t : threads) {
- ok = ok && wipeThread(t);
- }
-
- // Recursively for subgroups (if any)
- ThreadGroup[] children = groups(aGroup);
- for (ThreadGroup element : children) {
- ok = ok && wipeAllThreads(element);
- }
- return ok;
- }
-
- private boolean wipeSideEffectThreads(ThreadGroup aGroup) {
- boolean ok = true;
- Thread[] threads = threads(aGroup);
- for (Thread t : threads) {
- if (t.getName().equals("SimpleThread")
- || t.getName().equals("Bogus Name")
- || t.getName().equals("Testing")
- || t.getName().equals("foo")
- || t.getName().equals("Test Group")
- || t.getName().equals("Squawk")
- || t.getName().equals("Thread-1")
- || t.getName().equals("firstOne")
- || t.getName().equals("secondOne")
- || t.getName().equals("Thread-16")
- || t.getName().equals("Thread-14")) {
- ok = ok && wipeThread(t);
- }
- }
-
- // Recursively for subgroups (if any)
- ThreadGroup[] children = groups(aGroup);
-
- for (ThreadGroup element : children) {
- ok = ok && wipeSideEffectThreads(element);
- if(element.getName() != null) {
- if (element.getName().equals("Test Group")
- || element.getName().equals("foo")
- || element.getName().equals("jp")) {
- element.destroy();
- }
- }
- }
- try {
- // Give the threads a chance to die.
- Thread.sleep(50);
- } catch (InterruptedException e) {
- }
- return ok;
- }
-
- private void asyncBuildRandomTreeUnder(final ThreadGroup aGroup,
- final int depth, final Vector<ThreadGroup> allCreated) {
- if (depth <= 0) {
- return;
- }
-
- final int maxImmediateSubgroups = random(3);
- for (int i = 0; i < maxImmediateSubgroups; i++) {
- final int iClone = i;
- final String name = " Depth = " + depth + ",N = " + iClone
- + ",Vector size at creation: " + allCreated.size();
- // Use concurrency to maximize chance of exposing concurrency bugs
- // in ThreadGroups
- Thread t = new Thread(aGroup, name) {
- @Override
- public void run() {
- ThreadGroup newGroup = new ThreadGroup(aGroup, name);
- allCreated.addElement(newGroup);
- asyncBuildRandomTreeUnder(newGroup, depth - 1, allCreated);
- }
- };
- t.start();
- }
-
- }
-
- private Vector<ThreadGroup> asyncBuildRandomTreeUnder(final ThreadGroup aGroup,
- final int depth) {
- Vector<ThreadGroup> result = new Vector<ThreadGroup>();
- asyncBuildRandomTreeUnder(aGroup, depth, result);
- return result;
-
- }
-
- private boolean allSuspended(Vector<MyThread> threads) {
- for (int i = 0; i < threads.size(); i++) {
- MyThread t = threads.elementAt(i);
- if (t.isActivelyRunning()) {
- return false;
- }
- }
-
- return true;
-
- }
-
- private ThreadGroup[] groups(ThreadGroup parent) {
- // No API to get the count of immediate children only ?
- int count = parent.activeGroupCount();
- ThreadGroup[] all = new ThreadGroup[count];
- parent.enumerate(all, false);
- // Now we may have nulls in the array, we must find the actual size
- int actualSize = 0;
- for (; actualSize < all.length; actualSize++) {
- if (all[actualSize] == null) {
- break;
- }
- }
- ThreadGroup[] result;
- if (actualSize == all.length) {
- result = all;
- } else {
- result = new ThreadGroup[actualSize];
- System.arraycopy(all, 0, result, 0, actualSize);
- }
-
- return result;
-
- }
-
- private Vector<MyThread> populateGroupsWithThreads(final ThreadGroup aGroup,
- final int threadCount) {
- Vector<MyThread> result = new Vector<MyThread>();
- populateGroupsWithThreads(aGroup, threadCount, result);
- return result;
-
- }
-
- private void populateGroupsWithThreads(final ThreadGroup aGroup,
- final int threadCount, final Vector<MyThread> allCreated) {
- for (int i = 0; i < threadCount; i++) {
- final int iClone = i;
- final String name = "(MyThread)N =" + iClone + "/" + threadCount
- + " ,Vector size at creation: " + allCreated.size();
-
- MyThread t = new MyThread(aGroup, name);
- allCreated.addElement(t);
- }
-
- // Recursively for subgroups (if any)
- ThreadGroup[] children = groups(aGroup);
- for (ThreadGroup element : children) {
- populateGroupsWithThreads(element, threadCount, allCreated);
- }
-
- }
-
- private int random(int max) {
-
- return 1 + ((new Object()).hashCode() % max);
-
- }
-
- @SuppressWarnings("deprecation")
- private boolean wipeThread(Thread t) {
- t.stop();
- try {
- t.join(1000);
- } catch (InterruptedException ie) {
- fail("Should not have been interrupted");
- }
- // The thread had plenty (subjective) of time to die so there
- // is a problem.
- if (t.isAlive()) {
- return false;
- }
-
- return true;
- }
-
- private Vector<ThreadGroup> buildRandomTreeUnder(ThreadGroup aGroup, int depth) {
- Vector<ThreadGroup> result = asyncBuildRandomTreeUnder(aGroup, depth);
- while (true) {
- int sizeBefore = result.size();
- try {
- Thread.sleep(1000);
- int sizeAfter = result.size();
- // If no activity for a while, we assume async building may be
- // done.
- if (sizeBefore == sizeAfter) {
- // It can only be done if no more threads. Unfortunately we
- // are relying on this API to work as well.
- // If it does not, we may loop forever.
- if (aGroup.activeCount() == 0) {
- break;
- }
- }
- } catch (InterruptedException e) {
- }
- }
- return result;
-
- }
-
- private boolean arrayIncludes(Object[] array, Object toTest) {
- for (Object element : array) {
- if (element == toTest) {
- return true;
- }
- }
-
- return false;
- }
-
- protected void myassertTrue(String msg, boolean b) {
- // This method is defined here just to solve a visibility problem
- // of protected methods with inner types
- assertTrue(msg, b);
- }
-
- private ThreadGroup getRootThreadGroup() {
- return rootThreadGroup;
-
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkAccess(ThreadGroup g) {
- throw new SecurityException();
- }
- };
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadLocalTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadLocalTest.java
deleted file mode 100644
index c75e0f8..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadLocalTest.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(ThreadLocal.class)
-public class ThreadLocalTest extends TestCase {
-
- /**
- * @tests java.lang.ThreadLocal#ThreadLocal()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ThreadLocal",
- args = {}
- )
- public void test_Constructor() {
- try {
- new ThreadLocal<Object>();
- } catch (Exception e) {
- fail("unexpected exception: " + e.toString());
- }
- }
-
- /**
- * @tests java.lang.ThreadLocal#remove()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {}
- )
- public void test_remove() {
- ThreadLocal<String> tl = new ThreadLocal<String>() {
- @Override
- protected String initialValue() {
- return "initial";
- }
- };
-
- assertEquals("initial", tl.get());
- tl.set("fixture");
- assertEquals("fixture", tl.get());
- tl.remove();
- assertEquals("initial", tl.get());
- }
-
- /**
- * @tests java.lang.ThreadLocal#get()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {}
- )
- public void test_get() {
- // Test for method java.lang.Object java.lang.ThreadLocal.get()
- ThreadLocal<Object> l = new ThreadLocal<Object>();
- assertNull("ThreadLocal's initial value is null", l.get());
-
- // The ThreadLocal has to run once for each thread that touches the
- // ThreadLocal
- final Object INITIAL_VALUE = "'foo'";
- final ThreadLocal<Object> l1 = new ThreadLocal<Object>() {
- @Override
- protected Object initialValue() {
- return INITIAL_VALUE;
- }
- };
-
- assertTrue("ThreadLocal's initial value should be " + INITIAL_VALUE
- + " but is " + l1.get(), l1.get() == INITIAL_VALUE);
-
- // We need this because inner types cannot assign to variables in
- // container method. But assigning to object slots in the container
- // method is ok.
- class ResultSlot {
- public Object result = null;
- }
-
- final ResultSlot THREADVALUE = new ResultSlot();
- Thread t = new Thread() {
- @Override
- public void run() {
- THREADVALUE.result = l1.get();
- }
- };
-
- // Wait for the other Thread assign what it observes as the value of the
- // variable
- t.start();
- try {
- t.join();
- } catch (InterruptedException ie) {
- fail("Interrupted!!");
- }
-
- assertTrue("ThreadLocal's initial value in other Thread should be "
- + INITIAL_VALUE, THREADVALUE.result == INITIAL_VALUE);
-
- /* Regression test for implementation vulnerability reported
- * on Harmony dev list.
- */
- ThreadLocal<Object> thrVar = new ThreadLocal<Object>() {
- public int hashCode() {
- fail("ThreadLocal should not be asked for it's hashCode");
- return 0; // never reached
- }
- };
- thrVar.get();
- }
-
- /**
- * @tests java.lang.ThreadLocal#set(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "set",
- args = {java.lang.Object.class}
- )
- public void test_setLjava_lang_Object() {
- // Test for method void java.lang.ThreadLocal.set(java.lang.Object)
-
- final Object OBJ = new Object();
- final ThreadLocal<Object> l = new ThreadLocal<Object>();
- l.set(OBJ);
- assertTrue("ThreadLocal's initial value is " + OBJ, l.get() == OBJ);
-
- // We need this because inner types cannot assign to variables in
- // container method.
- // But assigning to object slots in the container method is ok.
- class ResultSlot {
- public Object result = null;
- }
-
- final ResultSlot THREADVALUE = new ResultSlot();
- Thread t = new Thread() {
- @Override
- public void run() {
- THREADVALUE.result = l.get();
- }
- };
-
- // Wait for the other Thread assign what it observes as the value of the
- // variable
- t.start();
- try {
- t.join();
- } catch (InterruptedException ie) {
- fail("Interrupted!!");
- }
-
- // ThreadLocal is not inherited, so the other Thread should see it as
- // null
- assertNull("ThreadLocal's value in other Thread should be null",
- THREADVALUE.result);
-
- }
-
- /**
- * @tests java.lang.InheritableThreadLocal
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {}
- )
- public void test_Ljava_lang_InheritableThreadLocal()
- throws InterruptedException {
- final Object value = new Object();
- final Object inheritedValue = new Object();
- final ThreadLocal<Object> threadLocal
- = new InheritableThreadLocal<Object>() {
- @Override
- protected Object childValue(Object parentValue) {
- assertSame(value, parentValue);
- return inheritedValue;
- }
- };
- threadLocal.set(value);
- final Object[] holder = new Object[1];
- Thread thread = new Thread() {
- public void run() {
- holder[0] = threadLocal.get();
- }
- };
- thread.start();
- thread.join();
- assertSame(value, threadLocal.get());
- assertSame(inheritedValue, holder[0]);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadStateTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadStateTest.java
deleted file mode 100644
index cab73a1..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadStateTest.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-import junit.framework.TestCase;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(Thread.State.class)
-public class ThreadStateTest extends TestCase {
-
- Thread.State [] exStates = { Thread.State.NEW, Thread.State.RUNNABLE,
- Thread.State.BLOCKED, Thread.State.WAITING,
- Thread.State.TIMED_WAITING, Thread.State.TERMINATED };
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {java.lang.String.class}
- )
- public void test_valueOfLString(){
- String [] spNames = {"NEW", "RUNNABLE", "BLOCKED", "WAITING",
- "TIMED_WAITING", "TERMINATED"};
-
- for(int i = 0; i < exStates.length; i++) {
- assertEquals(exStates[i], Thread.State.valueOf(spNames[i]));
- }
-
- String [] illegalNames = {"New", "new", "", "NAME", "TIME"};
- for(String s:illegalNames) {
- try {
- Thread.State.valueOf(s);
- fail("IllegalArgumentException was not thrown for string: "+s);
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
- public void test_values() {
-
- Thread.State [] thStates = Thread.State.values();
- assertEquals(exStates.length, thStates.length);
- for(Thread.State ts:thStates) {
- assertTrue(isContain(ts));
- }
-
- }
-
- boolean isContain(Thread.State state) {
- for(Thread.State ts:exStates) {
- if(ts.equals(state)) return true;
- }
- return false;
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadTest.java
deleted file mode 100644
index b290555..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadTest.java
+++ /dev/null
@@ -1,2166 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import java.io.ByteArrayOutputStream;
-import java.io.PrintStream;
-import java.lang.Thread.UncaughtExceptionHandler;
-import java.security.Permission;
-import java.util.Map;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.concurrent.Semaphore;
-
-@TestTargetClass(Thread.class)
-public class ThreadTest extends junit.framework.TestCase {
-
- int counter = 0;
-
- static class SimpleThread implements Runnable {
- int delay;
-
- public void run() {
- try {
- synchronized (this) {
- this.notify();
- this.wait(delay);
- }
- } catch (InterruptedException e) {
- return;
- }
-
- }
-
- public SimpleThread(int d) {
- if (d >= 0)
- delay = d;
- }
- }
-
- static class YieldThread implements Runnable {
- volatile int delay;
-
- public void run() {
- int x = 0;
- while (true) {
- ++x;
- }
- }
-
- public YieldThread(int d) {
- if (d >= 0)
- delay = d;
- }
- }
-
- static class ResSupThread implements Runnable {
- Thread parent;
-
- volatile int checkVal = -1;
-
- public void run() {
- try {
- synchronized (this) {
- this.notify();
- }
- while (true) {
- checkVal++;
- zz();
- Thread.sleep(100);
- }
- } catch (InterruptedException e) {
- return;
- } catch (BogusException e) {
- try {
- // Give parent a chance to sleep
- Thread.sleep(500);
- } catch (InterruptedException x) {
- }
- parent.interrupt();
- while (!Thread.currentThread().isInterrupted()) {
- // Don't hog the CPU
- try {
- Thread.sleep(50);
- } catch (InterruptedException x) {
- // This is what we've been waiting for...don't throw it
- // away!
- break;
- }
- }
- }
- }
-
- public void zz() throws BogusException {
- }
-
- public ResSupThread(Thread t) {
- parent = t;
- }
-
- public synchronized int getCheckVal() {
- return checkVal;
- }
- }
-
- static class BogusException extends Throwable {
-
- private static final long serialVersionUID = 1L;
-
- public BogusException(String s) {
- super(s);
- }
- }
-
- // TODO android-added
- class MonitoredClass {
- public synchronized void enterLocked() {
- boolean b = Thread.holdsLock(this);
- assertTrue("Thread should hold lock for object", b);
- }
-
- public void enterNonLocked() {
- boolean b = Thread.holdsLock(this);
- assertFalse("Thread should not hold lock for object", b);
- }
- }
-
- Thread st, ct, spinner;
-
- static boolean calledMySecurityManager = false;
-
- /**
- * @tests java.lang.Thread#Thread()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Thread",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.lang.Thread()
-
- Thread t;
- SecurityManager m = new SecurityManager() {
- @Override
- public ThreadGroup getThreadGroup() {
- calledMySecurityManager = true;
- return Thread.currentThread().getThreadGroup();
- }
-
- @Override
- public void checkPermission(Permission permission) {
- if (permission.getName().equals("setSecurityManager")) {
- return;
- }
- super.checkPermission(permission);
- }
- };
- try {
- // To see if it checks Thread creation with our SecurityManager
- System.setSecurityManager(m);
- t = new Thread();
- } finally {
- // restore original, no side-effects
- System.setSecurityManager(null);
- }
- assertTrue("Did not call SecurityManager.getThreadGroup ()",
- calledMySecurityManager);
- t.start();
- }
-
- /**
- * @tests java.lang.Thread#Thread(java.lang.Runnable)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Thread",
- args = {java.lang.Runnable.class}
- )
- public void test_ConstructorLjava_lang_Runnable() {
- // Test for method java.lang.Thread(java.lang.Runnable)
- try {
- ct = new Thread(new SimpleThread(10));
- ct.start();
- } catch (Exception e) {
- fail("Failed to create subthread : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.lang.Thread#Thread(java.lang.Runnable, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Thread",
- args = {java.lang.Runnable.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_RunnableLjava_lang_String() {
- // Test for method java.lang.Thread(java.lang.Runnable,
- // java.lang.String)
- Thread st1 = new Thread(new SimpleThread(1), "SimpleThread1");
- assertEquals("Constructed thread with incorrect thread name", "SimpleThread1", st1
- .getName());
- st1.start();
- }
-
- /**
- * @tests java.lang.Thread#Thread(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Thread",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.lang.Thread(java.lang.String)
- Thread t = new Thread("Testing");
- assertEquals("Created tread with incorrect name",
- "Testing", t.getName());
- t.start();
- }
-
- /**
- * @tests java.lang.Thread#Thread(java.lang.ThreadGroup, java.lang.Runnable)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Thread",
- args = {java.lang.ThreadGroup.class, java.lang.Runnable.class}
- )
- public void test_ConstructorLjava_lang_ThreadGroupLjava_lang_Runnable() {
- // Test for method java.lang.Thread(java.lang.ThreadGroup,
- // java.lang.Runnable)
- ThreadGroup tg = new ThreadGroup("Test Group1");
- st = new Thread(tg, new SimpleThread(1), "SimpleThread2");
- assertTrue("Returned incorrect thread group", st.getThreadGroup() == tg);
- st.start();
- try {
- st.join();
- } catch (InterruptedException e) {
- }
- tg.destroy();
- }
-
- /**
- * @tests java.lang.Thread#Thread(java.lang.ThreadGroup, java.lang.Runnable,
- * java.lang.String)lo
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Thread",
- args = {java.lang.ThreadGroup.class, java.lang.Runnable.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_ThreadGroupLjava_lang_RunnableLjava_lang_String() {
- // Test for method java.lang.Thread(java.lang.ThreadGroup,
- // java.lang.Runnable, java.lang.String)
- ThreadGroup tg = new ThreadGroup("Test Group2");
- st = new Thread(tg, new SimpleThread(1), "SimpleThread3");
- assertTrue("Constructed incorrect thread", (st.getThreadGroup() == tg)
- && st.getName().equals("SimpleThread3"));
- st.start();
- try {
- st.join();
- } catch (InterruptedException e) {
- }
- tg.destroy();
-
- Runnable r = new Runnable() {
- public void run() {
- }
- };
-
- ThreadGroup foo = null;
- try {
- new Thread(foo = new ThreadGroup("foo"), r, null);
- // Should not get here
- fail("Null cannot be accepted as Thread name");
- } catch (NullPointerException npe) {
- assertTrue("Null cannot be accepted as Thread name", true);
- foo.destroy();
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Thread",
- args = {java.lang.ThreadGroup.class, java.lang.Runnable.class, java.lang.String.class, long.class}
- )
- public void test_ConstructorLjava_lang_ThreadGroupLjava_lang_RunnableLjava_lang_StringL$L() {
- ThreadGroup tg = new ThreadGroup("Test Group2");
- st = new Thread(tg, new SimpleThread(1), "SimpleThread3", 1);
- assertTrue("Constructed incorrect thread", (st.getThreadGroup() == tg)
- && st.getName().equals("SimpleThread3"));
- st.start();
- try {
- st.join();
- } catch (InterruptedException e) {
- }
- tg.destroy();
-
- Runnable r = new Runnable() {
- public void run() {
- }
- };
-
- try {
- new Thread(tg, new SimpleThread(1), "SimpleThread3",
- Integer.MAX_VALUE);
- fail("StackOverflowError/OutOfMemoryError is not thrown.");
- } catch(IllegalThreadStateException itse) {
- //expected
- }
-
- }
-
- /**
- * @tests java.lang.Thread#Thread(java.lang.ThreadGroup, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Thread",
- args = {java.lang.ThreadGroup.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_ThreadGroupLjava_lang_String() {
- // Test for method java.lang.Thread(java.lang.ThreadGroup,
- // java.lang.String)
- st = new Thread(new SimpleThread(1), "SimpleThread4");
- assertEquals("Returned incorrect thread name",
- "SimpleThread4", st.getName());
- st.start();
- }
-
- /**
- * @tests java.lang.Thread#activeCount()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "activeCount",
- args = {}
- )
- public void test_activeCount() {
- // Test for method int java.lang.Thread.activeCount()
- Thread t = new Thread(new SimpleThread(1));
- int active = Thread.activeCount();
- assertTrue("Incorrect read made: " + active, active > 0);
- t.start();
- try {
- t.join();
- } catch (InterruptedException e) {
- }
- }
-
- /**
- * @tests java.lang.Thread#checkAccess()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkAccess",
- args = {}
- )
- public void test_checkAccess() {
- // Test for method void java.lang.Thread.checkAccess()
- ThreadGroup tg = new ThreadGroup("Test Group3");
- try {
- st = new Thread(tg, new SimpleThread(1), "SimpleThread5");
- st.checkAccess();
- assertTrue("CheckAccess passed", true);
- } catch (SecurityException e) {
- fail("CheckAccess failed : " + e.getMessage());
- }
- st.start();
- try {
- st.join();
- } catch (InterruptedException e) {
- }
- tg.destroy();
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkAccess(Thread t) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- st.checkAccess();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Thread#countStackFrames()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "countStackFrames",
- args = {}
- )
- @SuppressWarnings("deprecation")
- public void test_countStackFrames() {
- /*
- * Thread.countStackFrames() is unpredictable, so we just test that it
- * doesn't throw an exception.
- */
- try {
- Thread.currentThread().countStackFrames();
- } catch (Throwable t) {
- fail("unexpected throwable: " + t.toString());
- }
- }
-
- /**
- * @tests java.lang.Thread#currentThread()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "currentThread",
- args = {}
- )
- public void test_currentThread() {
- assertNotNull(Thread.currentThread());
- }
-
- /**
- * @tests java.lang.Thread#destroy()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "destroy",
- args = {}
- )
- @SuppressWarnings("deprecation")
- public void test_destroy() {
- try {
- new Thread().destroy();
- // FIXME uncomment when IBM VME is updated
- fail("NoSuchMethodError was not thrown");
- } catch (NoSuchMethodError e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "dumpStack",
- args = {}
- )
- public void test_dumpStack() {
- try {
- PrintStream savedErr = System.err;
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- System.setErr(new PrintStream(baos));
- Thread.dumpStack();
- System.setErr(savedErr);
-
- String s = new String(baos.toByteArray());
-
- assertTrue(s.contains("java.lang.Thread.dumpStack"));
-
- } catch(Exception e) {
- fail("Unexpected exception was thrown: " + e.toString());
- }
- }
-
- /**
- * @tests java.lang.Thread#enumerate(java.lang.Thread[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "enumerate",
- args = {java.lang.Thread[].class}
- )
- public void test_enumerate$Ljava_lang_Thread() {
- // Test for method int java.lang.Thread.enumerate(java.lang.Thread [])
- // The test has been updated according to HARMONY-1974 JIRA issue.
-
- class MyThread extends Thread {
- MyThread(ThreadGroup tg, String name) {
- super(tg, name);
- }
-
- boolean failed = false;
- String failMessage = null;
-
- public void run() {
- SimpleThread st1 = null;
- SimpleThread st2 = null;
- ThreadGroup mytg = null;
- Thread firstOne = null;
- Thread secondOne = null;
- try {
- int arrayLength = 10;
- Thread[] tarray = new Thread[arrayLength];
- st1 = new SimpleThread(-1);
- st2 = new SimpleThread(-1);
- mytg = new ThreadGroup("jp");
- firstOne = new Thread(mytg, st1, "firstOne2");
- secondOne = new Thread(mytg, st2, "secondOne1");
- int count = Thread.enumerate(tarray);
- assertEquals("Incorrect value returned1",
- 1, count);
- synchronized (st1) {
- firstOne.start();
- try {
- st1.wait();
- } catch (InterruptedException e) {
- }
- }
- count = Thread.enumerate(tarray);
- assertEquals("Incorrect value returned2",
- 2, count);
- synchronized (st2) {
- secondOne.start();
- try {
- st2.wait();
- } catch (InterruptedException e) {
- }
- }
- count = Thread.enumerate(tarray);
- assertEquals("Incorrect value returned3",
- 3, count);
- } catch (junit.framework.AssertionFailedError e) {
- failed = true;
- failMessage = e.getMessage();
- } finally {
- synchronized (st1) {
- firstOne.interrupt();
- }
- synchronized (st2) {
- secondOne.interrupt();
- }
- try {
- firstOne.join();
- secondOne.join();
- } catch (InterruptedException e) {
- }
- mytg.destroy();
- }
- }
- };
-
- ThreadGroup tg = new ThreadGroup("tg");
- MyThread t = new MyThread(tg, "top");
- t.start();
- try {
- t.join();
- } catch (InterruptedException e) {
- fail("Unexpected interrupt");
- } finally {
- tg.destroy();
- }
- assertFalse(t.failMessage, t.failed);
- }
-
- /**
- * @tests java.lang.Thread#getContextClassLoader()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getContextClassLoader",
- args = {}
- )
- public void test_getContextClassLoader() {
- // Test for method java.lang.ClassLoader
- // java.lang.Thread.getContextClassLoader()
- Thread t = new Thread();
- assertTrue("Incorrect class loader returned",
- t.getContextClassLoader() == Thread.currentThread()
- .getContextClassLoader());
- t.start();
-
- /* SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if(perm.getName().equals("getClassLoader")) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- t.getContextClassLoader();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
-*/
- }
-
- /**
- * @tests java.lang.Thread#getName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getName",
- args = {}
- )
- public void test_getName() {
- // Test for method java.lang.String java.lang.Thread.getName()
- st = new Thread(new SimpleThread(1), "SimpleThread6");
- assertEquals("Returned incorrect thread name",
- "SimpleThread6", st.getName());
- st.start();
- }
-
- /**
- * @tests java.lang.Thread#getPriority()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPriority",
- args = {}
- )
- public void test_getPriority() {
- // Test for method int java.lang.Thread.getPriority()
- st = new Thread(new SimpleThread(1));
- st.setPriority(Thread.MAX_PRIORITY);
- assertTrue("Returned incorrect thread priority",
- st.getPriority() == Thread.MAX_PRIORITY);
- st.start();
- }
-
- /**
- * @tests java.lang.Thread#getThreadGroup()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getThreadGroup",
- args = {}
- )
- public void test_getThreadGroup() {
- // Test for method java.lang.ThreadGroup
- // java.lang.Thread.getThreadGroup()
- ThreadGroup tg = new ThreadGroup("Test Group4");
- st = new Thread(tg, /* new SimpleThread(1), */ "SimpleThread8");
- assertTrue("Returned incorrect thread group", st.getThreadGroup() == tg);
- st.start();
- try {
- st.join();
- } catch (InterruptedException e) {
- }
- assertNull("group should be null", st.getThreadGroup());
- assertNotNull("toString() should not be null", st.toString());
- tg.destroy();
-
- final Object lock = new Object();
- Thread t = new Thread() {
- @Override
- public void run() {
- synchronized (lock) {
- lock.notifyAll();
- }
- }
- };
- synchronized (lock) {
- t.start();
- try {
- lock.wait();
- } catch (InterruptedException e) {
- }
- }
- int running = 0;
- while (t.isAlive())
- running++;
- ThreadGroup group = t.getThreadGroup();
- assertNull("ThreadGroup is not null", group);
- }
-
- /**
- * @tests java.lang.Thread#interrupt()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "interrupt",
- args = {}
- )
- public void test_interrupt() {
- // Test for method void java.lang.Thread.interrupt()
- final Object lock = new Object();
- class ChildThread1 extends Thread {
- Thread parent;
-
- boolean sync;
-
- @Override
- public void run() {
- if (sync) {
- synchronized (lock) {
- lock.notify();
- try {
- lock.wait();
- } catch (InterruptedException e) {
- }
- }
- }
- parent.interrupt();
- }
-
- public ChildThread1(Thread p, String name, boolean sync) {
- super(name);
- parent = p;
- this.sync = sync;
- }
- }
- boolean interrupted = false;
- try {
- ct = new ChildThread1(Thread.currentThread(), "Interrupt Test1",
- false);
- synchronized (lock) {
- ct.start();
- lock.wait();
- }
- } catch (InterruptedException e) {
- interrupted = true;
- }
- assertTrue("Failed to Interrupt thread1", interrupted);
-
- interrupted = false;
- try {
- ct = new ChildThread1(Thread.currentThread(), "Interrupt Test2",
- true);
- synchronized (lock) {
- ct.start();
- lock.wait();
- lock.notify();
- }
- Thread.sleep(20000);
- } catch (InterruptedException e) {
- interrupted = true;
- }
- assertTrue("Failed to Interrupt thread2", interrupted);
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkAccess(Thread t) {
- throw new SecurityException();
- }
- };
- st = new Thread();
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- st.interrupt();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Thread#interrupted()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "interrupted",
- args = {}
- )
- public void test_interrupted() {
- assertFalse("Interrupted returned true for non-interrupted thread", Thread
- .interrupted());
- Thread.currentThread().interrupt();
- assertTrue("Interrupted returned true for non-interrupted thread", Thread.interrupted());
- assertFalse("Failed to clear interrupted flag", Thread.interrupted());
- }
-
- /**
- * @tests java.lang.Thread#isAlive()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isAlive",
- args = {}
- )
- public void test_isAlive() {
- // Test for method boolean java.lang.Thread.isAlive()
- SimpleThread simple;
- st = new Thread(simple = new SimpleThread(500));
- assertFalse("A thread that wasn't started is alive.", st.isAlive());
- synchronized (simple) {
- st.start();
- try {
- simple.wait();
- } catch (InterruptedException e) {
- }
- }
- assertTrue("Started thread returned false", st.isAlive());
-
- try {
- st.join();
- } catch (InterruptedException e) {
- fail("Thread did not die");
- }
- assertTrue("Stopped thread returned true", !st.isAlive());
- }
-
- /**
- * @tests java.lang.Thread#isDaemon()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isDaemon",
- args = {}
- )
- public void test_isDaemon() {
- // Test for method boolean java.lang.Thread.isDaemon()
- st = new Thread(new SimpleThread(1), "SimpleThread10");
- assertTrue("Non-Daemon thread returned true", !st.isDaemon());
- st.setDaemon(true);
- assertTrue("Daemon thread returned false", st.isDaemon());
- st.start();
- }
-
- /**
- * @tests java.lang.Thread#isInterrupted()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isInterrupted",
- args = {}
- )
- public void test_isInterrupted() {
- // Test for method boolean java.lang.Thread.isInterrupted()
- class SpinThread implements Runnable {
- public volatile boolean done = false;
-
- public void run() {
- while (!Thread.currentThread().isInterrupted())
- ;
- while (!done)
- ;
- }
- }
-
- SpinThread spin = new SpinThread();
- spinner = new Thread(spin);
- spinner.start();
- Thread.yield();
- try {
- assertTrue("Non-Interrupted thread returned true", !spinner
- .isInterrupted());
- spinner.interrupt();
- assertTrue("Interrupted thread returned false", spinner
- .isInterrupted());
- spin.done = true;
- } finally {
- spinner.interrupt();
- spin.done = true;
- }
- }
-
- /**
- * @tests java.lang.Thread#join()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "join",
- args = {}
- )
- public void test_join() {
- // Test for method void java.lang.Thread.join()
- SimpleThread simple;
- try {
- st = new Thread(simple = new SimpleThread(100));
- // cause isAlive() to be compiled by the JIT, as it must be called
- // within 100ms below.
- assertTrue("Thread is alive", !st.isAlive());
- synchronized (simple) {
- st.start();
- simple.wait();
- }
- st.join();
- } catch (InterruptedException e) {
- fail("Join failed ");
- }
- assertTrue("Joined thread is still alive", !st.isAlive());
- boolean result = true;
- Thread th = new Thread("test");
- try {
- th.join();
- } catch (InterruptedException e) {
- result = false;
- }
- assertTrue("Hung joining a non-started thread", result);
- th.start();
-
- st = new Thread() {
- public void run() {
- try {
- join();
- fail("InterruptedException was not thrown.");
- } catch(InterruptedException ie) {
- //expected
- }
- }
- };
-
- st.start();
- }
-
- /**
- * @tests java.lang.Thread#join(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "join",
- args = {long.class}
- )
- public void test_joinJ() {
- // Test for method void java.lang.Thread.join(long)
- SimpleThread simple;
- try {
- st = new Thread(simple = new SimpleThread(1000), "SimpleThread12");
- // cause isAlive() to be compiled by the JIT, as it must be called
- // within 100ms below.
- assertTrue("Thread is alive", !st.isAlive());
- synchronized (simple) {
- st.start();
- simple.wait();
- }
- st.join(10);
- } catch (InterruptedException e) {
- fail("Join failed ");
- }
- assertTrue("Join failed to timeout", st.isAlive());
-
- st.interrupt();
- try {
- st = new Thread(simple = new SimpleThread(100), "SimpleThread13");
- synchronized (simple) {
- st.start();
- simple.wait();
- }
- st.join(1000);
- } catch (InterruptedException e) {
- fail("Join failed : " + e.getMessage());
- return;
- }
- assertTrue("Joined thread is still alive", !st.isAlive());
-
- final Object lock = new Object();
- final Thread main = Thread.currentThread();
- Thread killer = new Thread(new Runnable() {
- public void run() {
- try {
- synchronized (lock) {
- lock.notify();
- }
- Thread.sleep(100);
- } catch (InterruptedException e) {
- return;
- }
- main.interrupt();
- }
- });
- boolean result = true;
- Thread th = new Thread("test");
- try {
- synchronized (lock) {
- killer.start();
- lock.wait();
- }
- th.join(200);
- } catch (InterruptedException e) {
- result = false;
- }
- killer.interrupt();
- assertTrue("Hung joining a non-started thread", result);
- th.start();
-
- st = new Thread() {
- public void run() {
- try {
- join(1000);
- fail("InterruptedException was not thrown.");
- } catch(InterruptedException ie) {
- //expected
- }
- }
- };
-
- st.start();
- }
-
- /**
- * @tests java.lang.Thread#join(long, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "join",
- args = {long.class, int.class}
- )
- public void test_joinJI() {
- // Test for method void java.lang.Thread.join(long, int)
- SimpleThread simple;
- try {
- st = new Thread(simple = new SimpleThread(1000), "Squawk1");
- assertTrue("Thread is alive", !st.isAlive());
- synchronized (simple) {
- st.start();
- simple.wait();
- }
-
- long firstRead = System.currentTimeMillis();
- st.join(100, 999999);
- long secondRead = System.currentTimeMillis();
- assertTrue("Did not join by appropriate time: " + secondRead + "-"
- + firstRead + "=" + (secondRead - firstRead), secondRead
- - firstRead <= 300);
- assertTrue("Joined thread is not alive", st.isAlive());
- st.interrupt();
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
-
- final Object lock = new Object();
- final Thread main = Thread.currentThread();
- Thread killer = new Thread(new Runnable() {
- public void run() {
- try {
- synchronized (lock) {
- lock.notify();
- }
- Thread.sleep(100);
- } catch (InterruptedException e) {
- return;
- }
- main.interrupt();
- }
- });
- boolean result = true;
- Thread th = new Thread("test");
- try {
- synchronized (lock) {
- killer.start();
- lock.wait();
- }
- th.join(200, 20);
- } catch (InterruptedException e) {
- result = false;
- }
- killer.interrupt();
- assertTrue("Hung joining a non-started thread", result);
- th.start();
-
- st = new Thread() {
- public void run() {
- try {
- join(1000, 20);
- fail("InterruptedException was not thrown.");
- } catch(InterruptedException ie) {
- //expected
- }
- }
- };
-
- st.start();
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setContextClassLoader",
- args = {java.lang.ClassLoader.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getContextClassLoader",
- args = {}
- )
- })
- public void test_setContextClassLoader() {
- PublicClassLoader pcl = new PublicClassLoader();
- st = new Thread();
- st.setContextClassLoader(pcl);
- assertEquals(pcl, st.getContextClassLoader());
-
- st.setContextClassLoader(null);
- assertNull(st.getContextClassLoader());
-
- SecurityManager sm = new SecurityManager() {
- public void checkPermission(Permission perm) {
- if (perm.getName().equals("setContextClassLoader")
- || perm.getName().equals("getClassLoader") ) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- st.setContextClassLoader(pcl);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
-
- /**
- * @tests java.lang.Thread#resume()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "resume",
- args = {}
- )
- @AndroidOnly("Android throws UnsupportedOperationException for Thread.resume()")
- @SuppressWarnings("deprecation")
- public void test_resume() {
- // Test for method void java.lang.Thread.resume()
- int orgval;
- ResSupThread t;
- try {
- t = new ResSupThread(Thread.currentThread());
- synchronized (t) {
- ct = new Thread(t, "Interrupt Test2");
- ct.start();
- t.wait();
- }
- try {
- ct.resume();
- } catch (UnsupportedOperationException e) {
- // expected
- }
- } catch (InterruptedException e) {
- fail("Unexpected interrupt occurred : " + e.getMessage());
- }
-
- // Security checks are made even though resume() is not supported.
- SecurityManager sm = new SecurityManager() {
- public void checkPermission(Permission perm) {
- }
-
- public void checkAccess(Thread t) {
- throw new SecurityException();
- }
- };
- st = new Thread();
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- st.resume();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Thread#run()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "run",
- args = {}
- )
- public void test_run() {
- // Test for method void java.lang.Thread.run()
- class RunThread implements Runnable {
- boolean didThreadRun = false;
-
- public void run() {
- didThreadRun = true;
- }
- }
- RunThread rt = new RunThread();
- Thread t = new Thread(rt);
- try {
- t.start();
- int count = 0;
- while (!rt.didThreadRun && count < 20) {
- Thread.sleep(100);
- count++;
- }
- assertTrue("Thread did not run", rt.didThreadRun);
- t.join();
- } catch (InterruptedException e) {
- assertTrue("Joined thread was interrupted", true);
- }
- assertTrue("Joined thread is still alive", !t.isAlive());
- }
-
- /**
- * @tests java.lang.Thread#setDaemon(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setDaemon",
- args = {boolean.class}
- )
- public void test_setDaemonZ() {
- // Test for method void java.lang.Thread.setDaemon(boolean)
- st = new Thread(new SimpleThread(1), "SimpleThread14");
- st.setDaemon(true);
- assertTrue("Failed to set thread as daemon thread", st.isDaemon());
- st.start();
-
- // BEGIN android-added
- st = new Thread(new SimpleThread(5));
- st.start();
- try {
- st.setDaemon(false);
- fail("setDaemon() must throw exception for started thread");
- } catch (IllegalThreadStateException ex) {
- // We expect this one.
- }
- // END android-added
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkAccess(Thread t) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- st.setDaemon(false);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Thread#setName(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setName",
- args = {java.lang.String.class}
- )
- public void test_setNameLjava_lang_String() {
- // Test for method void java.lang.Thread.setName(java.lang.String)
- st = new Thread(new SimpleThread(1), "SimpleThread15");
- st.setName("Bogus Name");
- assertEquals("Failed to set thread name",
- "Bogus Name", st.getName());
- try {
- st.setName(null);
- fail("Null should not be accepted as a valid name");
- } catch (NullPointerException e) {
- // success
- assertTrue("Null should not be accepted as a valid name", true);
- }
- st.start();
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkAccess(Thread t) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- st.setName("Bogus Name");
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Thread#setPriority(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setPriority",
- args = {int.class}
- )
- public void test_setPriorityI() {
- // Test for method void java.lang.Thread.setPriority(int)
- st = new Thread(new SimpleThread(1));
- st.setPriority(Thread.MAX_PRIORITY);
- assertTrue("Failed to set priority",
- st.getPriority() == Thread.MAX_PRIORITY);
- st.start();
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkAccess(Thread t) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- st.setPriority(Thread.MIN_PRIORITY);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- try {
- st.setPriority(Thread.MIN_PRIORITY - 1);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setPriority(Thread.MAX_PRIORITY + 1);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @tests java.lang.Thread#sleep(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sleep",
- args = {long.class}
- )
- public void test_sleepJ() {
- // Test for method void java.lang.Thread.sleep(long)
-
- // TODO : Test needs enhancing.
- long stime = 0, ftime = 0;
- try {
- stime = System.currentTimeMillis();
- Thread.sleep(1000);
- ftime = System.currentTimeMillis();
- } catch (InterruptedException e) {
- fail("Unexpected interrupt received");
- }
- assertTrue("Failed to sleep long enough", (ftime - stime) >= 800);
-
- counter = 0;
- st = new Thread() {
-
- public void run() {
- while(true) {
- try {
- sleep(1000);
- counter++;
- } catch(InterruptedException e) {
-
- }
- }
- }
- };
-
- st.start();
-
- try {
- Thread.sleep(5000);
- } catch(InterruptedException e) {
- fail("InterruptedException was thrown.");
- }
- assertEquals(4, counter);
-
- st = new Thread() {
- public void run() {
- try {
- sleep(10000);
- fail("InterruptedException is thrown.");
- } catch(InterruptedException ie) {
- //exception
- }
- }
- };
-
- st.start();
- st.interrupt();
- }
-
- /**
- * @tests java.lang.Thread#sleep(long, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sleep",
- args = {long.class, int.class}
- )
- public void test_sleepJI() {
- // Test for method void java.lang.Thread.sleep(long, int)
-
- // TODO : Test needs revisiting.
- long stime = 0, ftime = 0;
- try {
- stime = System.currentTimeMillis();
- Thread.sleep(1000, 999999);
- ftime = System.currentTimeMillis();
- } catch (InterruptedException e) {
- fail("Unexpected interrupt received");
- }
- long result = ftime - stime;
- assertTrue("Failed to sleep long enough: " + result, result >= 900
- && result <= 1100);
-
- counter = 0;
- st = new Thread() {
-
- public void run() {
- while(true) {
- try {
- sleep(0, 999999);
- counter++;
- } catch(InterruptedException e) {
-
- }
- }
- }
- };
-
- st.start();
-
- try {
- Thread.sleep(2, 999999);
- } catch(InterruptedException e) {
- fail("InterruptedException was thrown.");
- }
- assertEquals(2, counter);
-
- st = new Thread() {
- public void run() {
- try {
- sleep(10000, 999999);
- fail("InterruptedException is thrown.");
- } catch(InterruptedException ie) {
- //exception
- }
- }
- };
- st.start();
- st.interrupt();
- }
-
- /**
- * @tests java.lang.Thread#start()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "start",
- args = {}
- )
- public void test_start() {
- // Test for method void java.lang.Thread.start()
- try {
- ResSupThread t = new ResSupThread(Thread.currentThread());
- synchronized (t) {
- ct = new Thread(t, "Interrupt Test4");
- ct.start();
- t.wait();
- }
- assertTrue("Thread is not running1", ct.isAlive());
- // Let the child thread get going.
- int orgval = t.getCheckVal();
- Thread.sleep(150);
- assertTrue("Thread is not running2", orgval != t.getCheckVal());
- ct.interrupt();
- } catch (InterruptedException e) {
- fail("Unexpected interrupt occurred");
- }
- Thread thr = new Thread();
- thr.start();
- try {
- thr.start();
- } catch(IllegalThreadStateException itse){
- //expected
- }
- }
-
- /**
- * @tests java.lang.Thread#stop()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "stop",
- args = {}
- )
- @AndroidOnly("Android throws UnsupportedOperationException for Thread.stop()")
- @SuppressWarnings("deprecation")
- public void test_stop() {
- // Test for method void java.lang.Thread.stop()
- try {
- Runnable r = new ResSupThread(null);
- synchronized (r) {
- st = new Thread(r, "Interupt Test5");
- st.start();
- r.wait();
- }
-
- } catch (InterruptedException e) {
- fail("Unexpected interrupt received");
- }
- try {
- st.stop();
- fail("Expected UnsupportedOperationException because" +
- "Thread.stop is not supported.");
- } catch (UnsupportedOperationException e) {
- // expected
- }
-
- // Security checks are made even though stop() is not supported.
- SecurityManager sm = new SecurityManager() {
- public void checkPermission(Permission perm) {
- if(perm.getName().equals("stopThread")) {
- throw new SecurityException();
- }
- }
- };
- st = new Thread();
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- st.stop();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Thread#stop(java.lang.Throwable)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies security.",
- method = "stop",
- args = {java.lang.Throwable.class}
- )
- @SuppressWarnings("deprecation")
- public void test_stopLjava_lang_Throwable_subtest0() {
- // Security checks are made even though stop(Throwable) is not supported.
- Thread t = new Thread("t");
- class MySecurityManager extends SecurityManager {
- @Override
- public void checkAccess(Thread t) {
- throw new SecurityException();
- }
- @Override
- public void checkPermission(Permission permission) {
-
- if(permission.getName().equals("stopThread")) {
- throw new SecurityException();
- }
- }
- }
- MySecurityManager sm = new MySecurityManager();
- System.setSecurityManager(sm);
- try {
- try {
- t.stop(new ThreadDeath());
- fail("SecurityException was thrown.");
- } catch (SecurityException e) {
- }
- t.start();
- try {
- t.join(1000);
- } catch (InterruptedException e) {
- }
- try {
- t.stop(new ThreadDeath());
- fail("SecurityException was thrown.");
- } catch (SecurityException e) {
- }
-
- } finally {
- System.setSecurityManager(null);
- }
- }
-
- /**
- * @tests java.lang.Thread#stop(java.lang.Throwable)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "SecurityException is not verified.",
- method = "stop",
- args = {java.lang.Throwable.class}
- )
- @AndroidOnly("Android throws UnsupportedOperationException for Thread.stop(Thorwable)")
- @SuppressWarnings("deprecation")
- public void test_stopLjava_lang_Throwable() {
- // Test for method void java.lang.Thread.stop(java.lang.Throwable)
- ResSupThread t = new ResSupThread(Thread.currentThread());
- synchronized (t) {
- st = new Thread(t, "StopThread");
- st.setPriority(Thread.MAX_PRIORITY);
- st.start();
- try {
- t.wait();
- } catch (InterruptedException e) {
- }
- }
- try {
- st.stop(new BogusException("Bogus"));
- fail("Expected UnsupportedOperationException because" +
- "Thread.stop is not supported.");
- } catch (UnsupportedOperationException e) {
- // expected
- }
-
- try {
- st.stop(null);
- fail("Expected NullPointerException was not thrown");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.lang.Thread#suspend()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "suspend",
- args = {}
- )
- @AndroidOnly("Android throws UnsupportedOperationException for Thread.suspend()")
- @SuppressWarnings("deprecation")
- public void test_suspend() {
- // Test for method void java.lang.Thread.suspend()
- int orgval;
- ResSupThread t = new ResSupThread(Thread.currentThread());
- try {
- synchronized (t) {
- ct = new Thread(t, "Interupt Test6");
- ct.start();
- t.wait();
- }
- ct.suspend();
- fail("Expected UnsupportedOperationException because" +
- "Thread.suspend is not supported.");
- } catch (UnsupportedOperationException e) {
- // expected
- } catch (InterruptedException e) {
- fail("Unexpected InterruptedException was thrown");
- }
-
- // Security checks are made even though suspend() is not supported.
- SecurityManager sm = new SecurityManager() {
- public void checkPermission(Permission perm) {
- }
-
- public void checkAccess(Thread t) {
- throw new SecurityException();
- }
- };
- st = new Thread();
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- st.suspend();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Thread#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.lang.Thread.toString()
- ThreadGroup tg = new ThreadGroup("Test Group5");
- st = new Thread(tg, new SimpleThread(1), "SimpleThread17");
- final String stString = st.toString();
- final String expected = "Thread[SimpleThread17,5,Test Group5]";
- assertTrue("Returned incorrect string: " + stString + "\t(expecting :"
- + expected + ")", stString.equals(expected));
- st.start();
- try {
- st.join();
- } catch (InterruptedException e) {
- }
- tg.destroy();
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "yield",
- args = {}
- )
- public void test_yield() {
-
- Counter [] countersNotYeld = new Counter[10];
-
- for(int i = 0; i < 10; i++) {
- countersNotYeld[i] = new Counter(false);
- }
- Counter countersYeld = new Counter(true);
- try {
- Thread.sleep(11000);
- } catch(InterruptedException ie) {}
-
- for(Counter c:countersNotYeld) {
- assertTrue(countersYeld.counter == c.counter);
- }
- }
-
- class Counter extends Thread {
- public int counter = 0;
- boolean isDoYield = false;
-
- public Counter(boolean isDoYield) {
- this.isDoYield = isDoYield;
- start();
- }
-
- public void run() {
- for(int i = 0; i < 10000; i++) {
- if(isDoYield)
- yield();
- counter ++;
- }
- }
- }
-
-
- /**
- * @tests java.lang.Thread#getAllStackTraces()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAllStackTraces",
- args = {}
- )
- public void test_getAllStackTraces() {
- Map<Thread, StackTraceElement[]> stMap = Thread.getAllStackTraces();
- assertNotNull(stMap);
- //TODO add security-based tests
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if(perm.getName().equals("modifyThreadGroup")) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- Thread.getAllStackTraces();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Thread#getDefaultUncaughtExceptionHandler
- * @tests java.lang.Thread#setDefaultUncaughtExceptionHandler
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setDefaultUncaughtExceptionHandler",
- args = {java.lang.Thread.UncaughtExceptionHandler.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDefaultUncaughtExceptionHandler",
- args = {}
- )
- })
- public void test_get_setDefaultUncaughtExceptionHandler() {
- class Handler implements UncaughtExceptionHandler {
- public void uncaughtException(Thread thread, Throwable ex) {
- }
- }
-
- final Handler handler = new Handler();
- Thread.setDefaultUncaughtExceptionHandler(handler);
- assertSame(handler, Thread.getDefaultUncaughtExceptionHandler());
-
- Thread.setDefaultUncaughtExceptionHandler(null);
- assertNull(Thread.getDefaultUncaughtExceptionHandler());
- //TODO add security-based tests
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if(perm.getName().
- equals("setDefaultUncaughtExceptionHandler")) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- st.setDefaultUncaughtExceptionHandler(handler);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Thread#getStackTrace()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getStackTrace",
- args = {}
- )
- public void test_getStackTrace() {
- StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
-
- assertNotNull(stackTrace);
-
- stack_trace_loop: {
- for (int i = 0; i < stackTrace.length; i++) {
- StackTraceElement e = stackTrace[i];
- if (getClass().getName().equals(e.getClassName())) {
- if ("test_getStackTrace".equals(e.getMethodName())) {
- break stack_trace_loop;
- }
- }
- }
- fail("class and method not found in stack trace");
- }
-
- //TODO add security-based tests
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if(perm.getName().
- equals("getStackTrace")) {
- throw new SecurityException();
- }
- }
- };
- st = new Thread();
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- st.getStackTrace();
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.lang.Thread#getState()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getState",
- args = {}
- )
- public void test_getState() {
- Thread.State state = Thread.currentThread().getState();
- assertNotNull(state);
- assertEquals(Thread.State.RUNNABLE, state);
-
- final Semaphore sem = new Semaphore(0);
- final Object lock = new Object();
- Thread th = new Thread() {
- @Override
- public void run() {
- while (!sem.hasQueuedThreads()) {}
- sem.release();
- while (run) {}
- try {
- sem.acquire();
- } catch (InterruptedException e) {
- fail("InterruptedException was thrown.");
- }
- synchronized (lock) {
- lock.equals(new Object());
- }
- synchronized (lock) {
- try {
- sem.release();
- lock.wait(Long.MAX_VALUE);
- } catch (InterruptedException e) {
- // expected
- }
- }
- }
- };
- assertEquals(Thread.State.NEW, th.getState());
- th.start();
- try {
- sem.acquire();
- } catch (InterruptedException e) {
- fail("InterruptedException was thrown.");
- }
- assertEquals(Thread.State.RUNNABLE, th.getState());
- run = false;
-
- while (!sem.hasQueuedThreads()){}
-
- assertEquals(Thread.State.WAITING, th.getState());
- synchronized (lock) {
- sem.release();
- long start = System.currentTimeMillis();
- while(start + 1000 > System.currentTimeMillis()) {}
- assertEquals(Thread.State.BLOCKED, th.getState());
- }
-
- try {
- sem.acquire();
- } catch (InterruptedException e) {
- fail("InterruptedException was thrown.");
- }
-
- synchronized (lock) {
- assertEquals(Thread.State.TIMED_WAITING, th.getState());
- th.interrupt();
- }
-
- try {
- th.join(1000);
- } catch(InterruptedException ie) {
- fail("InterruptedException was thrown.");
- }
- assertEquals(Thread.State.TERMINATED, th.getState());
- }
- boolean run = true;
-
- /**
- * @tests java.lang.Thread#getUncaughtExceptionHandler
- * @tests java.lang.Thread#setUncaughtExceptionHandler
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getUncaughtExceptionHandler",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setUncaughtExceptionHandler",
- args = {java.lang.Thread.UncaughtExceptionHandler.class}
- )
- })
- public void test_get_setUncaughtExceptionHandler() {
- class Handler implements UncaughtExceptionHandler {
- public void uncaughtException(Thread thread, Throwable ex) {
- }
- }
-
- final Handler handler = new Handler();
- Thread.currentThread().setUncaughtExceptionHandler(handler);
- assertSame(handler, Thread.currentThread().getUncaughtExceptionHandler());
-
- Thread.currentThread().setUncaughtExceptionHandler(null);
-
- //TODO add security-based tests
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkAccess(Thread t) {
- throw new SecurityException();
- }
- };
- st = new Thread();
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- st.setUncaughtExceptionHandler(handler);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- }
-
- /**
- * @tests java.lang.Thread#getId()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getId",
- args = {}
- )
- public void test_getId() {
- assertTrue("current thread's ID is not positive", Thread.currentThread().getId() > 0);
-
- //check all the current threads for positive IDs
- Map<Thread, StackTraceElement[]> stMap = Thread.getAllStackTraces();
- for (Thread thread : stMap.keySet()) {
- assertTrue("thread's ID is not positive: " + thread.getName(), thread.getId() > 0);
- }
- }
-
- /**
- * @tests java.lang.Thread#holdLock()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "holdsLock",
- args = {java.lang.Object.class}
- )
- public void test_holdsLock() {
- MonitoredClass monitor = new MonitoredClass();
-
- monitor.enterLocked();
- monitor.enterNonLocked();
-
- try {
- Thread.holdsLock(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- @Override
- protected void tearDown() {
- try {
- if (st != null)
- st.interrupt();
- } catch (Exception e) {
- }
- try {
- if (spinner != null)
- spinner.interrupt();
- } catch (Exception e) {
- }
- try {
- if (ct != null)
- ct.interrupt();
- } catch (Exception e) {
- }
-
- try {
- spinner = null;
- st = null;
- ct = null;
- System.runFinalization();
- } catch (Exception e) {
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThrowableTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThrowableTest.java
deleted file mode 100644
index 8a4d6e1..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThrowableTest.java
+++ /dev/null
@@ -1,413 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.PrintStream;
-import java.io.PrintWriter;
-
-@TestTargetClass(Throwable.class)
-public class ThrowableTest extends TestCase {
-
- /**
- * @tests java.lang.Throwable#Throwable()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Throwable",
- args = {}
- )
- public void test_Constructor() {
- Throwable e = new Throwable();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.Throwable#Throwable(java.lang.String)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Throwable",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
- })
- public void test_ConstructorLjava_lang_String() {
- Throwable e = new Throwable("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Throwable",
- args = {java.lang.String.class, java.lang.Throwable.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCause",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
- })
- public void test_ConstructorLStringLThrowable() {
- String message = "Test message";
- NullPointerException npe = new NullPointerException();
- Throwable thr = new Throwable(message, npe);
- assertEquals("message is incorrect.", message, thr.getMessage());
- assertEquals("cause is incorrect.", npe, thr.getCause());
-
- thr = new Throwable(null, npe);
- assertNull("message is not null.", thr.getMessage());
- assertEquals("cause is incorrect.", npe, thr.getCause());
-
- thr = new Throwable(message, null);
- assertEquals("message is incorrect.", message, thr.getMessage());
- assertNull("cause is not null.", thr.getCause());
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Throwable",
- args = {java.lang.Throwable.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCause",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
- })
- public void test_ConstructorLThrowable() {
-
- NullPointerException npe = new NullPointerException();
- Throwable thr = new Throwable(npe);
-
- assertEquals("Returned cause is incorrect.", npe, thr.getCause());
-
- thr = new Throwable((Throwable) null);
- assertNull("The cause is not null.", thr.getCause());
- }
-
- /**
- * @tests java.lang.Throwable#fillInStackTrace()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fillInStackTrace",
- args = {}
- )
- public void test_fillInStackTrace() {
- // Test for method java.lang.Throwable
- // java.lang.Throwable.fillInStackTrace()
- class Test implements Runnable {
- public int x;
-
- public Test(int x) {
- this.x = x;
- }
-
- public void anotherMethod() {
- if (true)
- throw new IndexOutOfBoundsException();
- }
-
- public void run() {
- if (x == 0)
- throw new IndexOutOfBoundsException();
- try {
- anotherMethod();
- } catch (IndexOutOfBoundsException e) {
- e.fillInStackTrace();
- throw e;
- }
- }
- }
- ByteArrayOutputStream bao = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(bao);
- try {
- new Test(0).run();
- } catch (Throwable e) {
- e.printStackTrace(ps);
- }
- ps.flush();
- String s = fixStacktrace(new String(bao.toByteArray(), 0, bao.size()));
-
- bao.reset();
- try {
- new Test(1).run();
- } catch (Throwable e) {
- e.printStackTrace(ps);
- }
- ps.close();
- String s2 = fixStacktrace(new String(bao.toByteArray(), 0, bao.size()));
- assertTrue("Invalid stackTrace? length: " + s2.length() + "\n" + s2, s2
- .length() > 300);
- assertTrue("Incorrect stackTrace printed: \n" + s2
- + "\n\nCompared with:\n" + s, s2.equals(s));
- }
-
- private String fixStacktrace(String trace) {
- // remove linenumbers
- StringBuffer sb = new StringBuffer();
- int lastIndex = 0;
- while (lastIndex < trace.length()) {
- int index = trace.indexOf('\n', lastIndex);
- if (index == -1)
- index = trace.length();
- String line = trace.substring(lastIndex, index);
- lastIndex = index + 1;
-
- index = line.indexOf("(");
- if (index > -1) {
- line = line.substring(0, index);
- }
- // Usually the construction of the exception is removed
- // however if running with the JIT, it may not be removed
- if (line.indexOf("java.lang.Throwable") > -1)
- continue;
- sb.append(line);
- sb.append('\n');
- }
- return sb.toString();
- }
-
- /**
- * @tests java.lang.Throwable#printStackTrace()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "printStackTrace",
- args = {}
- )
- public void test_printStackTrace() {
- // Test for method void java.lang.Throwable.printStackTrace()
- Throwable x = new ClassNotFoundException("A Test Message");
- ByteArrayOutputStream bao = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(bao);
- PrintStream err = System.err;
- System.setErr(ps);
- x.printStackTrace();
- System.setErr(err);
- ps.close();
- String s = new String(bao.toByteArray(), 0, bao.size());
- assertTrue("Incorrect stackTrace printed:\n" + s, s != null
- && s.length() > 400);
- }
-
- /**
- * @tests java.lang.Throwable#printStackTrace(java.io.PrintStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "printStackTrace",
- args = {java.io.PrintStream.class}
- )
- public void test_printStackTraceLjava_io_PrintStream() {
- // Test for method void
- // java.lang.Throwable.printStackTrace(java.io.PrintStream)
- ByteArrayOutputStream bao = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(bao);
- Throwable x = new java.net.UnknownHostException("A Message");
- x.printStackTrace(ps);
- ps.close();
- String s = new String(bao.toByteArray(), 0, bao.size());
- assertTrue("Incorrect stackTrace printed:\n" + s, s != null
- && s.length() > 400);
- }
-
- /**
- * @tests java.lang.Throwable#printStackTrace(java.io.PrintWriter)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "printStackTrace",
- args = {java.io.PrintWriter.class}
- )
- public void test_printStackTraceLjava_io_PrintWriter() {
- // Test for method void
- // java.lang.Throwable.printStackTrace(java.io.PrintWriter)
- // SM
- ByteArrayOutputStream bao = new ByteArrayOutputStream();
- PrintWriter pw = new PrintWriter(bao);
- Throwable x = new java.net.UnknownHostException("A Message");
- x.printStackTrace(pw);
- pw.close();
- String s = new String(bao.toByteArray(), 0, bao.size());
- assertTrue("Incorrect stackTrace printed:\n" + s, s != null
- && s.length() > 400);
- }
-
- /**
- * @tests java.lang.Throwable#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- Throwable e = new Throwable("Throw");
- assertEquals("java.lang.Throwable: Throw", e.toString());
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalizedMessage",
- args = {}
- )
- public void test_getLocalizedMessage() {
- String testMessage = "Test message";
- Throwable e = new Throwable(testMessage);
- assertEquals("Returned incorrect localized message.",
- testMessage, e.getLocalizedMessage());
-
- TestThrowable tt = new TestThrowable(testMessage);
- assertEquals("localized message", tt.getLocalizedMessage());
- }
-
- class TestThrowable extends Throwable {
-
- public TestThrowable(String message) {
- super(message);
- }
-
- public String getLocalizedMessage() {
- return "localized message";
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getStackTrace",
- args = {}
- )
- public void test_getStackTrace() {
- String message = "Test message";
- NullPointerException npe = new NullPointerException();
- Throwable thr = new Throwable(message, npe);
- StackTraceElement[] ste = thr.getStackTrace();
- assertNotNull("Returned stack trace is empty", ste.length != 0);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "initCause",
- args = {java.lang.Throwable.class}
- )
- public void test_initCause() {
- String message = "Test message";
- NullPointerException npe = new NullPointerException();
- IllegalArgumentException iae = new IllegalArgumentException();
- Throwable thr = new Throwable();
- thr.initCause(iae);
- assertEquals("getCause returns incorrect cause.", iae, thr.getCause());
-
- thr = new Throwable("message");
- thr.initCause(npe);
- assertEquals("getCause returns incorrect cause.", npe, thr.getCause());
-
- thr = new Throwable(message, npe);
- try {
- thr.initCause(iae);
- fail("IllegalStateException was not thrown.");
- } catch(IllegalStateException ise) {
- //expected
- }
-
- thr = new Throwable(npe);
- try {
- thr.initCause(iae);
- fail("IllegalStateException was not thrown.");
- } catch(IllegalStateException ise) {
- //expected
- }
-
- thr = new Throwable();
- try {
- thr.initCause(thr);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException ise) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setStackTrace",
- args = {java.lang.StackTraceElement[].class}
- )
- public void test_setStackTrace() {
- NullPointerException npe = new NullPointerException();
- Throwable thr = new Throwable(npe);
- StackTraceElement[] ste = thr.getStackTrace();
- Throwable thr1 = new Throwable(npe);
- thr1.setStackTrace(ste);
- assertEquals(ste.length, thr1.getStackTrace().length);
-
- try {
- thr.setStackTrace(null);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException np) {
- //expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TypeNotPresentExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TypeNotPresentExceptionTest.java
deleted file mode 100644
index 4b01a98..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TypeNotPresentExceptionTest.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/* 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(TypeNotPresentException.class)
-public class TypeNotPresentExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.TypeNotPresentException.TypeNotPresentException(String, Throwable)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TypeNotPresentException",
- args = {java.lang.String.class, java.lang.Throwable.class}
- )
- public void test_constructorLjava_lang_StringLjava_lang_Throwable() {
- TypeNotPresentException e = new TypeNotPresentException(null, null);
- assertNotNull(e);
- String m = e.getMessage();
- assertNotNull(m);
-
- e = new TypeNotPresentException(getClass().getName(), null);
- assertNotNull(e);
- m = e.getMessage();
- assertNotNull(m);
-
- NullPointerException npe = new NullPointerException();
- e = new TypeNotPresentException(getClass().getName(), npe);
- assertNotNull(e.getMessage());
- assertSame(npe, e.getCause());
- }
-
- /**
- * @tests java.lang.TypeNotPresentException.typeName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "typeName",
- args = {}
- )
- public void test_typeName() {
- TypeNotPresentException e = new TypeNotPresentException(null, null);
- assertNull(e.typeName());
-
- e = new TypeNotPresentException(getClass().getName(), null);
- assertEquals(getClass().getName(), e.typeName());
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnknownErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnknownErrorTest.java
deleted file mode 100644
index a894d7e..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnknownErrorTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(UnknownError.class)
-public class UnknownErrorTest extends TestCase {
-
- /**
- * @tests java.lang.UnknownError#UnknownError()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnknownError",
- args = {}
- )
- public void test_Constructor() {
- UnknownError e = new UnknownError();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.UnknownError#UnknownError(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnknownError",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- UnknownError e = new UnknownError("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsatisfiedLinkErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsatisfiedLinkErrorTest.java
deleted file mode 100644
index 39a8855..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsatisfiedLinkErrorTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(UnsatisfiedLinkError.class)
-public class UnsatisfiedLinkErrorTest extends TestCase {
-
- /**
- * @tests java.lang.UnsatisfiedLinkError#UnsatisfiedLinkError()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnsatisfiedLinkError",
- args = {}
- )
- public void test_Constructor() {
- UnsatisfiedLinkError e = new UnsatisfiedLinkError();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.UnsatisfiedLinkError#UnsatisfiedLinkError(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnsatisfiedLinkError",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- UnsatisfiedLinkError e = new UnsatisfiedLinkError("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsupportedClassVersionErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsupportedClassVersionErrorTest.java
deleted file mode 100644
index c1f3ee9..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsupportedClassVersionErrorTest.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(UnsupportedClassVersionError.class)
-public class UnsupportedClassVersionErrorTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnsupportedClassVersionError",
- args = {}
- )
- public void test_Constructor() {
- UnsupportedClassVersionError ucve = new UnsupportedClassVersionError();
- assertNull(ucve.getMessage());
- assertNull(ucve.getCause());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnsupportedClassVersionError",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLString() {
- String message = "Test message";
- UnsupportedClassVersionError ucve = new UnsupportedClassVersionError(
- message);
- assertEquals(message, ucve.getMessage());
- ucve = new UnsupportedClassVersionError(null);
- assertNull(ucve.getMessage());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsupportedOperationExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsupportedOperationExceptionTest.java
deleted file mode 100644
index 73176bb..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsupportedOperationExceptionTest.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-@TestTargetClass(UnsupportedOperationException.class)
-public class UnsupportedOperationExceptionTest extends TestCase {
-
- /**
- * @tests java.lang.UnsupportedOperationException#UnsupportedOperationException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnsupportedOperationException",
- args = {}
- )
- public void test_Constructor() {
- UnsupportedOperationException e = new UnsupportedOperationException();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.UnsupportedOperationException#UnsupportedOperationException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnsupportedOperationException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- UnsupportedOperationException e = new UnsupportedOperationException("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnsupportedOperationException",
- args = {java.lang.String.class, java.lang.Throwable.class}
- )
- public void test_ConstructorLStringLThrowable() {
- String message = "Test message";
- NullPointerException npe = new NullPointerException();
- UnsupportedOperationException uoe = new UnsupportedOperationException(message, npe);
- assertEquals(message, uoe.getMessage());
- assertEquals(npe, uoe.getCause());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnsupportedOperationException",
- args = {java.lang.Throwable.class}
- )
- public void test_ConstructorLThrowable(){
- NullPointerException npe = new NullPointerException();
- UnsupportedOperationException uoe = new UnsupportedOperationException(npe);
- assertEquals(npe, uoe.getCause());
- uoe = new UnsupportedOperationException((Throwable) null);
- assertNull("The cause is not null.", uoe.getCause());
- }
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new UnsupportedOperationException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this,
- new UnsupportedOperationException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/VerifyErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/VerifyErrorTest.java
deleted file mode 100644
index 3115698..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/VerifyErrorTest.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(VerifyError.class)
-public class VerifyErrorTest extends TestCase {
-
- /**
- * @tests java.lang.VerifyError#VerifyError()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "VerifyError",
- args = {}
- )
- public void test_Constructor() {
- VerifyError e = new VerifyError();
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.VerifyError#VerifyError(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "VerifyError",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- VerifyError e = new VerifyError("fixture");
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/VirtualMachineErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/VirtualMachineErrorTest.java
deleted file mode 100644
index b998b98..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/VirtualMachineErrorTest.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("serial")
-@TestTargetClass(VirtualMachineError.class)
-public class VirtualMachineErrorTest extends TestCase {
-
- /**
- * @tests java.lang.VirtualMachineError#VirtualMachineError()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "VirtualMachineError",
- args = {}
- )
- public void test_Constructor() {
- VirtualMachineError e = new VirtualMachineError() {};
- assertNull(e.getMessage());
- assertNull(e.getLocalizedMessage());
- assertNull(e.getCause());
- }
-
- /**
- * @tests java.lang.VirtualMachineError#VirtualMachineError(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "VirtualMachineError",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- VirtualMachineError e = new VirtualMachineError("fixture") {};
- assertEquals("fixture", e.getMessage());
- assertNull(e.getCause());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/AllTests.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/AllTests.java
deleted file mode 100644
index 91ca3a4..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/AllTests.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.net;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-import junit.textui.TestRunner;
-
-/**
- * Listing of all the tests that are to be run.
- */
-public class AllTests {
-
- public static void run() {
- TestRunner.main(new String[] { AllTests.class.getName() });
- }
-
- public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.net");
-
- // add net testsuites here
- suite.addTestSuite(ContentHandlerTest.class);
- suite.addTestSuite(ContentHandlerFactoryTest.class);
- suite.addTestSuite(HttpRetryExceptionTest.class);
- suite.addTestSuite(HttpURLConnectionTest.class);
- suite.addTestSuite(Inet4AddressTest.class);
- suite.addTestSuite(Inet6AddressTest.class);
- suite.addTestSuite(InetAddressTest.class);
- suite.addTestSuite(InetSocketAddressTest.class);
- suite.addTestSuite(URITest.class);
- suite.addTestSuite(URLConnectionTest.class);
- suite.addTestSuite(URLEncoderTest.class);
- suite.addTestSuite(URLTest.class);
-
- return suite;
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerFactoryTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerFactoryTest.java
deleted file mode 100644
index e03c14a..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerFactoryTest.java
+++ /dev/null
@@ -1,169 +0,0 @@
-package org.apache.harmony.luni.tests.java.net;
-
-import dalvik.annotation.BrokenTest;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import tests.support.Support_Configuration;
-
-import java.io.IOException;
-import java.lang.reflect.Field;
-import java.net.ContentHandler;
-import java.net.ContentHandlerFactory;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLConnection;
-
-@TestTargetClass(ContentHandlerFactory.class)
-public class ContentHandlerFactoryTest extends TestCase {
-
- ContentHandlerFactory oldFactory = null;
- Field factoryField = null;
-
- boolean isTestable = false;
-
- boolean isGetContentCalled = false;
- boolean isCreateContentHandlerCalled = false;
-
- @TestTargets ({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "createContentHandler",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies positive case, and java.lang.Error.",
- clazz = URLConnection.class,
- method = "setContentHandlerFactory",
- args = { ContentHandlerFactory.class }
- )
- })
- @BrokenTest("This test affects tests that are run after this one." +
- " The reason are side effects due to caching in URLConnection." +
- " Maybe this test has to be marked NOT_FEASIBLE.")
- public void test_createContentHandler() throws IOException {
-
- TestContentHandlerFactory factory = new TestContentHandlerFactory();
-
- if(isTestable) {
-
- assertFalse(isCreateContentHandlerCalled);
-
- URL url = new URL("http://" +
- Support_Configuration.SpecialInetTestAddress);
-
- URLConnection.setContentHandlerFactory(factory);
-
- URLConnection con = url.openConnection();
-
- try {
- con.getContent();
- assertTrue(isCreateContentHandlerCalled);
- assertTrue(isGetContentCalled);
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
-
- }
-
- isGetContentCalled = false;
-
- try {
- con.getContent(new Class[] {});
- assertTrue(isGetContentCalled);
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
-
- }
-
- try {
- con.setContentHandlerFactory(factory);
- fail("java.lang.Error was not thrown.");
- } catch(java.lang.Error e) {
- //expected
- }
-
- try {
- con.setContentHandlerFactory(null);
- fail("java.lang.Error was not thrown.");
- } catch(java.lang.Error e) {
- //expected
- }
-
- } else {
- ContentHandler ch = factory.createContentHandler("text/plain");
- URL url;
- try {
- url = new URL("http://" +
- Support_Configuration.SpecialInetTestAddress);
- assertNotNull(ch.getContent(url.openConnection()));
- } catch (MalformedURLException e) {
- fail("MalformedURLException was thrown: " + e.getMessage());
- } catch (IOException e) {
- fail("IOException was thrown.");
- }
- }
- }
-
- public void setUp() {
- Field [] fields = URLConnection.class.getDeclaredFields();
- int counter = 0;
- for (Field field : fields) {
- if (ContentHandlerFactory.class.equals(field.getType())) {
- counter++;
- factoryField = field;
- }
- }
-
- if(counter == 1) {
-
- isTestable = true;
-
- factoryField.setAccessible(true);
- try {
- oldFactory = (ContentHandlerFactory) factoryField.get(null);
- } catch (IllegalArgumentException e) {
- fail("IllegalArgumentException was thrown during setUp: "
- + e.getMessage());
- } catch (IllegalAccessException e) {
- fail("IllegalAccessException was thrown during setUp: "
- + e.getMessage());
- }
- }
- }
-
- public void tearDown() {
- if(isTestable) {
- try {
- factoryField.set(null, oldFactory);
- } catch (IllegalArgumentException e) {
- fail("IllegalArgumentException was thrown during tearDown: "
- + e.getMessage());
- } catch (IllegalAccessException e) {
- fail("IllegalAccessException was thrown during tearDown: "
- + e.getMessage());
- }
- }
- }
-
- public class TestContentHandler extends ContentHandler {
-
- public Object getContent(URLConnection u) {
- isGetContentCalled = true;
- return null;
- }
- }
-
- public class TestContentHandlerFactory implements ContentHandlerFactory {
-
- public ContentHandler createContentHandler(String mimetype) {
- isCreateContentHandlerCalled = true;
- return new TestContentHandler();
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerTest.java
deleted file mode 100644
index 6b1957a..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerTest.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.IOException;
-import java.net.ContentHandler;
-import java.net.URL;
-import java.net.URLConnection;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(ContentHandler.class)
-public class ContentHandlerTest extends TestCase {
-
- /**
- * @tests java.net.ContentHandler#getContent(java.net.URLConnection,
- * java.lang.Class[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getContent",
- args = {java.net.URLConnection.class, java.lang.Class[].class}
- )
- public void test_getContent() throws IOException {
- URLConnection conn = new URL("http://www.apache.org").openConnection();
- Class[] classes = { Foo.class, String.class, };
- ContentHandler handler = new ContentHandlerImpl();
- ((ContentHandlerImpl) handler).setContent(new Foo());
- Object content = handler.getContent(conn, classes);
- assertEquals("Foo", ((Foo) content).getFoo());
-
- ((ContentHandlerImpl) handler).setContent(new FooSub());
- content = handler.getContent(conn, classes);
- assertEquals("FooSub", ((Foo) content).getFoo());
-
- Class[] classes2 = { FooSub.class, String.class, };
- ((ContentHandlerImpl) handler).setContent(new Foo());
- content = handler.getContent(conn, classes2);
- assertNull(content);
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getContent",
- args = {java.net.URLConnection.class}
- )
- public void test_getContentLURLConnection() throws IOException {
- URLConnection conn = new URL("http://www.apache.org").openConnection();
- Class[] classes = { Foo.class, String.class, };
- ContentHandler handler = new ContentHandlerImpl();
- ((ContentHandlerImpl) handler).setContent(new Foo());
- Object content = handler.getContent(conn);
- assertEquals("Foo", ((Foo) content).getFoo());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ContentHandler",
- args = {}
- )
- public void test_Constructor() {
- ContentHandlerImpl ch = new ContentHandlerImpl();
- ch.setContent(new Object());
- }
-}
-
-class ContentHandlerImpl extends ContentHandler {
-
- private Object content;
-
- @Override
- public Object getContent(URLConnection uConn) throws IOException {
- return content;
- }
-
- public void setContent(Object content) {
- this.content = content;
- }
-}
-
-class Foo {
- public String getFoo() {
- return "Foo";
- }
-}
-
-class FooSub extends Foo {
- public String getFoo() {
- return "FooSub";
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/HttpRetryExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/HttpRetryExceptionTest.java
deleted file mode 100644
index 3e3cafe..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/HttpRetryExceptionTest.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.Serializable;
-import java.net.HttpRetryException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(HttpRetryException.class)
-public class HttpRetryExceptionTest extends TestCase {
-
- private static final String LOCATION = "Http test"; //$NON-NLS-1$
-
- private static final String DETAIL = "detail"; //$NON-NLS-1$
-
- // comparator for HttpRetryException objects
- private static final SerializableAssert comparator = new SerializableAssert() {
- public void assertDeserialized(Serializable reference, Serializable test) {
-
- HttpRetryException ref = (HttpRetryException) reference;
- HttpRetryException tst = (HttpRetryException) test;
-
- assertEquals("getLocation", ref.getLocation(), tst.getLocation());
- assertEquals("responseCode", ref.responseCode(), tst.responseCode());
- assertEquals("getReason", ref.getReason(), tst.getReason());
- assertEquals("getMessage", ref.getMessage(), tst.getMessage());
- }
- };
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Checks serialization",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
- SerializationTest.verifySelf(new HttpRetryException(DETAIL, 100,
- LOCATION), comparator);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Checks serialization",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
- SerializationTest.verifyGolden(this, new HttpRetryException(DETAIL,
- 100, LOCATION), comparator);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/HttpURLConnectionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/HttpURLConnectionTest.java
deleted file mode 100644
index 29d26da..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/HttpURLConnectionTest.java
+++ /dev/null
@@ -1,1144 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.net;
-
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.CacheRequest;
-import java.net.CacheResponse;
-import java.net.DatagramSocket;
-import java.net.HttpURLConnection;
-import java.net.MalformedURLException;
-import java.net.ProtocolException;
-import java.net.ResponseCache;
-import java.net.SocketException;
-import java.net.SocketPermission;
-import java.net.URI;
-import java.net.URL;
-import java.net.URLConnection;
-import java.security.Permission;
-import java.util.ArrayList;
-import java.util.Hashtable;
-import java.util.List;
-import java.util.Map;
-
-import tests.support.Support_Configuration;
-
-@TestTargetClass(HttpURLConnection.class)
-public class HttpURLConnectionTest extends junit.framework.TestCase {
-
- final String unknownURL = "http://unknown.host";
-
- URL url;
-
- HttpURLConnection uc;
-
- private boolean isGetCalled;
-
- private boolean isPutCalled;
-
- private boolean isCacheWriteCalled;
-
- private boolean isAbortCalled;
-
- private Map<String, List<String>> mockHeaderMap;
-
- private InputStream mockIs = new MockInputStream();
-
- /**
- * @tests java.net.HttpURLConnection#getResponseCode()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Verifies only successful response.",
- method = "getResponseCode",
- args = {}
- )
- public void test_getResponseCode() {
- try {
- uc.connect();
- assertEquals("Wrong response", 200, uc.getResponseCode());
- } catch (IOException e) {
- fail("Unexpected exception : " + e.getMessage());
- }
- try {
- URL url = new URL(unknownURL);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.getResponseCode();
- fail("IOException was not thrown.");
- } catch(IOException e) {
- //expected
- }
- }
-
- /**
- * @tests java.net.HttpURLConnection#getResponseMessage()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Verifies only successful response message.",
- method = "getResponseMessage",
- args = {}
- )
- public void test_getResponseMessage() {
- try {
- uc.connect();
- assertTrue("Wrong response: " + uc.getResponseMessage(), uc
- .getResponseMessage().equals("OK"));
- } catch (IOException e) {
- fail("Unexpected exception : " + e.getMessage());
- }
-
- try {
- URL url = new URL(unknownURL);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.connect();
- conn.getResponseMessage();
- fail("IOException was not thrown.");
- } catch(IOException e) {
- //expected
- }
- }
-
- /**
- * @tests java.net.HttpURLConnection#getHeaderFields()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getHeaderFields",
- args = {}
- )
- public void test_getHeaderFields() throws Exception {
- url = new URL("http://" + Support_Configuration.testURL);
- uc = (HttpURLConnection) url.openConnection();
- try {
- uc.getInputStream();
- } catch (IOException e) {
- fail();
- }
- Map headers = uc.getHeaderFields();
- List list = (List) headers.get("Content-Length");
- if (list == null) {
- list = (List) headers.get("content-length");
- }
- assertNotNull(list);
-
- // content-length should always appear
- String contentLength = (String) list.get(0);
- assertNotNull(contentLength);
-
- // there should be at least 2 headers
- assertTrue(headers.size() > 1);
-
- try {
- // the map should be unmodifiable
- headers.put("hi", "bye");
- fail();
- } catch (UnsupportedOperationException e) {
- }
-
- try {
- // the list should be unmodifiable
- list.set(0, "whatever");
- fail();
- } catch (UnsupportedOperationException e) {
- }
- }
-
- /**
- * @tests java.net.HttpURLConnection#getRequestProperties()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getRequestProperties",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "setRequestProperty",
- args = {String.class, String.class}
- )
- })
- public void test_getRequestProperties() {
- uc.setRequestProperty("whatever", "you like");
- Map headers = uc.getRequestProperties();
-
- List newHeader = (List) headers.get("whatever");
- assertNotNull(newHeader);
-
- assertEquals("you like", newHeader.get(0));
-
- try {
- // the map should be unmodifiable
- headers.put("hi", "bye");
- fail();
- } catch (UnsupportedOperationException e) {
- }
- }
-
- /**
- * @tests java.net.HttpURLConnection#getRequestProperty(String)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getRequestProperty",
- args = {String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Exception test verification.",
- method = "setRequestProperty",
- args = {String.class, String.class}
- )
- })
- public void test_getRequestPropertyLjava_lang_String_BeforeConnected()
- throws MalformedURLException, IOException {
- uc.setRequestProperty("whatever", "you like"); //$NON-NLS-1$//$NON-NLS-2$
- String res = uc.getRequestProperty("whatever"); //$NON-NLS-1$
- assertEquals("you like", res); //$NON-NLS-1$
-
- uc.setRequestProperty("", "you like"); //$NON-NLS-1$//$NON-NLS-2$
- res = uc.getRequestProperty(""); //$NON-NLS-1$
- assertEquals("you like", res); //$NON-NLS-1$
-
- uc.setRequestProperty("", null); //$NON-NLS-1$
- res = uc.getRequestProperty(""); //$NON-NLS-1$
- assertEquals(null, res);
- try {
- uc.setRequestProperty(null, "you like"); //$NON-NLS-1$
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.net.HttpURLConnection#getRequestProperty(String)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalStateException and null as a parameter.",
- method = "setRequestProperty",
- args = {String.class, String.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalStateException and null as a parameter.",
- method = "getRequestProperty",
- args = {String.class}
- )
- })
- public void test_getRequestPropertyLjava_lang_String_AfterConnected()
- throws IOException {
- uc.connect();
- try {
- uc.setRequestProperty("whatever", "you like"); //$NON-NLS-1$//$NON-NLS-2$
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
- // expected
- }
- try {
- uc.setRequestProperty(null, "you like"); //$NON-NLS-1$
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
- // expected
- }
- String res = uc.getRequestProperty("whatever"); //$NON-NLS-1$
- assertEquals(null, res);
- res = uc.getRequestProperty(null);
- assertEquals(null, res);
- try {
- uc.getRequestProperties();
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
- // expected
- }
- }
-
- /**
- * @tests java.net.HttpURLConnection#setFixedLengthStreamingMode_I()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setFixedLengthStreamingMode",
- args = {int.class}
- )
- public void test_setFixedLengthStreamingModeI() throws Exception {
- try {
- uc.setFixedLengthStreamingMode(-1);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // correct
- }
- uc.setFixedLengthStreamingMode(0);
- uc.setFixedLengthStreamingMode(1);
- try {
- uc.setChunkedStreamingMode(1);
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // correct
- }
- uc.connect();
- try {
- uc.setFixedLengthStreamingMode(-1);
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // correct
- }
- try {
- uc.setChunkedStreamingMode(-1);
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // correct
- }
- MockHttpConnection mock = new MockHttpConnection(url);
- assertEquals(-1, mock.getFixedLength());
- mock.setFixedLengthStreamingMode(0);
- assertEquals(0, mock.getFixedLength());
- mock.setFixedLengthStreamingMode(1);
- assertEquals(1, mock.getFixedLength());
- mock.setFixedLengthStreamingMode(0);
- assertEquals(0, mock.getFixedLength());
- }
-
- /**
- * @tests java.net.HttpURLConnection#setChunkedStreamingMode_I()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setChunkedStreamingMode",
- args = {int.class}
- )
- public void test_setChunkedStreamingModeI() throws Exception {
- uc.setChunkedStreamingMode(0);
- uc.setChunkedStreamingMode(-1);
- uc.setChunkedStreamingMode(-2);
-
- try {
- uc.setFixedLengthStreamingMode(-1);
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // correct
- }
- try {
- uc.setFixedLengthStreamingMode(1);
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // correct
- }
- uc.connect();
- try {
- uc.setFixedLengthStreamingMode(-1);
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // correct
- }
- try {
- uc.setChunkedStreamingMode(1);
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // correct
- }
- MockHttpConnection mock = new MockHttpConnection(url);
- assertEquals(-1, mock.getChunkLength());
- mock.setChunkedStreamingMode(-1);
- int defaultChunk = mock.getChunkLength();
- assertTrue(defaultChunk > 0);
- mock.setChunkedStreamingMode(0);
- assertEquals(mock.getChunkLength(), defaultChunk);
- mock.setChunkedStreamingMode(1);
- assertEquals(1, mock.getChunkLength());
- }
-
- /**
- * @tests java.net.HttpURLConnection#setFixedLengthStreamingMode_I()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setFixedLengthStreamingMode",
- args = {int.class}
- )
- public void test_setFixedLengthStreamingModeI_effect() throws Exception {
- String posted = "just a test";
- java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url
- .openConnection();
- conn.setDoOutput(true);
- conn.setRequestMethod("POST");
- conn.setFixedLengthStreamingMode(posted.length() - 1);
- assertNull(conn.getRequestProperty("Content-length"));
- conn.setRequestProperty("Content-length", String.valueOf(posted
- .length()));
- assertEquals(String.valueOf(posted.length()), conn
- .getRequestProperty("Content-length"));
- OutputStream out = conn.getOutputStream();
- try {
- out.write(posted.getBytes());
- fail("should throw IOException");
- } catch (IOException e) {
- // correct, too many bytes written
- }
- try {
- out.close();
- fail("should throw IOException");
- } catch (IOException e) {
- // correct, too many bytes written
- }
- }
-
- /**
- * @tests java.net.HttpURLConnection#setChunkedStreamingMode_I()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setChunkedStreamingMode",
- args = {int.class}
- )
- public void test_setChunkedStreamingModeI_effect() throws Exception {
- String posted = "just a test";
- // for test, use half length of the string
- int chunkSize = posted.length() / 2;
- java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url
- .openConnection();
- conn.setDoOutput(true);
- conn.setRequestMethod("POST");
- conn.setChunkedStreamingMode(chunkSize);
- assertNull(conn.getRequestProperty("Transfer-Encoding"));
- // does not take effect
- conn.setRequestProperty("Content-length", String.valueOf(posted
- .length() - 1));
- assertEquals(conn.getRequestProperty("Content-length"), String
- .valueOf(posted.length() - 1));
- OutputStream out = conn.getOutputStream();
- // no error occurs
- out.write(posted.getBytes());
- out.close();
- // no assert here, pass if no exception thrown
- assertTrue(conn.getResponseCode() > 0);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Simple test.",
- method = "getOutputStream",
- args = {}
- )
- public void test_getOutputStream_afterConnection() throws Exception {
- uc.setDoOutput(true);
- uc.connect();
- assertNotNull(uc.getOutputStream());
- }
-
- /**
- * @tests java.net.URLConnection#setUseCaches() and its real implementation
- * in HttpURLConnection using GetInputStream() and Connect()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "using GetInputStream() and Connect()",
- method = "setUseCaches",
- args = {boolean.class}
- )
- public void test_UseCache_HttpURLConnection_Connect_GetInputStream()
- throws Exception {
- // set cache before URLConnection created, or it does not take effect
- ResponseCache rc = new MockNonCachedResponseCache();
- ResponseCache.setDefault(rc);
- uc = (HttpURLConnection) url.openConnection();
- assertFalse(isGetCalled);
- uc.setUseCaches(true);
- uc.setDoInput(true);
- uc.connect();
- assertTrue(isGetCalled);
- assertFalse(isPutCalled);
- InputStream is = uc.getInputStream();
- assertTrue(isPutCalled);
- is.close();
- ((HttpURLConnection) uc).disconnect();
- }
-
- /**
- * @tests java.net.URLConnection#setUseCaches() and its real implementation
- * in HttpURLConnection using GetOutputStream() and Connect()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "using GetOutputStream() and Connect()",
- method = "setUseCaches",
- args = {boolean.class}
- )
- public void test_UseCache_HttpURLConnection_Connect_GetOutputStream()
- throws Exception {
- // set cache before URLConnection created, or it does not take effect
- ResponseCache rc = new MockNonCachedResponseCache();
- ResponseCache.setDefault(rc);
- uc.setUseCaches(true);
- URLConnection uc = url.openConnection();
- uc.setDoOutput(true);
- assertFalse(isGetCalled);
- uc.connect();
- assertTrue(isGetCalled);
- assertFalse(isPutCalled);
- OutputStream os = uc.getOutputStream();
- assertFalse(isPutCalled);
- os.close();
- ((HttpURLConnection) uc).disconnect();
- }
-
- /**
- * @tests java.net.URLConnection#setUseCaches() and its real implementation
- * in HttpURLConnection using GetOutputStream()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "real implementation\n in HttpURLConnection using GetOutputStream()",
- method = "setUseCaches",
- args = {boolean.class}
- )
- public void test_UseCache_HttpURLConnection_GetOutputStream()
- throws Exception {
- // set cache before URLConnection created, or it does not take effect
- ResponseCache rc = new MockNonCachedResponseCache();
- ResponseCache.setDefault(rc);
- uc = (HttpURLConnection) url.openConnection();
- assertFalse(isGetCalled);
- uc.setDoOutput(true);
- uc.setUseCaches(true);
- OutputStream os = uc.getOutputStream();
- assertTrue(isGetCalled);
- assertFalse(isPutCalled);
- os.write(1);
- os.flush();
- os.close();
- ((HttpURLConnection) uc).getResponseCode();
- assertTrue(isGetCalled);
- // assertTrue(isPutCalled);
- isGetCalled = false;
- isPutCalled = false;
- //InputStream is = uc.getInputStream();
- //assertFalse(isGetCalled);
- //assertFalse(isPutCalled);
- //is.close();
- ((HttpURLConnection) uc).disconnect();
- }
-
- /**
- * @tests java.net.URLConnection#setUseCaches() and its real implementation
- * in HttpURLConnection using GetInputStream()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "real implementation in HttpURLConnection using GetInputStream()",
- method = "setUseCaches",
- args = {boolean.class}
- )
- public void test_UseCache_HttpURLConnection_GetInputStream()
- throws Exception {
- // set cache before URLConnection created, or it does not take effect
- ResponseCache rc = new MockNonCachedResponseCache();
- ResponseCache.setDefault(rc);
- URLConnection uc = url.openConnection();
- assertFalse(isGetCalled);
- uc.setDoOutput(true);
- uc.setUseCaches(true);
- InputStream is = uc.getInputStream();
- assertTrue(isGetCalled);
- assertTrue(isPutCalled);
- ((HttpURLConnection) uc).getResponseCode();
- is.close();
- ((HttpURLConnection) uc).disconnect();
- }
-
- /**
- * @tests java.net.URLConnection#setUseCaches() and its real implementation
- * in HttpURLConnection using a MockResponseCache returns cache of
- * null
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "MockResponseCache returns cache null",
- method = "setUseCaches",
- args = {boolean.class}
- )
- @KnownFailure("getInputStream doesn't call get method of cache")
- public void test_UseCache_HttpURLConnection_NonCached() throws IOException {
- ResponseCache.setDefault(new MockNonCachedResponseCache());
- uc = (HttpURLConnection) url.openConnection();
-
- // default useCaches is true
- assertTrue(uc.getUseCaches());
- uc.setDoInput(true);
- uc.connect();
-
- // make sure ResponseCache.get/put is called
- isGetCalled = false;
- isPutCalled = false;
- InputStream is = uc.getInputStream();
- assertFalse(is instanceof MockInputStream);
- assertTrue(isGetCalled);
- assertTrue(isPutCalled);
-
- // make sure protocol handler has tried to write to cache.
- isCacheWriteCalled = false;
- is.read();
- assertTrue(isCacheWriteCalled);
-
- // make sure protocol handler has tried to write to cache.
- isCacheWriteCalled = false;
- byte[] buf = new byte[1];
- is.read(buf);
- assertTrue(isCacheWriteCalled);
-
- // make sure protocol handler has tried to write to cache.
- isCacheWriteCalled = false;
- buf = new byte[1];
- is.read(buf, 0, 1);
- assertTrue(isCacheWriteCalled);
-
- // make sure protocol handler has tried to call abort.
- isAbortCalled = false;
- is.close();
- assertTrue(isAbortCalled);
- uc.disconnect();
- }
-
- /**
- * @tests java.net.URLConnection#setUseCaches() and its real implementation
- * in HttpURLConnection using a MockResponseCache returns a mock
- * cache
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "test default, and implementation with MockResponseCache",
- method = "setUseCaches",
- args = {boolean.class}
- )
- public void test_UseCache_HttpURLConnection_Cached() throws IOException {
- ResponseCache.setDefault(new MockCachedResponseCache());
- URL u = new URL("http://" + Support_Configuration.SpecialInetTestAddress);
- HttpURLConnection uc = (HttpURLConnection) u.openConnection();
-
- // default useCaches is true
- assertTrue(uc.getUseCaches());
-
- // make sure ResponseCache.get/put is called
- isGetCalled = false;
- isPutCalled = false;
- InputStream is = uc.getInputStream();
- assertEquals(4711, is.read());
- assertTrue(isGetCalled);
-
- // make sure protocol handler doesn't try to write to cache, since
- // it has been in cache already.
- isCacheWriteCalled = false;
- is.read();
- assertFalse(isCacheWriteCalled);
-
- // make sure protocol handler doesn't try to write to cache, since
- // it has been in cache already.
- isCacheWriteCalled = false;
- byte[] buf = new byte[1];
- is.read(buf);
- assertFalse(isCacheWriteCalled);
-
- // make sure protocol handler doesn't try to write to cache, since
- // it has been in cache already.
- isCacheWriteCalled = false;
- buf = new byte[1];
- is.read(buf, 0, 1);
- assertFalse(isCacheWriteCalled);
-
- // make sure abort is not called since no write is performed
- isAbortCalled = false;
- is.close();
- assertFalse(isAbortCalled);
- uc.disconnect();
- }
-
- /**
- * @tests java.net.URLConnection#setUseCaches() and its real implementation
- * in HttpURLConnection using getHeaderFields()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "tests header fields written to cache with getHeaderFields.",
- method = "setUseCaches",
- args = {boolean.class}
- )
- public void test_UseCache_HttpURLConnection_getHeaderFields()
- throws IOException {
- ResponseCache.setDefault(new MockCachedResponseCache());
- URL u = new URL("http://" + Support_Configuration.SpecialInetTestAddress);
- HttpURLConnection uc = (HttpURLConnection) u.openConnection();
- Map<String, List<String>> headerMap = uc.getHeaderFields();
- assertTrue(isGetCalled);
- assertFalse(isPutCalled);
- assertEquals(mockHeaderMap, headerMap);
- assertEquals(4711, uc.getInputStream().read());
- uc.disconnect();
- }
-
- /**
- * @tests java.net.URLConnection#setUseCaches() and its real implementation
- * in HttpURLConnection using GetOutputStream()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "setUseCaches",
- args = {boolean.class}
- )
- public void test_UseCache_HttpURLConnection_NoCached_GetOutputStream()
- throws Exception {
- ResponseCache.setDefault(new MockNonCachedResponseCache());
- uc = (HttpURLConnection) url.openConnection();
- uc.setChunkedStreamingMode(10);
- uc.setDoOutput(true);
- uc.getOutputStream();
- assertTrue(isGetCalled);
- assertFalse(isPutCalled);
- assertFalse(isAbortCalled);
- uc.disconnect();
- }
-
- /**
- * @tests java.net.URLConnection#getErrorStream()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Negative cases depends on server responds.",
- method = "getErrorStream",
- args = {}
- )
- public void test_getErrorStream() throws Exception {
- uc.connect();
- assertEquals(200, uc.getResponseCode());
- // no error stream
- assertNull(uc.getErrorStream());
- uc.disconnect();
- assertNull(uc.getErrorStream());
-
- try {
- URL url = new URL(unknownURL);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- assertNull(conn.getErrorStream());
- } catch(IOException e) {
- fail("IOException was thrown.");
- }
- }
-
- /**
- * @tests {@link java.net.HttpURLConnection#setFollowRedirects(boolean)}
- * @tests {@link java.net.HttpURLConnection#getFollowRedirects()}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFollowRedirects",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setFollowRedirects",
- args = {boolean.class}
- )
- })
- public void test_followRedirects() {
- assertTrue("The default value of followRedirects is not true",
- HttpURLConnection.getFollowRedirects());
-
- HttpURLConnection.setFollowRedirects(false);
- assertFalse(HttpURLConnection.getFollowRedirects());
-
- HttpURLConnection.setFollowRedirects(true);
- assertTrue(HttpURLConnection.getFollowRedirects());
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkSetFactory() {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- HttpURLConnection.setFollowRedirects(false);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstanceFollowRedirects",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setInstanceFollowRedirects",
- args = {boolean.class}
- )
- })
- public void test_instanceFollowRedirect() {
- assertTrue(uc.getInstanceFollowRedirects());
-
- uc.setInstanceFollowRedirects(false);
- assertFalse(uc.getInstanceFollowRedirects());
-
- uc.setInstanceFollowRedirects(true);
- assertTrue(uc.getInstanceFollowRedirects());
-
- uc.setFollowRedirects(false);
- assertTrue(uc.getInstanceFollowRedirects());
- }
-
- /**
- * @throws ProtocolException
- * @tests {@link java.net.HttpURLConnection#setRequestMethod(String)}
- * @tests {@link java.net.HttpURLConnection#getRequestMethod()}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRequestMethod",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setRequestMethod",
- args = {java.lang.String.class}
- )
- })
- public void test_requestMethod() throws MalformedURLException, ProtocolException{
- URL url = new URL("http://" + Support_Configuration.SpecialInetTestAddress);
-
- HttpURLConnection con = new MyHttpURLConnection(url);
- assertEquals("The default value of requestMethod is not \"GET\"", "GET",
- con.getRequestMethod());
-
- String[] methods = { "GET", "DELETE", "HEAD", "OPTIONS", "POST", "PUT",
- "TRACE" };
- // Nomal set. Should not throw ProtocolException
- for (String method : methods) {
- con.setRequestMethod(method);
- assertEquals("The value of requestMethod is not " + method, method,
- con.getRequestMethod());
- }
-
- try {
- con.setRequestMethod("Wrong method");
- fail("Should throw ProtocolException");
- } catch (ProtocolException e) {
- // Expected
- }
-
- try {
- con.setRequestMethod("get");
- fail("Should throw ProtocolException");
- } catch (ProtocolException e) {
- // Expected
- }
- }
-
- private static class MyHttpURLConnection extends HttpURLConnection {
-
- protected MyHttpURLConnection(URL url) {
- super(url);
- }
-
- @Override
- public void disconnect() {
- // do nothing
- }
-
- @Override
- public boolean usingProxy() {
- return false;
- }
-
- @Override
- public void connect() throws IOException {
- // do nothing
- }
- }
-
- /**
- * @tests java.net.URLConnection#getPermission()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException is not verified.",
- method = "getPermission",
- args = {}
- )
- public void test_Permission() throws Exception {
- uc.connect();
- Permission permission = uc.getPermission();
- assertNotNull(permission);
- permission.implies(new SocketPermission("localhost","connect"));
-
- try {
- URL url = new URL(unknownURL);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.getPermission();
- } catch(IOException e) {
- fail("IOException was thrown.");
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "HttpURLConnection",
- args = {java.net.URL.class}
- )
- public void test_Constructor() throws IOException {
- MockHttpConnection conn1 = new MockHttpConnection(url);
- conn1.connect();
- conn1.disconnect();
-
- MockHttpConnection conn2 = new MockHttpConnection(null);
- conn2.connect();
- conn2.disconnect();
-
- URL url = new URL("file://newFile.txt");
- MockHttpConnection conn3 = new MockHttpConnection(url);
- conn3.connect();
- conn3.disconnect();
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "disconnect",
- args = {}
- )
- public void test_disconnect() {
-
- try {
- URL url1 = new URL("http://" + Support_Configuration.testURL);
- HttpURLConnection uc1 = (HttpURLConnection) url1.openConnection();
- uc1.disconnect();
- InputStream is = uc1.getInputStream();
- byte [] array = new byte [10];
- is.read(array);
- assertNotNull(array);
- try {
- uc1.connect();
- uc1.disconnect();
- } catch(IOException e) {
- fail("IOException was thrown.");
- }
- } catch (Exception e) {
- fail("Exception during setup : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getHeaderFieldDate",
- args = {java.lang.String.class, long.class}
- )
- public void test_getHeaderFieldDate(String name, long Default) {
- long date = uc.getHeaderFieldDate(uc.getHeaderField(0), 0);
- assertEquals(System.currentTimeMillis(), date);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "usingProxy",
- args = {}
- )
- public void test_usingProxy() {
- assertFalse(uc.usingProxy());
- }
-
- class MockNonCachedResponseCache extends ResponseCache {
-
- public CacheResponse get(URI arg0, String arg1, Map arg2)
- throws IOException {
- isGetCalled = true;
- return null;
- }
-
- public CacheRequest put(URI arg0, URLConnection arg1)
- throws IOException {
- isPutCalled = true;
- return new MockCacheRequest();
- }
- }
-
- class MockCachedResponseCache extends ResponseCache {
-
- public CacheResponse get(URI arg0, String arg1, Map arg2)
- throws IOException {
- if (null == arg0 || null == arg1 || null == arg2) {
- throw new NullPointerException();
- }
- isGetCalled = true;
- return new MockCacheResponse();
- }
-
- public CacheRequest put(URI arg0, URLConnection arg1)
- throws IOException {
- if (null == arg0 || null == arg1) {
- throw new NullPointerException();
- }
- isPutCalled = true;
- return new MockCacheRequest();
- }
- }
-
- class MockCacheRequest extends CacheRequest {
-
- public OutputStream getBody() throws IOException {
- isCacheWriteCalled = true;
- return new MockOutputStream();
- }
-
- public void abort() {
- isAbortCalled = true;
- }
-
- }
-
- class MockCacheResponse extends CacheResponse {
-
- public Map<String, List<String>> getHeaders() throws IOException {
- return mockHeaderMap;
- }
-
- public InputStream getBody() throws IOException {
- return mockIs;
- }
- }
-
- class MockInputStream extends InputStream {
-
- public int read() throws IOException {
- return 4711;
- }
-
- public int read(byte[] arg0, int arg1, int arg2) throws IOException {
- return 1;
- }
-
- public int read(byte[] arg0) throws IOException {
- return 1;
- }
-
- }
-
- class MockOutputStream extends OutputStream {
-
- public void write(int b) throws IOException {
- isCacheWriteCalled = true;
- }
-
- public void write(byte[] b, int off, int len) throws IOException {
- isCacheWriteCalled = true;
- }
-
- public void write(byte[] b) throws IOException {
- isCacheWriteCalled = true;
- }
- }
-
- class MockHttpConnection extends HttpURLConnection {
-
- protected MockHttpConnection(URL url) {
- super(url);
- }
-
- public void disconnect() {
- // do nothing
- }
-
- public boolean usingProxy() {
- return false;
- }
-
- public void connect() throws IOException {
- // do nothing
- }
-
- public int getChunkLength() {
- return super.chunkLength;
- }
-
- public int getFixedLength() {
- return super.fixedContentLength;
- }
-
- }
-
- protected void setUp() {
- try {
- url = new URL(Support_Configuration.hTTPURLyahoo);
- uc = (HttpURLConnection) url.openConnection();
- } catch (Exception e) {
- fail("Exception during setup : " + e.getMessage());
- }
- mockHeaderMap = new Hashtable<String, List<String>>();
- List<String> valueList = new ArrayList<String>();
- valueList.add("value1");
- mockHeaderMap.put("field1", valueList);
- mockHeaderMap.put("field2", valueList);
- isGetCalled = false;
- isPutCalled = false;
- isCacheWriteCalled = false;
- }
-
- protected void tearDown() {
- uc.disconnect();
- ResponseCache.setDefault(null);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/Inet4AddressTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/Inet4AddressTest.java
deleted file mode 100644
index 163db31..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/Inet4AddressTest.java
+++ /dev/null
@@ -1,542 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.Serializable;
-import java.net.Inet4Address;
-import java.net.InetAddress;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(Inet4Address.class)
-public class Inet4AddressTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.Inet4Address#isMulticastAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMulticastAddress",
- args = {}
- )
- public void test_isMulticastAddress() {
-
- // Create 2 IP v4 addresses and call "isMulticastAddress()"
- // result should return true if the first 4 bits of the
- // address are: 1110, false otherwise
- // Make 1 address with 1110, and 1 without
- String addrName = "";
- try {
- addrName = "224.0.0.0"; // a multicast addr 1110 = 224-239
- InetAddress addr = Inet4Address.getByName(addrName);
- assertTrue("Multicast address " + addrName + " not detected.", addr
- .isMulticastAddress());
-
- addrName = "239.255.255.255"; // a multicast addr 1110 = 224-239
- addr = Inet4Address.getByName(addrName);
- assertTrue("Multicast address " + addrName + " not detected.", addr
- .isMulticastAddress());
-
- addrName = "42.42.42.42"; // a non-multicast address
- addr = Inet4Address.getByName(addrName);
- assertTrue("Non multicast address " + addrName
- + " reporting as a multicast address.", !addr
- .isMulticastAddress());
- } catch (Exception e) {
- fail("Unknown address : " + addrName);
- }
-
- }
-
- /**
- * @tests java.net.Inet4Address#isAnyLocalAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isAnyLocalAddress",
- args = {}
- )
- public void test_isAnyLocalAddress() {
- String addrName = "";
- try {
- addrName = "0.0.0.0";
- InetAddress addr = Inet4Address.getByName(addrName);
- assertTrue("ANY address " + addrName + " not detected.", addr
- .isAnyLocalAddress());
- } catch (Exception e) {
- fail("Unknown address : " + addrName);
- }
- }
-
- /**
- * @tests java.net.Inet4Address#isLoopbackAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isLoopbackAddress",
- args = {}
- )
- public void test_isLoopbackAddress() {
- // Create some IP V4 addresses and test if they are local...
-
- String addrName = "";
- try {
- addrName = "127.0.0.0"; // a loopback address should be 127.d.d.d
- InetAddress addr = Inet4Address.getByName(addrName);
- assertTrue("Loopback address " + addrName + " not detected.", addr
- .isLoopbackAddress());
-
- addrName = "127.42.42.42"; // a loopback address should be
- // 127.d.d.d
- addr = Inet4Address.getByName(addrName);
- assertTrue("Loopback address " + addrName + " not detected.", addr
- .isLoopbackAddress());
-
- addrName = "42.42.42.42"; // a loopback address should be
- // 127.d.d.d
- addr = Inet4Address.getByName(addrName);
- assertTrue("Address incorrectly " + addrName
- + " detected as a loopback address.", !addr
- .isLoopbackAddress());
-
- } catch (Exception e) {
- fail("Unknown address : " + addrName);
- }
-
- }
-
- /**
- * @tests java.net.Inet4Address#isLinkLocalAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isLinkLocalAddress",
- args = {}
- )
- public void test_isLinkLocalAddress() {
-
- String addrName = "";
- try {
- // There are no link local addresses for IPv4
- // We'll test one to ensure we get "false"
-
- addrName = "42.42.42.42";
- InetAddress addr = Inet4Address.getByName(addrName);
- assertTrue("IPv4 address " + addrName
- + " incorrectly reporting as a link local address.", !addr
- .isLinkLocalAddress());
- } catch (Exception e) {
- fail("Unknown address : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.net.Inet4Address#isSiteLocalAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isSiteLocalAddress",
- args = {}
- )
- public void test_isSiteLocalAddress() {
- String addrName = "";
- try {
- // There are no site local addresses for IPv4
- // We'll test one to ensure we get "false"
-
- addrName = "42.42.42.42";
- InetAddress addr = Inet4Address.getByName(addrName);
- assertTrue("IPv4 address " + addrName
- + " incorrectly reporting as a site local address.", !addr
- .isSiteLocalAddress());
- } catch (Exception e) {
- fail("Unknown address : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.net.Inet4Address#isMCGlobal()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMCGlobal",
- args = {}
- )
- public void test_isMCGlobal() {
-
- // Create an IPv4 mulitcast address. It should return
- // false for globabl mutlicast. There are no valid IPv4
- // global multicast addresses
-
- String addrName = "";
- try {
- addrName = "224.0.0.0"; // a multicast addr 1110
- InetAddress addr = Inet4Address.getByName(addrName);
- assertTrue("IPv4 link-local multicast address " + addrName
- + " incorrectly identified as a global multicast address.",
- !addr.isMCGlobal());
-
- addrName = "224.0.0.255"; // a multicast addr 1110
- addr = Inet4Address.getByName(addrName);
- assertTrue("IPv4 link-local multicast address " + addrName
- + " incorrectly identified as a global multicast address.",
- !addr.isMCGlobal());
-
- addrName = "224.0.1.0"; // a multicast addr 1110
- addr = Inet4Address.getByName(addrName);
- assertTrue("IPv4 global multicast address " + addrName
- + " not identified as a global multicast address.", addr
- .isMCGlobal());
-
- addrName = "238.255.255.255"; // a multicast addr 1110
- addr = Inet4Address.getByName(addrName);
- assertTrue("IPv4 global multicast address " + addrName
- + " not identified as a global multicast address.", addr
- .isMCGlobal());
-
- addrName = "239.0.0.0"; // a multicast addr 1110
- addr = Inet4Address.getByName(addrName);
- assertTrue("IPv4 reserved multicast address " + addrName
- + " incorrectly identified as a global multicast address.",
- !addr.isMCGlobal());
-
- addrName = "239.191.255.255"; // a multicast addr 1110
- addr = Inet4Address.getByName(addrName);
- assertTrue("IPv4 reserved multicast address " + addrName
- + " incorrectly identified as a global multicast address.",
- !addr.isMCGlobal());
-
- } catch (Exception e) {
- fail("Unknown address : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.net.Inet4Address#isMCNodeLocal()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMCNodeLocal",
- args = {}
- )
- public void test_isMCNodeLocal() {
- // Create an IPv4 mulitcast address. It should return
- // false for node-local mutlicast. There are no valid IPv4
- // node-local multicast addresses
-
- String addrName = "";
- try {
- addrName = "224.42.42.42"; // a multicast addr 1110 = 224
- InetAddress addr = Inet4Address.getByName(addrName);
- assertTrue(
- "IPv4 multicast address "
- + addrName
- + " incorrectly identified as a node-local multicast address.",
- !addr.isMCNodeLocal());
-
- addrName = "239.0.0.0"; // a multicast addr 1110
- addr = Inet4Address.getByName(addrName);
- assertTrue(
- "IPv4 reserved multicast address "
- + addrName
- + " incorrectly identified as a node-local multicast address.",
- !addr.isMCNodeLocal());
-
- } catch (Exception e) {
- fail("Unknown address : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.net.Inet4Address#isMCLinkLocal()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMCLinkLocal",
- args = {}
- )
- public void test_isMCLinkLocal() {
- // Create an IPv4 mulitcast address. It should return
- // false for link-local mutlicast. There are no valid IPv4
- // link-local multicast addresses
-
- String addrName = "";
- try {
- addrName = "224.0.0.0"; // a multicast addr 1110
- InetAddress addr = Inet4Address.getByName(addrName);
- assertTrue("IPv4 link-local multicast address " + addrName
- + " not identified as a link-local multicast address.",
- addr.isMCLinkLocal());
-
- addrName = "224.0.0.255"; // a multicast addr 1110
- addr = Inet4Address.getByName(addrName);
- assertTrue("IPv4 link-local multicast address " + addrName
- + " not identified as a link-local multicast address.",
- addr.isMCLinkLocal());
-
- addrName = "224.0.1.0"; // a multicast addr 1110
- addr = Inet4Address.getByName(addrName);
- assertTrue(
- "IPv4 global multicast address "
- + addrName
- + " incorrectly identified as a link-local multicast address.",
- !addr.isMCLinkLocal());
-
- addrName = "239.0.0.0"; // a multicast addr 1110
- addr = Inet4Address.getByName(addrName);
- assertTrue(
- "IPv4 reserved multicast address "
- + addrName
- + " incorrectly identified as a link-local multicast address.",
- !addr.isMCLinkLocal());
-
- } catch (Exception e) {
- fail("Unknown address : " + addrName);
- }
- }
-
- /**
- * @tests java.net.Inet4Address#isMCSiteLocal()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMCSiteLocal",
- args = {}
- )
- public void test_isMCSiteLocal() {
- // Create an IPv4 mulitcast address. It should return
- // false for site-local mutlicast. There are no valid IPv4
- // site-local multicast addresses
-
- String addrName = "";
- try {
- addrName = "240.0.0.0"; // a multicast addr 1110 = 224
- InetAddress addr = Inet4Address.getByName(addrName);
- assertTrue(
- "IPv4 multicast address "
- + addrName
- + " incorrectly identified as a site-local multicast address.",
- !addr.isMCSiteLocal());
-
- addrName = "239.0.0.0"; // a multicast addr 1110
- addr = Inet4Address.getByName(addrName);
- assertTrue(
- "IPv4 reserved multicast address "
- + addrName
- + " incorrectly identified as a site-local multicast address.",
- !addr.isMCSiteLocal());
-
- addrName = "239.255.0.0"; // a multicast addr 1110
- addr = Inet4Address.getByName(addrName);
- assertTrue("IPv4 site-local multicast address " + addrName
- + " not identified as a site-local multicast address.",
- addr.isMCSiteLocal());
-
- addrName = "239.255.255.255"; // a multicast addr 1110
- addr = Inet4Address.getByName(addrName);
- assertTrue("IPv4 site-local multicast address " + addrName
- + " not identified as a site-local multicast address.",
- addr.isMCSiteLocal());
-
- addrName = "239.255.2.2"; // a multicast addr 1110
- addr = Inet4Address.getByName(addrName);
- assertTrue("IPv4 site-local multicast address " + addrName
- + " not identified as a site-local multicast address.",
- addr.isMCSiteLocal());
-
- } catch (Exception e) {
- fail("Unknown address : " + addrName);
- }
- }
-
- /**
- * @tests java.net.Inet4Address#isMCOrgLocal()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMCOrgLocal",
- args = {}
- )
- public void test_isMCOrgLocal() {
- // Create an IPv4 mulitcast address. It should return
- // false for organization-local mutlicast. There are no valid IPv4
- // organization-local multicast addresses
-
- String addrName = "";
- try {
-
- addrName = "239.191.255.255"; // a multicast addr 1110
- InetAddress addr = Inet4Address.getByName(addrName);
- assertTrue(
- "IPv4 reserved multicast address "
- + addrName
- + " incorrectly identified as a org-local multicast address.",
- !addr.isMCOrgLocal());
-
- addrName = "239.252.0.0"; // a multicast addr 1110
- addr = Inet4Address.getByName(addrName);
- assertTrue(
- "IPv4 site-local multicast address "
- + addrName
- + " incorrectly identified as a org-local multicast address.",
- !addr.isMCOrgLocal());
-
- addrName = "239.192.0.0"; // a multicast addr 1110
- addr = Inet4Address.getByName(addrName);
- assertTrue("IPv4 org-local multicast address " + addrName
- + " not identified as a org-local multicast address.", addr
- .isMCOrgLocal());
-
- addrName = "239.195.255.255"; // a multicast addr 1110
- addr = Inet4Address.getByName(addrName);
- assertTrue("IPv4 org-local multicast address " + addrName
- + " not identified as a org-local multicast address.", addr
- .isMCOrgLocal());
-
- } catch (Exception e) {
- fail("Unknown address : " + addrName);
- }
- }
-
- // comparator for Inet4Address objects
- private static final SerializableAssert COMPARATOR = new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
-
- Inet4Address initAddr = (Inet4Address) initial;
- Inet4Address desrAddr = (Inet4Address) deserialized;
-
- byte[] iaAddresss = initAddr.getAddress();
- byte[] deIAAddresss = desrAddr.getAddress();
- for (int i = 0; i < iaAddresss.length; i++) {
- assertEquals(iaAddresss[i], deIAAddresss[i]);
- }
- assertEquals(4, deIAAddresss.length);
- assertEquals(initAddr.getHostName(), desrAddr.getHostName());
- }
- };
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Checks serialization",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(Inet4Address.getByName("localhost"),
- COMPARATOR);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Checks serialization",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, Inet4Address
- .getByName("localhost"), COMPARATOR);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equals() throws Exception {
- InetAddress addr = Inet4Address.getByName("239.191.255.255");
- assertTrue(addr.equals(addr));
- InetAddress addr1 = Inet4Address.getByName("127.0.0.1");
- InetAddress addr2 = Inet4Address.getByName("localhost");
- assertTrue(addr1.equals(addr2));
- assertFalse(addr.equals(addr1));
-
- InetAddress addr3 = Inet4Address.getByName("127.0.0");
- assertFalse(addr1.equals(addr3));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getHostAddress",
- args = {}
- )
- public void test_getHostAddress() throws Exception {
- InetAddress addr = Inet4Address.getByName("localhost");
- assertEquals("127.0.0.1", addr.getHostAddress());
-
- addr = Inet4Address.getByName("127.0.0.1");
- assertEquals("127.0.0.1", addr.getHostAddress());
-
- addr = Inet4Address.getByName("224.0.0.0");
- assertEquals("224.0.0.0", addr.getHostAddress());
-
- addr = Inet4Address.getByName("1");
- assertEquals("0.0.0.1", addr.getHostAddress());
-
- addr = Inet4Address.getByName("1.1");
- assertEquals("1.0.0.1", addr.getHostAddress());
-
- addr = Inet4Address.getByName("1.1.1");
- assertEquals("1.1.0.1", addr.getHostAddress());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() throws Exception {
- InetAddress addr1 = Inet4Address.getByName("1.1");
- InetAddress addr2 = Inet4Address.getByName("1.1.1");
- assertFalse(addr1.hashCode() == addr2.hashCode());
-
- addr2 = InetAddress.getByName("1.0.0.1");
- assertTrue(addr1.hashCode() == addr2.hashCode());
-
- addr1 = Inet4Address.getByName("127.0.0.1");
- addr2 = Inet4Address.getByName("localhost");
- assertTrue(addr1.hashCode() == addr2.hashCode());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/Inet6AddressTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/Inet6AddressTest.java
deleted file mode 100644
index 1b2aa22..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/Inet6AddressTest.java
+++ /dev/null
@@ -1,1242 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.Serializable;
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.NetworkInterface;
-import java.net.UnknownHostException;
-
-import java.security.Permission;
-
-import org.apache.harmony.luni.tests.java.net.InetAddressTest.MockSecurityManager;
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(Inet6Address.class)
-public class Inet6AddressTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.Inet6Address#isMulticastAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMulticastAddress",
- args = {}
- )
- public void test_isMulticastAddress() {
-
- String addrName = "";
- InetAddress addr = null;
-
- try {
-
- // IP V6 regular multicast and non-multicast tests
- //
- // Create 2 IP v6 addresses and call "isMulticastAddress()"
- // A prefix of "11111111" means that the address is multicast
- // The first one will be one with the prefix the second without
-
- addrName = "FFFF::42:42"; // 11111111 = FFFF
- addr = Inet6Address.getByName(addrName);
- assertTrue("Multicast address " + addrName + " not detected.", addr
- .isMulticastAddress());
-
- addrName = "42::42:42"; // an non-multicast address
- addr = Inet6Address.getByName(addrName);
- assertTrue("Non multicast address " + addrName
- + " reporting as a multicast address.", !addr
- .isMulticastAddress());
-
- // IPv4-compatible IPv6 address tests
- //
- // Now create 2 IP v6 addresses that are IP v4 compatable
- // to IP v6 addresses. The address prefix for a multicast ip v4
- // address is 1110 for the last 16 bits ::d.d.d.d
- // We expect these to be false
-
- addrName = "::224.42.42.42"; // an ipv4 multicast addr 1110 = 224
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv4 compatable address " + addrName
- + " reported incorrectly as multicast.", !addr
- .isMulticastAddress());
-
- addrName = "::42.42.42.42"; // an ipv4 non-multicast address
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv4 compatable address " + addrName
- + " reported incorrectly as multicast.", !addr
- .isMulticastAddress());
-
- // IPv4-mapped IPv6 address tests
- //
- // Now create 2 IP v6 addresses that are IP v4 compatable
- // to IP v6 addresses. The address prefix for a multicast ip v4
- // address is 1110 for the last 16 bits ::FFFF:d.d.d.d
-
- addrName = "::FFFF:224.42.42.42"; // an ipv4 multicast addr 1110 =
- // 224
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv4-mapped IPv6 multicast address " + addrName
- + " not detected.", addr.isMulticastAddress());
-
- addrName = "::FFFF:42.42.42.42"; // an ipv4 non-multicast address
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv4-mapped IPv6 non-multicast address " + addrName
- + " reporting as a multicast address.", !addr
- .isMulticastAddress());
- } catch (Exception e) {
- fail("Unknown address : " + addrName);
- }
- }
-
- /**
- * @tests java.net.Inet6Address#isAnyLocalAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isAnyLocalAddress",
- args = {}
- )
- public void test_isAnyLocalAddress() {
-
- String addrName = "";
- InetAddress addr = null;
-
- try {
-
- // test to ensure that the unspecified address returns tru
- addrName = "::0"; // The unspecified address
- addr = InetAddress.getByName(addrName);
- assertTrue(
- "The unspecified (also known as wildcard and any local address) "
- + addrName + " not detected.", addr
- .isAnyLocalAddress());
-
- addrName = "::"; // another form of the unspecified address
- addr = InetAddress.getByName(addrName);
- assertTrue(
- "The unspecified (also known as wildcard and any local address) "
- + addrName + " not detected.", addr
- .isAnyLocalAddress());
-
- addrName = "::1"; // The loopback address
- addr = InetAddress.getByName(addrName);
- assertTrue("The addresses " + addrName
- + " incorrectly reporting an the unspecified address.",
- !addr.isAnyLocalAddress());
-
- } catch (Exception e) {
- fail("Unknown address : " + addrName);
- }
- }
-
- /**
- * @tests java.net.Inet6Address#isLoopbackAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isLoopbackAddress",
- args = {}
- )
- public void test_isLoopbackAddress() {
-
- String addrName = "";
- try {
-
- // IP V6 regular address tests for loopback
- // The loopback address for IPv6 is ::1
-
- addrName = "::1";
- InetAddress addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 loopback address " + addrName + " not detected.",
- addr.isLoopbackAddress());
-
- addrName = "::2";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 address incorrectly " + addrName
- + " detected as a loopback address.", !addr
- .isLoopbackAddress());
-
- // a loopback address should be 127.d.d.d
- addrName = "42:42::42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 address incorrectly " + addrName
- + " detected as a loopback address.", !addr
- .isLoopbackAddress());
-
- // IPv4-compatible IPv6 address tests
- //
- // Now create 2 IP v6 addresses that are IP v4 compatable
- // to IP v6 addresses. The address prefix for a multicast ip v4
- // address is 1110 for the last 16 bits ::d.d.d.d
- // We expect these to be false, as they are not IPv4 addresses
-
- // a loopback address should be 127.d.d.d
- addrName = "::127.0.0.0";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv4-compatible IPv6 address " + addrName
- + " detected incorrectly as a loopback.", !addr
- .isLoopbackAddress());
-
- addrName = "::127.42.42.42"; // a loopback address should be
- // 127.d.d.d
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv4-compatible IPv6 address " + addrName
- + " detected incorrectly as a loopback.", !addr
- .isLoopbackAddress());
-
- // a loopback address should be 127.d.d.d
- addrName = "::42.42.42.42";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv4-compatible IPv6 address " + addrName
- + " detected incorrectly as a loopback.", !addr
- .isLoopbackAddress());
-
- // IPv4-mapped IPv6 address tests
- //
- // Now create 2 IP v6 addresses that are IP v4 compatable
- // to IP v6 addresses. The address prefix for a multicast ip v4
- // address is 1110 for the last 16 bits ::FFFF:d.d.d.d
-
- // a loopback address should be 127.d.d.d
- addrName = "::FFFF:127.0.0.0";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv4-compatible IPv6 loopback address " + addrName
- + " not detected.", addr.isLoopbackAddress());
-
- // a loopback address should be 127.d.d.d
- addrName = "::FFFF:127.42.42.42";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv4-compatible IPv6 loopback address " + addrName
- + " not detected.", addr.isLoopbackAddress());
-
- // a loopback address should be 127.d.d.d
- addrName = "::FFFF:42.42.42.42";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv4-compatible IPv6 address incorrectly " + addrName
- + " detected as a loopback address.", !addr
- .isLoopbackAddress());
-
- } catch (UnknownHostException e) {
- fail("Unknown address : " + addrName);
- }
- }
-
- /**
- * @tests java.net.Inet6Address#isLinkLocalAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isLinkLocalAddress",
- args = {}
- )
- public void test_isLinkLocalAddress() {
-
- String addrName = "";
- try {
- // IP V6 regular address tests for link local addresses
- //
- // Link local addresses are FE80:: -
- // FEBF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF
-
- addrName = "FE80::0";
- InetAddress addr = Inet6Address.getByName(addrName);
- assertTrue(
- "IPv6 link local address " + addrName + " not detected.",
- addr.isLinkLocalAddress());
-
- addrName = "FEBF::FFFF:FFFF:FFFF:FFFF";
- addr = Inet6Address.getByName(addrName);
- assertTrue(
- "IPv6 link local address " + addrName + " not detected.",
- addr.isLinkLocalAddress());
-
- addrName = "FEC0::1";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 address " + addrName
- + " detected incorrectly as a link local address.", !addr
- .isLinkLocalAddress());
-
- addrName = "FD80::1:FFFF:FFFF:FFFF:FFFF";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 address " + addrName
- + " detected incorrectly as a link local address.", !addr
- .isLinkLocalAddress());
-
- addrName = "FE7F::FFFF:FFFF:FFFF:FFFF";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 address " + addrName
- + " detected incorrectly as a link local address.", !addr
- .isLinkLocalAddress());
- } catch (Exception e) {
- fail("Unknown address : " + addrName);
- }
-
- }
-
- /**
- * @tests java.net.Inet6Address#isSiteLocalAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isSiteLocalAddress",
- args = {}
- )
- public void test_isSiteLocalAddress() {
- String addrName = "";
- try {
- // IP V6 regular address tests for link local addresses
- //
- // Link local addresses are FEC0::0 through to
- // FEFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF
-
- addrName = "FEC0::0";
- InetAddress addr = Inet6Address.getByName(addrName);
- assertTrue(
- "IPv6 site local address " + addrName + " not detected.",
- addr.isSiteLocalAddress());
-
- addrName = "FEFF::FFFF:FFFF:FFFF:FFFF:FFFF";
- addr = Inet6Address.getByName(addrName);
- assertTrue(
- "IPv6 site local address " + addrName + " not detected.",
- addr.isSiteLocalAddress());
-
- addrName = "FEBF::FFFF:FFFF:FFFF:FFFF:FFFF";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 address " + addrName
- + " detected incorrectly as a site local address.", !addr
- .isSiteLocalAddress());
-
- addrName = "FFC0::0";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 address " + addrName
- + " detected incorrectly as a site local address.", !addr
- .isSiteLocalAddress());
-
- } catch (Exception e) {
- fail("Unknown address : " + addrName);
- }
- }
-
- /**
- * @tests java.net.Inet6Address#isMCGlobal()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMCGlobal",
- args = {}
- )
- public void test_isMCGlobal() {
- String addrName = "";
- try {
- // IP V6 regular address tests for Mulitcase Global addresses
- //
- // Multicast global addresses are FFxE:/112 where x is
- // a set of flags, and the addition 112 bits make up
- // the global address space
-
- addrName = "FF0E::0";
- InetAddress addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 global mutlicast address " + addrName
- + " not detected.", addr.isMCGlobal());
-
- addrName = "FF0E:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 global multicast address " + addrName
- + " not detected.", addr.isMCGlobal());
-
- // a currently invalid address as the prefix FFxE
- // is only valid for x = {1,0} as the rest are reserved
- addrName = "FFFE::0";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 global mutlicast address " + addrName
- + " not detected.", addr.isMCGlobal());
-
- // a currently invalid address as the prefix FFxE
- // is only valid for x = {1,0} as the rest are reserved
- addrName = "FFFE:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 global multicast address " + addrName
- + " not detected.", addr.isMCGlobal());
-
- // a sample MC organizational address
- addrName = "FF08:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 mulitcast organizational " + addrName
- + " incorrectly indicated as a global address.", !addr
- .isMCGlobal());
-
- // a sample MC site address
- addrName = "FF05:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 mulitcast site address " + addrName
- + " incorrectly indicated as a global address.", !addr
- .isMCGlobal());
-
- // a sample MC link address
- addrName = "FF02:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 mulitcast link address " + addrName
- + " incorrectly indicated as a global address.", !addr
- .isMCGlobal());
-
- // a sample MC Node
- addrName = "FF01:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 mulitcast node address " + addrName
- + " incorrectly indicated as a global address.", !addr
- .isMCGlobal());
-
- // IPv4-mapped IPv6 address tests
- addrName = "::FFFF:224.0.1.0";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv4 global multicast address " + addrName
- + " not identified as a global multicast address.", addr
- .isMCGlobal());
-
- addrName = "::FFFF:238.255.255.255";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv4 global multicast address " + addrName
- + " not identified as a global multicast address.", addr
- .isMCGlobal());
-
- } catch (Exception e) {
- fail("Unknown address : " + addrName);
- }
- }
-
- /**
- * @tests java.net.Inet6Address#isMCNodeLocal()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMCNodeLocal",
- args = {}
- )
- public void test_isMCNodeLocal() {
- String addrName = "";
- try {
- // IP V6 regular address tests for Mulitcase node local addresses
- //
- // Multicast node local addresses are FFx1:/112 where x is
- // a set of flags, and the addition 112 bits make up
- // the global address space
-
- addrName = "FF01::0";
- InetAddress addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 node-local mutlicast address " + addrName
- + " not detected.", addr.isMCNodeLocal());
-
- addrName = "FF01:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 node-local multicast address " + addrName
- + " not detected.", addr.isMCNodeLocal());
-
- // a currently invalid address as the prefix FFxE
- // is only valid for x = {1,0} as the rest are reserved
- addrName = "FFF1::0";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 node-local mutlicast address " + addrName
- + " not detected.", addr.isMCNodeLocal());
-
- // a currently invalid address as the prefix FFxE
- // is only valid for x = {1,0} as the rest are reserved
- addrName = "FFF1:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 node-local multicast address " + addrName
- + " not detected.", addr.isMCNodeLocal());
-
- // a sample MC organizational address
- addrName = "FF08:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 mulitcast organizational address " + addrName
- + " incorrectly indicated as a node-local address.", !addr
- .isMCNodeLocal());
-
- // a sample MC site address
- addrName = "FF05:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 mulitcast site address " + addrName
- + " incorrectly indicated as a node-local address.", !addr
- .isMCNodeLocal());
-
- // a sample MC link address
- addrName = "FF02:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 mulitcast link address " + addrName
- + " incorrectly indicated as a node-local address.", !addr
- .isMCNodeLocal());
-
- // a sample MC global address
- addrName = "FF0E:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 mulitcast node address " + addrName
- + " incorrectly indicated as a node-local address.", !addr
- .isMCNodeLocal());
-
- } catch (Exception e) {
- fail("Unknown address : " + addrName);
- }
- }
-
- /**
- * @tests java.net.Inet6Address#isMCLinkLocal()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMCLinkLocal",
- args = {}
- )
- public void test_isMCLinkLocal() {
- String addrName = "";
- try {
- // IP V6 regular address tests for Mulitcase link local addresses
- //
- // Multicast link local addresses are FFx2:/112 where x is
- // a set of flags, and the addition 112 bits make up
- // the global address space
-
- addrName = "FF02::0";
- InetAddress addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 link local multicast address " + addrName
- + " not detected.", addr.isMCLinkLocal());
-
- addrName = "FF02:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 link local multicast address " + addrName
- + " not detected.", addr.isMCLinkLocal());
-
- // a currently invalid address as the prefix FFxE
- // is only valid for x = {1,0} as the rest are reserved
- addrName = "FFF2::0";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 link local multicast address " + addrName
- + " not detected.", addr.isMCLinkLocal());
-
- // a currently invalid address as the prefix FFxE
- // is only valid for x = {1,0} as the rest are reserved
- addrName = "FFF2:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 link local multicast address " + addrName
- + " not detected.", addr.isMCLinkLocal());
-
- // a sample MC organizational address
- addrName = "FF08:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue(
- "IPv6 organization multicast address "
- + addrName
- + " incorrectly indicated as a link-local mulitcast address.",
- !addr.isMCLinkLocal());
-
- // a sample MC site address
- addrName = "FF05:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue(
- "IPv6 site-local mulitcast address "
- + addrName
- + " incorrectly indicated as a link-local mulitcast address.",
- !addr.isMCLinkLocal());
-
- // a sample MC global address
- addrName = "FF0E:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue(
- "IPv6 global multicast address "
- + addrName
- + " incorrectly indicated as a link-local mulitcast address.",
- !addr.isMCLinkLocal());
-
- // a sample MC Node
- addrName = "FF01:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue(
- "IPv6 mulitcast node address "
- + addrName
- + " incorrectly indicated as a link-local mulitcast address.",
- !addr.isMCLinkLocal());
-
- // Ipv4-mapped IPv6 addresses
-
- addrName = "::FFFF:224.0.0.0"; // a multicast addr 1110
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv4 link-local multicast address " + addrName
- + " not identified as a link-local multicast address.",
- addr.isMCLinkLocal());
-
- addrName = "::FFFF:224.0.0.255"; // a multicast addr 1110
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv4 link-local multicast address " + addrName
- + " not identified as a link-local multicast address.",
- addr.isMCLinkLocal());
-
- } catch (Exception e) {
- fail("Unknown address : " + addrName);
- }
- }
-
- /**
- * @tests java.net.Inet6Address#isMCSiteLocal()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMCSiteLocal",
- args = {}
- )
- public void test_isMCSiteLocal() {
- String addrName = "";
- try {
- // IP V6 regular address tests for Multicast site-local addresses
- //
- // Multicast global addresses are FFx5:/112 where x is
- // a set of flags, and the addition 112 bits make up
- // the global address space
-
- addrName = "FF05::0";
- InetAddress addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 site-local mutlicast address " + addrName
- + " not detected.", addr.isMCSiteLocal());
-
- addrName = "FF05:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 site-local multicast address " + addrName
- + " not detected.", addr.isMCSiteLocal());
-
- // a currently invalid address as the prefix FFxE
- // is only valid for x = {1,0} as the rest are reserved
- addrName = "FFF5::0";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 site-local mutlicast address " + addrName
- + " not detected.", addr.isMCSiteLocal());
-
- // a currently invalid address as the prefix FFxE
- // is only valid for x = {1,0} as the rest are reserved
- addrName = "FFF5:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 site-local multicast address " + addrName
- + " not detected.", addr.isMCSiteLocal());
-
- // a sample MC organizational address
- addrName = "FF08:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue(
- "IPv6 organization multicast address "
- + addrName
- + " incorrectly indicated as a site-local mulitcast address.",
- !addr.isMCSiteLocal());
-
- // a sample MC global address
- addrName = "FF0E:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue(
- "IPv6 global mulitcast address "
- + addrName
- + " incorrectly indicated as a site-local mulitcast address.",
- !addr.isMCSiteLocal());
-
- // a sample MC link address
- addrName = "FF02:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue(
- "IPv6 link-local multicast address "
- + addrName
- + " incorrectly indicated as a site-local mulitcast address.",
- !addr.isMCSiteLocal());
-
- // a sample MC Node
- addrName = "FF01:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue(
- "IPv6 mulitcast node address "
- + addrName
- + " incorrectly indicated as a site-local mulitcast address.",
- !addr.isMCSiteLocal());
-
- // IPv4-mapped IPv6 addresses
- addrName = "::FFFF:239.255.0.0";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv4 site-local multicast address " + addrName
- + " not identified as a site-local multicast address.",
- addr.isMCSiteLocal());
-
- addrName = "::FFFF:239.255.255.255";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv4 site-local multicast address " + addrName
- + " not identified as a site-local multicast address.",
- addr.isMCSiteLocal());
-
- } catch (Exception e) {
- fail("Unknown address : " + addrName);
- }
- }
-
- /**
- * @tests java.net.Inet6Address#isMCOrgLocal()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMCOrgLocal",
- args = {}
- )
- public void test_isMCOrgLocal() {
- String addrName = "";
- try {
- // IP V6 regular address tests for Mulitcase organization-local
- // addresses
- //
- // Multicast global addresses are FFxE:/112 where x is
- // a set of flags, and the addition 112 bits make up
- // the global address space
-
- addrName = "FF08::0";
- InetAddress addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 organization-local mutlicast address " + addrName
- + " not detected.", addr.isMCOrgLocal());
-
- addrName = "FF08:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 organization-local multicast address " + addrName
- + " not detected.", addr.isMCOrgLocal());
-
- // a currently invalid address as the prefix FFxE
- // is only valid for x = {1,0} as the rest are reserved
- addrName = "FFF8::0";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 organization-local mutlicast address " + addrName
- + " not detected.", addr.isMCOrgLocal());
-
- // a currently invalid address as the prefix FFxE
- // is only valid for x = {1,0} as the rest are reserved
- addrName = "FFF8:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 organization-local multicast address " + addrName
- + " not detected.", addr.isMCOrgLocal());
-
- // a sample MC global address
- addrName = "FF0E:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue(
- "IPv6 global multicast address "
- + addrName
- + " incorrectly indicated as an organization-local mulitcast address.",
- !addr.isMCOrgLocal());
-
- // a sample MC site address
- addrName = "FF05:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue(
- "IPv6 site-local mulitcast address "
- + addrName
- + " incorrectly indicated as an organization-local mulitcast address.",
- !addr.isMCOrgLocal());
-
- // a sample MC link address
- addrName = "FF02:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue(
- "IPv6 link-local multicast address "
- + addrName
- + " incorrectly indicated as an organization-local mulitcast address.",
- !addr.isMCOrgLocal());
-
- // a sample MC Node
- addrName = "FF01:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue(
- "IPv6 mulitcast node address "
- + addrName
- + " incorrectly indicated as an organization-local mulitcast address.",
- !addr.isMCOrgLocal());
-
- // IPv4-mapped IPv6 addresses
-
- addrName = "::FFFF:239.192.0.0";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv4 org-local multicast address " + addrName
- + " not identified as a org-local multicast address.", addr
- .isMCOrgLocal());
-
- addrName = "::FFFF:239.195.255.255";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv4 org-local multicast address " + addrName
- + " not identified as a org-local multicast address.", addr
- .isMCOrgLocal());
-
- } catch (Exception e) {
- fail("Unknown address : " + addrName);
- }
- }
-
- /**
- * @tests java.net.Inet6Address#isIPv4CompatibleAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isIPv4CompatibleAddress",
- args = {}
- )
- public void test_isIPv4CompatibleAddress() {
- String addrName = "";
- Inet6Address addr = null;
-
- try {
-
- // Tests a number of addresses to see if they are compatable with
- // IPv6 addresses
-
- addrName = "FFFF::42:42"; // 11111111 = FFFF
- addr = (Inet6Address) InetAddress.getByName(addrName);
- assertTrue("A non-compatable IPv6 address " + addrName
- + " incorrectly identified as a IPv4 compatable address.",
- !addr.isIPv4CompatibleAddress());
-
- // IPv4-compatible IPv6 address tests
- //
- // Now create 2 IP v6 addresses that are IP v4 compatable
- // to IP v6 addresses.
-
- addrName = "::0.0.0.0";
- addr = (Inet6Address) InetAddress.getByName(addrName);
- assertTrue("IPv4 compatable address " + addrName
- + " not detected correctly.", addr
- .isIPv4CompatibleAddress());
-
- addrName = "::255.255.255.255"; // an ipv4 non-multicast address
- addr = (Inet6Address) InetAddress.getByName(addrName);
- assertTrue("IPv4 compatable address " + addrName
- + " not detected correctly.", addr
- .isIPv4CompatibleAddress());
-
- } catch (Exception e) {
- e.printStackTrace();
- fail("Unknown address : " + addrName);
- }
- }
-
- /**
- * @tests java.net.Inet6Address#getByName(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getByName",
- args = {java.lang.String.class}
- )
- public void test_getByNameLjava_lang_String() throws Exception {
- // ones to add "::255.255.255.255", "::FFFF:0.0.0.0",
- // "0.0.0.0.0.0::255.255.255.255", "F:F:F:F:F:F:F:F",
- // "[F:F:F:F:F:F:F:F]"
- String validIPAddresses[] = { "::1.2.3.4", "::", "::", "1::0", "1::",
- "::1", "0", /* jdk1.5 accepts 0 as valid */
- "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF",
- "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:255.255.255.255",
- "0:0:0:0:0:0:0:0", "0:0:0:0:0:0:0.0.0.0" };
-
- String invalidIPAddresses[] = { "FFFF:FFFF" };
-
- for (int i = 0; i < validIPAddresses.length; i++) {
-
- InetAddress.getByName(validIPAddresses[i]);
-
- //exercise positive cache
- InetAddress.getByName(validIPAddresses[i]);
-
- if (!validIPAddresses[i].equals("0")) {
- String tempIPAddress = "[" + validIPAddresses[i] + "]";
- InetAddress.getByName(tempIPAddress);
- }
- }
-
- for (int i = 0; i < invalidIPAddresses.length; i++) {
- try {
- InetAddress.getByName(invalidIPAddresses[i]);
- fail("Invalid IP address incorrectly recognized as valid: "
- + invalidIPAddresses[i]);
- } catch (Exception e) {
- }
-
- //exercise negative cache
- try {
- InetAddress.getByName(invalidIPAddresses[i]);
- fail("Invalid IP address incorrectly recognized as valid: "
- + invalidIPAddresses[i]);
- } catch (Exception e) {
- }
- }
-
- class MockSecurityManager extends SecurityManager {
- public void checkPermission(Permission permission) {
- if (permission.getName().equals("setSecurityManager")){
- return;
- }
- if (permission.getName().equals("3d.com")){
- throw new SecurityException();
- }
- super.checkPermission(permission);
- }
- }
-
- SecurityManager oldman = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
- try {
- boolean exception = false;
- try {
- Inet6Address.getByName("3d.com");
- fail("SecurityException was not thrown.");
- } catch (SecurityException ex) {
- //expected
- } catch (Exception ex) {
- fail("getByName threw wrong exception : " + ex.getMessage());
- }
- } finally {
- System.setSecurityManager(oldman);
- }
- }
-
- /**
- * @tests java.net.Inet6Address#getByAddress(String, byte[], int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getByAddress",
- args = {java.lang.String.class, byte[].class, int.class}
- )
- public void test_getByAddressLString$BI() throws UnknownHostException{
- try {
- Inet6Address.getByAddress("123", null, 0);
- fail("should throw UnknownHostException");
- } catch (UnknownHostException uhe) {
- // expected
- }
- byte[] addr1 = { (byte) 127, 0, 0, 1 };
- try {
- Inet6Address.getByAddress("123", addr1, 0);
- fail("should throw UnknownHostException");
- } catch (UnknownHostException uhe) {
- // expected
- }
-
- byte[] addr2 = { (byte) 0xFE, (byte) 0x80, 0, 0, 0, 0, 0, 0, 0x02,
- 0x11, 0x25, (byte) 0xFF, (byte) 0xFE, (byte) 0xF8, (byte) 0x7C,
- (byte) 0xB2 };
-
- // should not throw any exception
- Inet6Address.getByAddress("123", addr2, 3);
- Inet6Address.getByAddress("123", addr2, 0);
- Inet6Address.getByAddress("123", addr2, -1);
- }
-
- /**
- * @tests java.net.Inet6Address#getByAddress(String, byte[],
- * NetworkInterface)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getByAddress",
- args = {java.lang.String.class, byte[].class, java.net.NetworkInterface.class}
- )
- public void test_getByAddressLString$BLNetworkInterface()
- throws UnknownHostException {
- NetworkInterface nif = null;
- try {
- Inet6Address.getByAddress("123", null, nif);
- fail("should throw UnknownHostException");
- } catch (UnknownHostException uhe) {
- // expected
- }
- byte[] addr1 = { (byte) 127, 0, 0, 1 };
- try {
- Inet6Address.getByAddress("123", addr1, nif);
- fail("should throw UnknownHostException");
- } catch (UnknownHostException uhe) {
- // expected
- }
- byte[] addr2 = { (byte) 0xFE, (byte) 0x80, 0, 0, 0, 0, 0, 0, 0x02,
- 0x11, 0x25, (byte) 0xFF, (byte) 0xFE, (byte) 0xF8, (byte)
-
- 0x7C, (byte) 0xB2 };
- // should not throw any exception
- Inet6Address.getByAddress("123", addr2, nif);
- }
-
- /**
- * @throws UnknownHostException
- * @tests java.net.Inet6Address#getScopeID()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getScopeId",
- args = {}
- )
- public void test_getScopeID() throws UnknownHostException {
- Inet6Address v6ia;
- byte[] addr = { (byte) 0xFE, (byte) 0x80, 0, 0, 0, 0, 0, 0, 0x02, 0x11,
- 0x25, (byte) 0xFF, (byte) 0xFE, (byte) 0xF8, (byte) 0x7C,
- (byte) 0xB2 };
-
- v6ia = Inet6Address.getByAddress("123", addr, 3);
- assertEquals(3, v6ia.getScopeId());
-
- v6ia = Inet6Address.getByAddress("123", addr, 0);
- assertEquals(0, v6ia.getScopeId());
-
- v6ia = Inet6Address.getByAddress("123", addr, -1);
- assertEquals(0, v6ia.getScopeId());
- }
-
- /**
- * @tests java.net.Inet6Address#getScopedInterface()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getScopedInterface",
- args = {}
- )
- public void test_getScopedInterface() throws UnknownHostException {
- byte[] addr = { (byte) 0xFE, (byte) 0x80, (byte) 0x09, (byte) 0xb5,
- (byte) 0x6b, (byte) 0xa4, 0, 0, 0, 0, 0, 0, (byte) 0x09,
- (byte) 0xb5, (byte) 0x6b, (byte) 0xa4 };
- Inet6Address v6Addr;
- v6Addr = Inet6Address.getByAddress("123", addr, null);
- assertNull(v6Addr.getScopedInterface());
- }
-
-
- int bytesToInt(byte bytes[], int start) {
-
- int byteMask = 255;
- int value = ((bytes[start + 3] & byteMask))
- | ((bytes[start + 2] & byteMask) << 8)
- | ((bytes[start + 1] & byteMask) << 16)
- | ((bytes[start] & byteMask) << 24);
- return value;
-
- }
-
- String byteArrayToHexString(byte bytes[], boolean leadingZeros) {
-
- String fullString = "";
- int times = bytes.length / 4;
- int intArray[] = new int[times];
- for (int i = 0; i < times; i++) {
- intArray[i] = bytesToInt(bytes, i * 4);
- }
-
- return intArrayToHexString(intArray, leadingZeros);
- }
-
- void intToBytes(int value, byte bytes[], int start) {
-
- int byteMask = 255;
- bytes[start + 3] = (byte) (value & byteMask);
- bytes[start + 2] = (byte) ((value >> 8) & byteMask);
- bytes[start + 1] = (byte) ((value >> 16) & byteMask);
- bytes[start] = (byte) ((value >> 24) & byteMask);
- }
-
- String intArrayToHexString(int ints[], boolean leadingZeros) {
-
- String fullString = "";
- String tempString;
- int intsLength = ints.length;
- for (int i = 0; i < intsLength; i++) {
- tempString = Integer.toHexString(ints[i]);
- while (tempString.length() < 4 && leadingZeros) {
- tempString = "0" + tempString;
- }
- if (i + 1 < intsLength) {
- tempString += ":";
- }
- fullString += tempString;
- }
-
- return fullString.toUpperCase();
- }
-
- // comparator for Inet6Address objects
- private static final SerializableAssert COMPARATOR = new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
-
- Inet6Address initAddr = (Inet6Address) initial;
- Inet6Address desrAddr = (Inet6Address) deserialized;
-
- byte[] iaAddresss = initAddr.getAddress();
- byte[] deIAAddresss = desrAddr.getAddress();
- for (int i = 0; i < iaAddresss.length; i++) {
- assertEquals(iaAddresss[i], deIAAddresss[i]);
- }
- assertEquals(initAddr.getScopeId(), desrAddr.getScopeId());
- assertEquals(initAddr.getScopedInterface(), desrAddr
- .getScopedInterface());
- }
- };
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Checks serialization",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- byte[] localv6 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
-
- SerializationTest.verifySelf(InetAddress.getByAddress(localv6),
- COMPARATOR);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Checks serialization",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- byte[] localv6 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
-
- Object[] addresses = { InetAddress.getByAddress(localv6),
- // Regression for Harmony-1039: ser-form has
- // null interface name
- InetAddress.getByAddress(localv6) };
-
- SerializationTest.verifyGolden(this, addresses, COMPARATOR);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equals() throws Exception {
- InetAddress addr = Inet6Address.getByName("239.191.255.255");
- assertTrue(addr.equals(addr));
- InetAddress addr1 = Inet6Address.getByName("127.0.0.1");
- InetAddress addr2 = Inet6Address.getByName("localhost");
- assertTrue(addr1.equals(addr2));
- assertFalse(addr.equals(addr1));
-
- InetAddress addr3 = Inet6Address.getByName("127.0.0");
- assertFalse(addr1.equals(addr3));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getHostAddress",
- args = {}
- )
- public void test_getHostAddress() throws Exception {
- InetAddress addr = Inet6Address.getByName("localhost");
- assertEquals("127.0.0.1", addr.getHostAddress());
-
- addr = Inet6Address.getByName("127.0.0.1");
- assertEquals("127.0.0.1", addr.getHostAddress());
-
- addr = Inet6Address.getByName("224.0.0.0");
- assertEquals("224.0.0.0", addr.getHostAddress());
-
- addr = Inet6Address.getByName("1");
- assertEquals("0.0.0.1", addr.getHostAddress());
-
- addr = Inet6Address.getByName("1.1");
- assertEquals("1.0.0.1", addr.getHostAddress());
-
- addr = Inet6Address.getByName("1.1.1");
- assertEquals("1.1.0.1", addr.getHostAddress());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() throws Exception {
- InetAddress addr1 = Inet6Address.getByName("1.1");
- InetAddress addr2 = Inet6Address.getByName("1.1.1");
- assertFalse(addr1.hashCode() == addr2.hashCode());
-
- addr2 = Inet6Address.getByName("1.0.0.1");
- assertTrue(addr1.hashCode() == addr2.hashCode());
-
- addr1 = Inet6Address.getByName("127.0.0.1");
- addr2 = Inet6Address.getByName("localhost");
- assertTrue(addr1.hashCode() == addr2.hashCode());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() throws Exception {
- String validIPAddresses[] = { "::1.2.3.4", "::", "::", "1::0", "1::",
- "::1", "0", /* jdk1.5 accepts 0 as valid */
- "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF",
- "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:255.255.255.255",
- "0:0:0:0:0:0:0:0", "0:0:0:0:0:0:0.0.0.0" };
-
- String [] resultStrings = {"/0:0:0:0:0:0:102:304", "/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:0:0:0:0:0:0",
- "/0:0:0:0:0:0:0:1",
- "/0.0.0.0", "/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
- "/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", "/0:0:0:0:0:0:0:0",
- "/0:0:0:0:0:0:0:0"};
-
- for(int i = 0; i < validIPAddresses.length; i++) {
- InetAddress ia = Inet6Address.getByName(validIPAddresses[i]);
- String result = ia.toString();
- assertNotNull(result);
- //assertEquals("toString method returns incorrect value: " +
- // result, resultStrings[i], result);
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/InetAddressTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/InetAddressTest.java
deleted file mode 100644
index 1cfb1cb..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/InetAddressTest.java
+++ /dev/null
@@ -1,1096 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.IOException;
-import java.io.Serializable;
-import java.net.DatagramSocket;
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.NetworkInterface;
-import java.net.UnknownHostException;
-import java.security.Permission;
-import java.util.ArrayList;
-import java.util.Enumeration;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-import tests.support.Support_Configuration;
-
-@TestTargetClass(InetAddress.class)
-public class InetAddressTest extends junit.framework.TestCase {
-
- private static boolean someoneDone[] = new boolean[2];
-
- protected static boolean threadedTestSucceeded;
-
- protected static String threadedTestErrorString;
-
- /**
- * This class is used to test inet_ntoa, gethostbyaddr and gethostbyname
- * functions in the VM to make sure they're threadsafe. getByName will cause
- * the gethostbyname function to be called. getHostName will cause the
- * gethostbyaddr to be called. getHostAddress will cause inet_ntoa to be
- * called.
- */
- static class threadsafeTestThread extends Thread {
- private String lookupName;
-
- private InetAddress testAddress;
-
- private int testType;
-
- /*
- * REP_NUM can be adjusted if desired. Since this error is
- * non-deterministic it may not always occur. Setting REP_NUM higher,
- * increases the chances of an error being detected, but causes the test
- * to take longer. Because the Java threads spend a lot of time
- * performing operations other than running the native code that may not
- * be threadsafe, it is quite likely that several thousand iterations
- * will elapse before the first error is detected.
- */
- private static final int REP_NUM = 20000;
-
- public threadsafeTestThread(String name, String lookupName,
- InetAddress testAddress, int type) {
- super(name);
- this.lookupName = lookupName;
- this.testAddress = testAddress;
- testType = type;
- }
-
- public void run() {
- try {
- String correctName = testAddress.getHostName();
- String correctAddress = testAddress.getHostAddress();
- long startTime = System.currentTimeMillis();
-
- synchronized (someoneDone) {
- }
-
- for (int i = 0; i < REP_NUM; i++) {
- if (someoneDone[testType]) {
- break;
- } else if ((i % 25) == 0
- && System.currentTimeMillis() - startTime > 240000) {
- System.out
- .println("Exiting due to time limitation after "
- + i + " iterations");
- break;
- }
-
- InetAddress ia = InetAddress.getByName(lookupName);
- String hostName = ia.getHostName();
- String hostAddress = ia.getHostAddress();
-
- // Intentionally not looking for exact name match so that
- // the test works across different platforms that may or
- // may not include a domain suffix on the hostname
- if (!hostName.startsWith(correctName)) {
- threadedTestSucceeded = false;
- threadedTestErrorString = (testType == 0 ? "gethostbyname"
- : "gethostbyaddr")
- + ": getHostName() returned "
- + hostName
- + " instead of " + correctName;
- break;
- }
- // IP addresses should match exactly
- if (!correctAddress.equals(hostAddress)) {
- threadedTestSucceeded = false;
- threadedTestErrorString = (testType == 0 ? "gethostbyname"
- : "gethostbyaddr")
- + ": getHostName() returned "
- + hostAddress
- + " instead of " + correctAddress;
- break;
- }
-
- }
- someoneDone[testType] = true;
- } catch (Exception e) {
- threadedTestSucceeded = false;
- threadedTestErrorString = e.toString();
- }
- }
- }
-
- /**
- * @tests java.net.InetAddress#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean java.net.InetAddress.equals(java.lang.Object)
- try {
- InetAddress ia1 = InetAddress
- .getByName(Support_Configuration.InetTestAddress);
- InetAddress ia2 = InetAddress
- .getByName(Support_Configuration.InetTestIP);
- assertTrue("Equals returned incorrect result - " + ia1 + " != "
- + ia2, ia1.equals(ia2));
- } catch (Exception e) {
- fail("Exception during equals test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.net.InetAddress#getAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAddress",
- args = {}
- )
- public void test_getAddress() {
- // Test for method byte [] java.net.InetAddress.getAddress()
- try {
- InetAddress ia = InetAddress
- .getByName(Support_Configuration.InetTestIP);
- // BEGIN android-changed
- // using different address. The old one was { 9, 26, -56, -111 }
- // this lead to a crash, also in RI.
- byte[] caddr = Support_Configuration.InetTestAddr;
- // END android-changed
- byte[] addr = ia.getAddress();
- for (int i = 0; i < addr.length; i++)
- assertTrue("Incorrect address returned", caddr[i] == addr[i]);
- } catch (java.net.UnknownHostException e) {
- }
- }
-
- /**
- * @tests java.net.InetAddress#getAllByName(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAllByName",
- args = {java.lang.String.class}
- )
- public void test_getAllByNameLjava_lang_String() throws Exception {
- // Test for method java.net.InetAddress []
- // java.net.InetAddress.getAllByName(java.lang.String)
- InetAddress[] all = InetAddress
- .getAllByName(Support_Configuration.SpecialInetTestAddress);
- assertNotNull(all);
- // Number of aliases depends on individual test machine
- assertTrue(all.length >= 1);
- for (InetAddress alias : all) {
- // Check that each alias has the same hostname. Intentionally not
- // checking for exact string match.
- assertTrue(alias.getHostName().startsWith(
- Support_Configuration.SpecialInetTestAddress));
- }// end for all aliases
-
- // check the getByName if there is a security manager.
- SecurityManager oldman = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
- try {
- boolean exception = false;
- try {
- InetAddress.getByName("3d.com");
- } catch (SecurityException ex) {
- exception = true;
- } catch (Exception ex) {
- fail("getByName threw wrong exception : " + ex.getMessage());
- }
- assertTrue("expected SecurityException", exception);
- } finally {
- System.setSecurityManager(oldman);
- }
-
- //Regression for HARMONY-56
- InetAddress[] ia = InetAddress.getAllByName(null);
- assertEquals("Assert 0: No loopback address", 1, ia.length);
- assertTrue("Assert 1: getAllByName(null) not loopback",
- ia[0].isLoopbackAddress());
-
- try {
- InetAddress.getAllByName("unknown.host");
- fail("UnknownHostException was not thrown.");
- } catch(UnknownHostException uhe) {
- //expected
- }
- }
-
- /**
- * @tests java.net.InetAddress#getByName(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getByName",
- args = {java.lang.String.class}
- )
- public void test_getByNameLjava_lang_String() throws Exception {
- // Test for method java.net.InetAddress
- // java.net.InetAddress.getByName(java.lang.String)
- InetAddress ia2 = InetAddress
- .getByName(Support_Configuration.InetTestIP);
-
- // Intentionally not testing for exact string match
- /* FIXME: comment the assertion below because it is platform/configuration dependent
- * Please refer to HARMONY-1664 (https://issues.apache.org/jira/browse/HARMONY-1664)
- * for details
- */
-// assertTrue(
-// "Expected " + Support_Configuration.InetTestAddress + "*",
-// ia2.getHostName().startsWith(Support_Configuration.InetTestAddress));
-
- // TODO : Test to ensure all the address formats are recognized
- InetAddress i = InetAddress.getByName("1.2.3");
- assertEquals("1.2.0.3",i.getHostAddress());
- i = InetAddress.getByName("1.2");
- assertEquals("1.0.0.2",i.getHostAddress());
- i = InetAddress.getByName(String.valueOf(0xffffffffL));
- assertEquals("255.255.255.255",i.getHostAddress());
- // BEGIN android-removed
- // This test checks a bug in the RI that allows any number of '.' after
- // a valid ipv4 address. This bug doesn't exist in this implementation.
- // String s = "222.222.222.222....";
- // i = InetAddress.getByName(s);
- // assertEquals("222.222.222.222",i.getHostAddress());
- // END android-removed
-
- class MockSecurityManager extends SecurityManager {
- public void checkPermission(Permission permission) {
- if (permission.getName().equals("setSecurityManager")){
- return;
- }
- if (permission.getName().equals("3d.com")){
- throw new SecurityException();
- }
- super.checkPermission(permission);
- }
-
- public void checkConnect(String host, int port) {
- if(host.equals("google.com")) {
- throw new SecurityException();
- }
- }
- }
- SecurityManager oldman = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
- try {
- boolean exception = false;
- try {
- InetAddress.getByName("google.com");
- fail("SecurityException was not thrown.");
- } catch (SecurityException ex) {
- //expected
- } catch (Exception ex) {
- fail("getByName threw wrong exception : " + ex.getMessage());
- }
- } finally {
- System.setSecurityManager(oldman);
- }
-
- try {
- InetAddress.getByName("0.0.0.0.0");
- fail("UnknownHostException was not thrown.");
- } catch(UnknownHostException ue) {
- //expected
- }
- }
-
- /**
- * @tests java.net.InetAddress#getHostAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getHostAddress",
- args = {}
- )
- public void test_getHostAddress() {
- // Test for method java.lang.String
- // java.net.InetAddress.getHostAddress()
- try {
- InetAddress ia2 = InetAddress
- .getByName(Support_Configuration.InetTestAddress);
- assertTrue("getHostAddress returned incorrect result: "
- + ia2.getHostAddress() + " != "
- + Support_Configuration.InetTestIP, ia2.getHostAddress()
- .equals(Support_Configuration.InetTestIP));
- } catch (Exception e) {
- fail("Exception during getHostAddress test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.net.InetAddress#getHostName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getHostName",
- args = {}
- )
- public void test_getHostName() throws Exception {
- // Test for method java.lang.String java.net.InetAddress.getHostName()
- InetAddress ia = InetAddress
- .getByName(Support_Configuration.InetTestIP);
-
- // Intentionally not testing for exact string match
- /* FIXME: comment the assertion below because it is platform/configuration dependent
- * Please refer to HARMONY-1664 (https://issues.apache.org/jira/browse/HARMONY-1664)
- * for details
- */
-// assertTrue(
-// "Expected " + Support_Configuration.InetTestAddress + "*",
-// ia.getHostName().startsWith(Support_Configuration.InetTestAddress));
-
- // Test for any of the host lookups, where the default SecurityManager
- // is installed.
-
- SecurityManager oldman = System.getSecurityManager();
- try {
- String exp = Support_Configuration.InetTestIP;
- System.setSecurityManager(new MockSecurityManager());
- ia = InetAddress.getByName(exp);
- String ans = ia.getHostName();
- /* FIXME: comment the assertion below because it is platform/configuration dependent
- * Please refer to HARMONY-1664 (https://issues.apache.org/jira/browse/HARMONY-1664)
- * for details
- */
- // assertEquals(Support_Configuration.InetTestIP, ans);
- } finally {
- System.setSecurityManager(oldman);
- }
-
- // Make sure there is no caching
- String originalPropertyValue = System
- .getProperty("networkaddress.cache.ttl");
- System.setProperty("networkaddress.cache.ttl", "0");
-
- // Test for threadsafety
- try {
- InetAddress lookup1 = InetAddress
- .getByName(Support_Configuration.InetTestAddress);
- assertTrue(lookup1 + " expected "
- + Support_Configuration.InetTestIP,
- Support_Configuration.InetTestIP.equals(lookup1
- .getHostAddress()));
- InetAddress lookup2 = InetAddress
- .getByName(Support_Configuration.InetTestAddress2);
- assertTrue(lookup2 + " expected "
- + Support_Configuration.InetTestIP2,
- Support_Configuration.InetTestIP2.equals(lookup2
- .getHostAddress()));
- threadsafeTestThread thread1 = new threadsafeTestThread("1",
- lookup1.getHostName(), lookup1, 0);
- threadsafeTestThread thread2 = new threadsafeTestThread("2",
- lookup2.getHostName(), lookup2, 0);
- threadsafeTestThread thread3 = new threadsafeTestThread("3",
- lookup1.getHostAddress(), lookup1, 1);
- threadsafeTestThread thread4 = new threadsafeTestThread("4",
- lookup2.getHostAddress(), lookup2, 1);
-
- // initialize the flags
- threadedTestSucceeded = true;
- synchronized (someoneDone) {
- thread1.start();
- thread2.start();
- thread3.start();
- thread4.start();
- }
- thread1.join();
- thread2.join();
- thread3.join();
- thread4.join();
- /* FIXME: comment the assertion below because it is platform/configuration dependent
- * Please refer to HARMONY-1664 (https://issues.apache.org/jira/browse/HARMONY-1664)
- * for details
- */
-// assertTrue(threadedTestErrorString, threadedTestSucceeded);
- } finally {
- // restore the old value of the property
- if (originalPropertyValue == null)
- // setting the property to -1 has the same effect as having the
- // property be null
- System.setProperty("networkaddress.cache.ttl", "-1");
- else
- System.setProperty("networkaddress.cache.ttl",
- originalPropertyValue);
- }
- }
-
- /**
- * @tests java.net.InetAddress#getLocalHost()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "UnknownHostException should be thrown if no IP address for the host could be found.",
- method = "getLocalHost",
- args = {}
- )
- public void test_getLocalHost() {
- // Test for method java.net.InetAddress
- // java.net.InetAddress.getLocalHost()
- try {
- // We don't know the host name or ip of the machine
- // running the test, so we can't build our own address
- DatagramSocket dg = new DatagramSocket(0, InetAddress
- .getLocalHost());
- assertTrue("Incorrect host returned", InetAddress.getLocalHost()
- .equals(dg.getLocalAddress()));
- dg.close();
- } catch (Exception e) {
- fail("Exception during getLocalHost test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.net.InetAddress#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- // Test for method int java.net.InetAddress.hashCode()
- try {
- InetAddress host = InetAddress
- .getByName(Support_Configuration.InetTestAddress);
- int hashcode = host.hashCode();
- assertTrue("Incorrect hash returned: " + hashcode + " from host: "
- + host, hashcode == Support_Configuration.InetTestHashcode);
- } catch (java.net.UnknownHostException e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.net.InetAddress#isMulticastAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMulticastAddress",
- args = {}
- )
- public void test_isMulticastAddress() {
- // Test for method boolean java.net.InetAddress.isMulticastAddress()
- try {
- InetAddress ia2 = InetAddress.getByName("239.255.255.255");
- assertTrue("isMulticastAddress returned incorrect result", ia2
- .isMulticastAddress());
- } catch (Exception e) {
- fail("Exception during isMulticastAddress test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.net.InetAddress#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() throws Exception {
- // Test for method java.lang.String java.net.InetAddress.toString()
- InetAddress ia2 = InetAddress
- .getByName(Support_Configuration.InetTestIP);
- assertEquals("/" + Support_Configuration.InetTestIP, ia2.toString());
- // Regression for HARMONY-84
- InetAddress addr = InetAddress.getByName("localhost");
- assertEquals("Assert 0: wrong string from name", "localhost/127.0.0.1", addr.toString());
- InetAddress addr2 = InetAddress.getByAddress(new byte[]{127, 0, 0, 1});
- assertEquals("Assert 1: wrong string from address", "/127.0.0.1", addr2.toString());
- }
-
- /**
- * @tests java.net.InetAddress#getByAddress(java.lang.String, byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getByAddress",
- args = {java.lang.String.class, byte[].class}
- )
- public void test_getByAddressLjava_lang_String$B() {
- // Check an IPv4 address with an IPv6 hostname
- byte ipAddress[] = { 127, 0, 0, 1 };
- String addressStr = "::1";
- try {
- InetAddress addr = InetAddress.getByAddress(addressStr, ipAddress);
- addr = InetAddress.getByAddress(ipAddress);
- } catch (UnknownHostException e) {
- fail("Unexpected problem creating IP Address "
- + ipAddress.length);
- }
-
- byte ipAddress2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 127, 0, 0,
- 1 };
- addressStr = "::1";
- try {
- InetAddress addr = InetAddress.getByAddress(addressStr, ipAddress2);
- addr = InetAddress.getByAddress(ipAddress);
- } catch (UnknownHostException e) {
- fail("Unexpected problem creating IP Address "
- + ipAddress.length);
- }
-
- try {
- InetAddress addr = InetAddress.getByAddress(addressStr,
- new byte [] {0, 0, 0, 0, 0});
- fail("UnknownHostException was thrown.");
- } catch(UnknownHostException uhe) {
- //expected
- }
- }
-
- /**
- * @tests java.net.InetAddress#getCanonicalHostName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCanonicalHostName",
- args = {}
- )
- public void test_getCanonicalHostName() throws Exception {
- InetAddress theAddress = null;
- theAddress = InetAddress.getLocalHost();
- assertTrue("getCanonicalHostName returned a zero length string ",
- theAddress.getCanonicalHostName().length() != 0);
- assertTrue("getCanonicalHostName returned an empty string ",
- !theAddress.equals(""));
-
- // test against an expected value
- InetAddress ia = InetAddress
- .getByName(Support_Configuration.InetTestIP);
-
- // Intentionally not testing for exact string match
- /* FIXME: comment the assertion below because it is platform/configuration dependent
- * Please refer to HARMONY-1664 (https://issues.apache.org/jira/browse/HARMONY-1664)
- * for details
- */
-// assertTrue(
-// "Expected " + Support_Configuration.InetTestAddress + "*",
-// ia.getCanonicalHostName().startsWith(Support_Configuration.InetTestAddress));
- }
-
- /**
- * @tests java.net.InetAddress#isReachableI
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException checking missed (if network error occurs).",
- method = "isReachable",
- args = {int.class}
- )
- public void test_isReachableI() throws Exception {
- InetAddress ia = Inet4Address.getByName("127.0.0.1");
- assertTrue(ia.isReachable(10000));
- ia = Inet4Address.getByName("127.0.0.1");
- try {
- ia.isReachable(-1);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // correct
- }
- }
-
- /**
- * @tests java.net.InetAddress#isReachableLjava_net_NetworkInterfaceII
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException checking missed (if network error occurs).",
- method = "isReachable",
- args = {java.net.NetworkInterface.class, int.class, int.class}
- )
- public void test_isReachableLjava_net_NetworkInterfaceII() throws Exception {
- // tests local address
- InetAddress ia = Inet4Address.getByName("127.0.0.1");
- assertTrue(ia.isReachable(null, 0, 10000));
- ia = Inet4Address.getByName("127.0.0.1");
- try {
- ia.isReachable(null, -1, 10000);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // correct
- }
- try {
- ia.isReachable(null, 0, -1);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // correct
- }
- try {
- ia.isReachable(null, -1, -1);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // correct
- }
- // tests nowhere
- ia = Inet4Address.getByName("1.1.1.1");
- assertFalse(ia.isReachable(1000));
- assertFalse(ia.isReachable(null, 0, 1000));
-
- // Regression test for HARMONY-1842.
- ia = InetAddress.getByName("localhost"); //$NON-NLS-1$
- Enumeration<NetworkInterface> nif = NetworkInterface.getNetworkInterfaces();
- NetworkInterface netif;
- while(nif.hasMoreElements()) {
- netif = nif.nextElement();
- ia.isReachable(netif, 10, 1000);
- }
- }
-
- // comparator for InetAddress objects
- private static final SerializableAssert COMPARATOR = new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
-
- InetAddress initAddr = (InetAddress) initial;
- InetAddress desrAddr = (InetAddress) deserialized;
-
- byte[] iaAddresss = initAddr.getAddress();
- byte[] deIAAddresss = desrAddr.getAddress();
- for (int i = 0; i < iaAddresss.length; i++) {
- assertEquals(iaAddresss[i], deIAAddresss[i]);
- }
- assertEquals(initAddr.getHostName(), desrAddr.getHostName());
- }
- };
-
- // Regression Test for Harmony-2290
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- notes = "Regeression test. Functional test.",
- method = "isReachable",
- args = {java.net.NetworkInterface.class, int.class, int.class}
- )
- public void test_isReachableLjava_net_NetworkInterfaceII_loopbackInterface() throws IOException {
- final int TTL = 20;
- final int TIME_OUT = 3000;
-
- NetworkInterface loopbackInterface = null;
- ArrayList<InetAddress> localAddresses = new ArrayList<InetAddress>();
- Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
- .getNetworkInterfaces();
- while (networkInterfaces.hasMoreElements()) {
- NetworkInterface networkInterface = networkInterfaces.nextElement();
- Enumeration<InetAddress> addresses = networkInterface
- .getInetAddresses();
- while (addresses.hasMoreElements()) {
- InetAddress address = addresses.nextElement();
- if (address.isLoopbackAddress()) {
- loopbackInterface = networkInterface;
- } else {
- localAddresses.add(address);
- }
- }
- }
-
- //loopbackInterface can reach local address
- if (null != loopbackInterface) {
- for (InetAddress destAddress : localAddresses) {
- assertTrue(destAddress.isReachable(loopbackInterface, TTL, TIME_OUT));
- }
- }
-
- //loopback Interface cannot reach outside address
- InetAddress destAddress = InetAddress.getByName("www.google.com");
- assertFalse(destAddress.isReachable(loopbackInterface, TTL, TIME_OUT));
- }
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Checks serialization.",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(InetAddress.getByName("localhost"),
- COMPARATOR);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Checks serialization.",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this,
- InetAddress.getByName("localhost"), COMPARATOR);
- }
-
- /**
- * @tests java.net.InetAddress#getByAddress(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getByAddress",
- args = {byte[].class}
- )
- public void test_getByAddress() {
- byte ipAddress[] = { 127, 0, 0, 1 };
- try {
- InetAddress.getByAddress(ipAddress);
- } catch (UnknownHostException e) {
- fail("Unexpected problem creating IP Address "
- + ipAddress.length);
- }
-
- byte ipAddress2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 127, 0, 0,
- 1 };
- try {
- InetAddress.getByAddress(ipAddress2);
- } catch (UnknownHostException e) {
- fail("Unexpected problem creating IP Address "
- + ipAddress.length);
- }
-
- // Regression for HARMONY-61
- try {
- InetAddress.getByAddress(null);
- fail("Assert 0: UnknownHostException must be thrown");
- } catch (UnknownHostException e) {
- // Expected
- }
-
- try {
- byte [] byteArray = new byte[] {};
- InetAddress.getByAddress(byteArray);
- fail("Assert 1: UnknownHostException must be thrown");
- } catch (UnknownHostException e) {
- // Expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isAnyLocalAddress",
- args = {}
- )
- public void test_isAnyLocalAddress() throws Exception {
- byte [] ipAddress1 = { 127, 42, 42, 42 };
- InetAddress ia1 = InetAddress.getByAddress(ipAddress1);
- assertFalse(ia1.isAnyLocalAddress());
-
- byte [] ipAddress2 = { 0, 0, 0, 0 };
- InetAddress ia2 = InetAddress.getByAddress(ipAddress2);
- assertTrue(ia2.isAnyLocalAddress());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isLinkLocalAddress",
- args = {}
- )
- public void test_isLinkLocalAddress() throws Exception {
- String addrName = "FE80::0";
- InetAddress addr = InetAddress.getByName(addrName);
- assertTrue(
- "IPv6 link local address " + addrName + " not detected.",
- addr.isLinkLocalAddress());
-
- addrName = "FEBF::FFFF:FFFF:FFFF:FFFF";
- addr = Inet6Address.getByName(addrName);
- assertTrue(
- "IPv6 link local address " + addrName + " not detected.",
- addr.isLinkLocalAddress());
-
- addrName = "FEC0::1";
- addr = Inet6Address.getByName(addrName);
- assertTrue("IPv6 address " + addrName
- + " detected incorrectly as a link local address.", !addr
- .isLinkLocalAddress());
-
- addrName = "42.42.42.42";
- addr = Inet4Address.getByName(addrName);
- assertTrue("IPv4 address " + addrName
- + " incorrectly reporting as a link local address.", !addr
- .isLinkLocalAddress());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isLoopbackAddress",
- args = {}
- )
- public void test_isLoopbackAddress() throws Exception {
- String addrName = "127.0.0.0";
- InetAddress addr = InetAddress.getByName(addrName);
- assertTrue("Loopback address " + addrName + " not detected.", addr
- .isLoopbackAddress());
-
- addrName = "127.42.42.42";
- addr = InetAddress.getByName(addrName);
- assertTrue("Loopback address " + addrName + " not detected.", addr
- .isLoopbackAddress());
-
- addrName = "42.42.42.42";
- addr = Inet4Address.getByName(addrName);
- assertTrue("Address incorrectly " + addrName
- + " detected as a loopback address.", !addr
- .isLoopbackAddress());
-
-
- addrName = "::FFFF:127.42.42.42";
- addr = InetAddress.getByName(addrName);
- assertTrue("IPv4-compatible IPv6 loopback address " + addrName
- + " not detected.", addr.isLoopbackAddress());
-
- addrName = "::FFFF:42.42.42.42";
- addr = InetAddress.getByName(addrName);
- assertTrue("IPv4-compatible IPv6 address incorrectly " + addrName
- + " detected as a loopback address.", !addr
- .isLoopbackAddress());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMCGlobal",
- args = {}
- )
- public void test_isMCGlobal() throws Exception {
- String addrName = "224.0.0.255";
- InetAddress addr = InetAddress.getByName(addrName);
- assertTrue("IPv4 link-local multicast address " + addrName
- + " incorrectly identified as a global multicast address.",
- !addr.isMCGlobal());
-
- addrName = "224.0.1.0"; // a multicast addr 1110
- addr = Inet4Address.getByName(addrName);
- assertTrue("IPv4 global multicast address " + addrName
- + " not identified as a global multicast address.", addr
- .isMCGlobal());
-
- addrName = "FFFE:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
- addr = InetAddress.getByName(addrName);
- assertTrue("IPv6 global multicast address " + addrName
- + " not detected.", addr.isMCGlobal());
-
- addrName = "FF08:42:42:42:42:42:42:42";
- addr = InetAddress.getByName(addrName);
- assertTrue("IPv6 mulitcast organizational " + addrName
- + " incorrectly indicated as a global address.", !addr
- .isMCGlobal());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMCLinkLocal",
- args = {}
- )
- public void test_isMCLinkLocal() throws Exception {
- String addrName = "224.0.0.255";
- InetAddress addr = InetAddress.getByName(addrName);
- assertTrue("IPv4 link-local multicast address " + addrName
- + " not identified as a link-local multicast address.",
- addr.isMCLinkLocal());
-
- addrName = "224.0.1.0";
- addr = InetAddress.getByName(addrName);
- assertTrue(
- "IPv4 global multicast address "
- + addrName
- + " incorrectly identified as a link-local " +
- "multicast address.",
- !addr.isMCLinkLocal());
-
- addrName = "FFF2:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
- addr = InetAddress.getByName(addrName);
- assertTrue("IPv6 link local multicast address " + addrName
- + " not detected.", addr.isMCLinkLocal());
-
- addrName = "FF08:42:42:42:42:42:42:42";
- addr = InetAddress.getByName(addrName);
- assertTrue(
- "IPv6 organization multicast address "
- + addrName
- + " incorrectly indicated as a link-local " +
- "mulitcast address.",
- !addr.isMCLinkLocal());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMCNodeLocal",
- args = {}
- )
- public void test_isMCNodeLocal() throws Exception {
- String addrName = "224.42.42.42";
- InetAddress addr = InetAddress.getByName(addrName);
- assertTrue(
- "IPv4 multicast address "
- + addrName
- + " incorrectly identified as a node-local " +
- "multicast address.",
- !addr.isMCNodeLocal());
-
- addrName = "FFF1:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
- addr = InetAddress.getByName(addrName);
- assertTrue("IPv6 node-local multicast address " + addrName
- + " not detected.", addr.isMCNodeLocal());
-
- addrName = "FF08:42:42:42:42:42:42:42";
- addr = InetAddress.getByName(addrName);
- assertTrue("IPv6 mulitcast organizational address " + addrName
- + " incorrectly indicated as a node-local address.", !addr
- .isMCNodeLocal());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMCOrgLocal",
- args = {}
- )
- public void test_isMCOrgLocal() throws Exception {
- String addrName = "239.252.0.0"; // a multicast addr 1110
- InetAddress addr = InetAddress.getByName(addrName);
- assertTrue(
- "IPv4 site-local multicast address "
- + addrName
- + " incorrectly identified as a org-local multicast address.",
- !addr.isMCOrgLocal());
-
- addrName = "239.192.0.0"; // a multicast addr 1110
- addr = InetAddress.getByName(addrName);
- assertTrue("IPv4 org-local multicast address " + addrName
- + " not identified as a org-local multicast address.", addr
- .isMCOrgLocal());
-
- addrName = "FFF8:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
- addr = InetAddress.getByName(addrName);
- assertTrue("IPv6 organization-local multicast address " + addrName
- + " not detected.", addr.isMCOrgLocal());
-
- addrName = "FF0E:42:42:42:42:42:42:42";
- addr = InetAddress.getByName(addrName);
- assertTrue(
- "IPv6 global multicast address "
- + addrName
- + " incorrectly indicated as an organization-local mulitcast address.",
- !addr.isMCOrgLocal());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isMCSiteLocal",
- args = {}
- )
- public void test_isMCSiteLocal() throws Exception {
- String addrName = "FFF5:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF";
- InetAddress addr = InetAddress.getByName(addrName);
- assertTrue("IPv6 site-local multicast address " + addrName
- + " not detected.", addr.isMCSiteLocal());
-
- // a sample MC organizational address
- addrName = "FF08:42:42:42:42:42:42:42";
- addr = Inet6Address.getByName(addrName);
- assertTrue(
- "IPv6 organization multicast address "
- + addrName
- + " incorrectly indicated as a site-local " +
- "mulitcast address.",
- !addr.isMCSiteLocal());
-
- addrName = "239.0.0.0";
- addr = Inet4Address.getByName(addrName);
- assertTrue(
- "IPv4 reserved multicast address "
- + addrName
- + " incorrectly identified as a site-local " +
- "multicast address.",
- !addr.isMCSiteLocal());
-
- addrName = "239.255.0.0";
- addr = Inet4Address.getByName(addrName);
- assertTrue("IPv4 site-local multicast address " + addrName
- + " not identified as a site-local multicast address.",
- addr.isMCSiteLocal());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isSiteLocalAddress",
- args = {}
- )
- public void test_isSiteLocalAddress() throws Exception {
- String addrName = "42.42.42.42";
- InetAddress addr = InetAddress.getByName(addrName);
- assertTrue("IPv4 address " + addrName
- + " incorrectly reporting as a site local address.", !addr
- .isSiteLocalAddress());
-
- addrName = "FEFF::FFFF:FFFF:FFFF:FFFF:FFFF";
- addr = InetAddress.getByName(addrName);
- assertTrue(
- "IPv6 site local address " + addrName + " not detected.",
- addr.isSiteLocalAddress());
-
- addrName = "FEBF::FFFF:FFFF:FFFF:FFFF:FFFF";
- addr = InetAddress.getByName(addrName);
- assertTrue("IPv6 address " + addrName
- + " detected incorrectly as a site local address.", !addr
- .isSiteLocalAddress());
- }
-
- class MockSecurityManager extends SecurityManager {
- public void checkPermission(Permission permission) {
- if (permission.getName().equals("setSecurityManager")){
- return;
- }
- if (permission.getName().equals("3d.com")){
- throw new SecurityException();
- }
- super.checkPermission(permission);
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/InetSocketAddressTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/InetSocketAddressTest.java
deleted file mode 100644
index 15f3a5a..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/InetSocketAddressTest.java
+++ /dev/null
@@ -1,421 +0,0 @@
-/* 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.harmony.luni.tests.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.Serializable;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-import java.net.UnknownHostException;
-import java.security.Permission;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(InetSocketAddress.class)
-public class InetSocketAddressTest extends TestCase {
-
- /**
- * @tests java.net.InetSocketAddress#InetSocketAddress(String, int)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InetSocketAddress",
- args = {java.lang.String.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = SocketAddress.class,
- method = "SocketAddress",
- args = {}
- )
- })
- public void test_ConstructorLjava_lang_StringI() throws Exception {
- // regression test for Harmony-1042
- InetSocketAddress address = new InetSocketAddress("127.0.0.1", 0);
- assertNotNull(address.getHostName());
-
- try {
- new InetSocketAddress("127.0.0.1", -1);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- new InetSocketAddress("127.0.0.1", 65536);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- class MockSecurityManager extends SecurityManager {
- public void checkPermission(Permission permission) {
-
- }
-
- public void checkConnect(String host, int port) {
- if(host.equals("google.com")) {
- throw new SecurityException();
- }
- }
- }
- SecurityManager oldman = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
- try {
- boolean exception = false;
- try {
- new InetSocketAddress("google.com", 80);
- fail("SecurityException was not thrown.");
- } catch (SecurityException ex) {
- //expected
- } catch (Exception ex) {
- fail("getByName threw wrong exception : " + ex.getMessage());
- }
- } finally {
- System.setSecurityManager(oldman);
- }
-
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InetSocketAddress",
- args = {java.net.InetAddress.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getHostName",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPort",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = SocketAddress.class,
- method = "SocketAddress",
- args = {}
- )
- })
- public void test_ConstructorLInetAddressI() {
- String validIPAddresses[] = { "::1.2.3.4", "::", "::", "1::0", "1::",
- "::1", "0",
- "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF",
- "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:255.255.255.255",
- "0:0:0:0:0:0:0:0", "0:0:0:0:0:0:0.0.0.0",
- "127.0.0.1", "localhost", "1.1", "42.42.42.42", "0.0.0.0"};
-
- String results [] = { "0:0:0:0:0:0:102:304", "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:0:0:0:0:0:0",
- "0:0:0:0:0:0:0:1", "0.0.0.0",
- "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
- "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
- "0:0:0:0:0:0:0:0", "0:0:0:0:0:0:0:0",
- "localhost", "localhost", "1.0.0.1", "42.42.42.42", "0.0.0.0"};
-
- for(int i = 0; i < validIPAddresses.length; i++) {
- try {
- InetAddress ia = InetAddress.getByName(validIPAddresses[i]);
- InetSocketAddress isa = new InetSocketAddress(ia, 80);
- assertEquals(80,isa.getPort());
- //assertEquals(results[i], isa.getHostName());
- } catch(UnknownHostException uhe) {
- fail("UnknownHostException was thrown for: " +
- validIPAddresses[i]);
- }
- }
- try {
- InetSocketAddress isa = new InetSocketAddress((InetAddress)null, 80);
- assertEquals("0.0.0.0", isa.getHostName());
- } catch(Exception e) {
- fail("Unexpected exception was thrown.");
- }
-
- try {
- InetAddress isa = InetAddress.getByName("localhost");
- new InetSocketAddress(isa, 65536);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- } catch (UnknownHostException e) {
- fail("UnknownHostException was thrown.");
- }
-
- try {
- InetAddress isa = InetAddress.getByName("localhost");
- new InetSocketAddress(isa, -1);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- } catch (UnknownHostException e) {
- fail("UnknownHostException was thrown.");
- }
- }
- @TestTargets ({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InetSocketAddress",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- clazz = SocketAddress.class,
- method = "SocketAddress",
- args = {}
- )
- })
- public void test_ConstructorI() {
-
- InetSocketAddress isa = new InetSocketAddress(65535);
- assertEquals("0.0.0.0", isa.getHostName());
- assertEquals(65535, isa.getPort());
-
- try {
- new InetSocketAddress(-1);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- new InetSocketAddress(65536);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @tests java.net.InetSocketAddress#createUnresolved(String, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is the complete subset of tests for createUnresolved method.",
- method = "createUnresolved",
- args = {java.lang.String.class, int.class}
- )
- public void test_createUnresolvedLjava_lang_StringI() {
- HostPortPair[] legalHostPortPairs = { new HostPortPair("127.0.0.1", 1234),
- new HostPortPair("192.168.0.1", 10000), new HostPortPair("127.0.0", 0),
- new HostPortPair("127.0.0", 65535),
- new HostPortPair("strange host", 65535) };
- for (int i = 0; i < legalHostPortPairs.length; i++) {
- InetSocketAddress isa = InetSocketAddress.createUnresolved(
- legalHostPortPairs[i].host, legalHostPortPairs[i].port);
- assertTrue(isa.isUnresolved());
- assertNull(isa.getAddress());
- assertEquals(isa.getHostName(), legalHostPortPairs[i].host);
- assertEquals(isa.getPort(), legalHostPortPairs[i].port);
- }
- }
-
- /**
- * @tests java.net.InetSocketAddress#createUnresolved(String, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is the complete subset of tests for createUnresolved method.",
- method = "createUnresolved",
- args = {java.lang.String.class, int.class}
- )
- public void test_createUnresolvedLjava_lang_StringI_IllegalArgumentException() {
- HostPortPair[] illegalHostPortPairs = { new HostPortPair(null, 1),
- new HostPortPair("host", -1), new HostPortPair("host", 65536) };
- for (int i = 0; i < illegalHostPortPairs.length; i++) {
- try {
- InetSocketAddress.createUnresolved(
- illegalHostPortPairs[i].host,
- illegalHostPortPairs[i].port);
- fail("should throw IllegalArgumentException, host = "
- + illegalHostPortPairs[i].host + ",port = "
- + illegalHostPortPairs[i].port);
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
- }
-
- /*
- * inner class for createUnresolved test convenience.
- */
- class HostPortPair {
- String host;
-
- int port;
-
- public HostPortPair(String host, int port) {
- this.host = host;
- this.port = port;
- }
- };
-
- // comparator for InetSocketAddress objects
- private static final SerializableAssert COMPARATOR = new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
-
- InetSocketAddress init = (InetSocketAddress) initial;
- InetSocketAddress desr = (InetSocketAddress) deserialized;
-
- assertEquals("HostName", init.getHostName(), desr.getHostName());
- assertEquals("Port", init.getPort(), desr.getPort());
- assertEquals("Address", init.getAddress(), desr.getAddress());
- }
- };
-
- /**
- * @tests serialization/deserialization compatibility.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Checks serialization",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- Object[] testCases = {
- InetSocketAddress.createUnresolved("badhost", 1000), // unresolved
- new InetSocketAddress("Localhost", 1000) };
-
- SerializationTest.verifySelf(testCases, COMPARATOR);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Checks serialization",
- method = "!SerializationGolden",
- args = {}
- )
- public void _testSerializationCompatibility() throws Exception {
-
- Object[] testCases = {
- InetSocketAddress.createUnresolved("badhost", 1000), // unresolved
- new InetSocketAddress("Localhost", 1000) };
-
- SerializationTest.verifyGolden(this, testCases, COMPARATOR);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equals() {
- InetSocketAddress isa1 = new InetSocketAddress(1);
- InetSocketAddress isa2 = new InetSocketAddress(2);
- assertFalse(isa1.equals(isa2));
- InetSocketAddress isa3 = new InetSocketAddress(1);
- assertTrue(isa1.equals(isa3));
-
- isa1 = new InetSocketAddress("localhost", 80);
- isa2 = new InetSocketAddress("127.0.0.1", 80);
- assertTrue(isa1.equals(isa2));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAddress",
- args = {}
- )
- public void test_getAddress() {
-
- String validIPAddresses[] = { "::1.2.3.4", "::", "::", "1::0", "1::",
- "::1", "0",
- "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF",
- "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:255.255.255.255",
- "0:0:0:0:0:0:0:0", "0:0:0:0:0:0:0.0.0.0",
- "127.0.0.1", "localhost", "1.1", "42.42.42.42", "0.0.0.0"};
-
- for(int i = 0; i < validIPAddresses.length; i++) {
- try {
- InetAddress ia = InetAddress.getByName(validIPAddresses[i]);
- InetSocketAddress isa = new InetSocketAddress(ia, 0);
- assertEquals(ia, isa.getAddress());
- } catch(UnknownHostException uhe) {
- fail("UnknownHostException was thrown for: " +
- validIPAddresses[i]);
- }
- }
- InetSocketAddress isa = new InetSocketAddress((InetAddress) null, 0);
- assertNotNull(isa.getAddress());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- InetSocketAddress isa1 = new InetSocketAddress("localhost", 8080);
- InetSocketAddress isa2 = new InetSocketAddress("127.0.0.1", 8080);
- assertTrue(isa1.hashCode() == isa2.hashCode());
-
- InetSocketAddress isa3 = new InetSocketAddress("0.0.0.0", 8080);
- assertFalse(isa1.hashCode() == isa3.hashCode());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isUnresolved",
- args = {}
- )
- public void test_isUnresolved() {
- InetSocketAddress isa1 = new InetSocketAddress("localhost", 80);
- assertFalse(isa1.isUnresolved());
-
- InetSocketAddress sockAddr = new InetSocketAddress("unknown.host", 1000);
- assertTrue(sockAddr.isUnresolved());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- InetSocketAddress isa = new InetSocketAddress("localhost", 80);
- assertNotNull(isa.toString());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URITest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URITest.java
deleted file mode 100644
index e290e27..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URITest.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/* 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.harmony.luni.tests.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.URI;
-import java.net.URISyntaxException;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(URI.class)
-public class URITest extends TestCase {
- /**
- * @tests java.net.URI(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "NullPointerException checking missed.",
- method = "URI",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() throws URISyntaxException {
- // Regression test for HARMONY-23
- try {
- new URI("%3");
- fail("Assert 0: URI constructor failed to throw exception on invalid input.");
- } catch (URISyntaxException e) {
- // Expected
- assertEquals("Assert 1: Wrong index in URISyntaxException.", 0, e.getIndex());
- }
-
- // Regression test for HARMONY-25
- // if port value is negative, the authority should be considered registry-based.
- URI uri = new URI("http://host:-8096/path/index.html");
- assertEquals("Assert 2: returned wrong port value,", -1, uri.getPort());
- assertNull("Assert 3: returned wrong host value,", uri.getHost());
- try {
- uri.parseServerAuthority();
- fail("Assert 4: Expected URISyntaxException");
- } catch (URISyntaxException e){
- // Expected
- }
-
- uri = new URI("http","//myhost:-8096", null);
- assertEquals("Assert 5: returned wrong port value,", -1, uri.getPort());
- assertNull("Assert 6: returned wrong host value,", uri.getHost());
- try {
- uri.parseServerAuthority();
- fail("Assert 7: Expected URISyntaxException");
- } catch (URISyntaxException e){
- // Expected
- }
- }
-
- /**
- * @tests java.net.URI(java.lang.String, java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Exceptions checked only.",
- method = "URI",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String() {
- // scheme can not be empty string
- try {
- new URI("","//authority/path", "fragment");
- fail ("Assert 0: Expected URISyntaxException with empty URI scheme");
- } catch(URISyntaxException e) {
- // Expected
- assertEquals("Assert 1: Wrong index in URISyntaxException.", 0, e.getIndex());
- }
- }
-
- /**
- * @tests java.net.URI#relativize(java.net.URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "NullPointerException checking missed.",
- method = "relativize",
- args = {java.net.URI.class}
- )
- public void test_relativizeLjava_net_URI() throws URISyntaxException{
- URI a = new URI("http://host/dir");
- URI b = new URI("http://host/dir/file?query");
- assertEquals("Assert 0: URI relativized incorrectly,",
- new URI("file?query"), a.relativize(b));
-
- // One URI with empty host
- a = new URI("file:///~/first");
- b = new URI("file://tools/~/first");
- assertEquals("Assert 1: URI relativized incorrectly,",
- new URI("file://tools/~/first"), a.relativize(b));
- assertEquals("Assert 2: URI relativized incorrectly,",
- new URI("file:///~/first"), b.relativize(a));
-
- // Both URIs with empty hosts
- b = new URI("file:///~/second");
- assertEquals("Assert 3: URI relativized incorrectly,",
- new URI("file:///~/second"), a.relativize(b));
- assertEquals("Assert 4: URI relativized incorrectly,",
- new URI("file:///~/first"), b.relativize(a));
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "NullPointerException checking missed.",
- method = "relativize",
- args = {java.net.URI.class}
- )
- public void test_relativizeBasedOneEclipseCoreResources() throws URISyntaxException {
- URI one = new URI("file:/C:/test/ws");
- URI two = new URI("file:/C:/test/ws");
-
- URI empty = new URI("");
- assertEquals(empty, one.relativize(two));
-
- one = new URI("file:/C:/test/ws");
- two = new URI("file:/C:/test/ws/p1");
- URI result = new URI("p1");
- assertEquals(result, one.relativize(two));
-
- one = new URI("file:/C:/test/ws/");
- assertEquals(result, one.relativize(two));
- }
-
- /**
- * @tests java.net.URI#compareTo(java.net.URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.net.URI.class}
- )
- public void test_compareToLjava_net_URI() throws URISyntaxException{
- URI uri1, uri2;
-
- // URIs whose host names have different casing
- uri1 = new URI("http://MixedCaseHost/path/resource");
- uri2 = new URI("http://mixedcasehost/path/resource");
- assertEquals("Assert 0: host name equality failure", 0, uri1.compareTo(uri2));
- assertEquals("Assert 1: host name equality failure", 0, uri1.compareTo(uri2));
-
- // URIs with one undefined component (port)
- uri1 = new URI("http://anyhost:80/path/resource");
- uri2 = new URI("http://anyhost/path/resource");
- assertTrue("Assert 2: comparison failure", uri1.compareTo(uri2) > 0);
- assertTrue("Assert 3: comparison failure", uri2.compareTo(uri1) < 0);
-
- // URIs with one undefined component (user-info)
- uri1 = new URI("http://user-info@anyhost/path/resource");
- uri2 = new URI("http://anyhost/path/resource");
- assertTrue("Assert 4: comparison failure", uri1.compareTo(uri2) > 0);
- assertTrue("Assert 5: comparison failure", uri2.compareTo(uri1) < 0);
-
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLConnectionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLConnectionTest.java
deleted file mode 100644
index 7a6c505..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLConnectionTest.java
+++ /dev/null
@@ -1,2190 +0,0 @@
-/* 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.harmony.luni.tests.java.net;
-
-import dalvik.annotation.BrokenTest;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-import junit.framework.TestCase;
-
-import tests.support.Support_Configuration;
-import tests.support.resource.Support_Resources;
-
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FilePermission;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.net.CacheRequest;
-import java.net.CacheResponse;
-import java.net.FileNameMap;
-import java.net.HttpURLConnection;
-import java.net.JarURLConnection;
-import java.net.MalformedURLException;
-import java.net.ResponseCache;
-import java.net.SocketPermission;
-import java.net.SocketTimeoutException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.net.URLConnection;
-import java.net.URLStreamHandler;
-import java.net.UnknownServiceException;
-import java.security.Permission;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.GregorianCalendar;
-import java.util.List;
-import java.util.Map;
-import java.util.TimeZone;
-
-@TestTargetClass(
- value = URLConnection.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "Default implementation returns always null according to spec.",
- method = "getHeaderField",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "Default implementation returns always null according to spec.",
- method = "getHeaderFieldKey",
- args = {int.class}
- )
- }
-)
-public class URLConnectionTest extends TestCase {
-
- private static final String testString = "Hello World";
-
- private URLConnection fileURLCon;
-
- private URL fileURL;
-
- private JarURLConnection jarURLCon;
-
- private URL jarURL;
-
- private URLConnection gifURLCon;
-
- private URL gifURL;
-
- public boolean isGetCalled;
-
- public boolean isPutCalled;
-
- private Map<String, List<String>> mockHeaderMap;
-
- private InputStream mockIs = new MockInputStream();
-
- public boolean isCacheWriteCalled;
-
- public boolean isAbortCalled;
-
- /**
- * @tests {@link java.net.URLConnection#addRequestProperty(String, String)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Exceptions checked only. Cannot test positive test since getter method is not supported.",
- method = "addRequestProperty",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_addRequestProperty() throws MalformedURLException,
- IOException {
-
-
- MockURLConnection u = new MockURLConnection(new URL(
- "http://www.apache.org"));
-
- try {
- // Regression for HARMONY-604
- u.addRequestProperty(null, "someValue");
- fail("Expected NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- u.connect();
- try {
- // state of connection is checked first
- // so no NPE in case of null 'field' param
- u.addRequestProperty(null, "someValue");
- fail("Expected IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- }
-
- /**
- * @tests {@link java.net.URLConnection#setRequestProperty(String, String)}
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Exceptions checked only -> only partially implemented.",
- method = "setRequestProperty",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_setRequestProperty() throws MalformedURLException,
- IOException {
-
- MockURLConnection u = new MockURLConnection(new URL(
- "http://www.apache.org"));
- try {
- u.setRequestProperty(null, "someValue");
- fail("Expected NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- u.setRequestProperty("user-agent", "Mozilla/5.0 (Windows; U; Windows NT 5.0; de-DE; rv:1.7.5) Gecko/20041122 Firefox/1.0");
- } catch (NullPointerException e) {
- fail("Unexpected Exception");
- }
-
- u.connect();
-
- try {
- // state of connection is checked first
- // so no NPE in case of null 'field' param
- u.setRequestProperty(null, "someValue");
- fail("Expected IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- }
-
- /**
- * @tests {@link java.net.URLConnection#setUseCaches(boolean)}
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Complete together with getUseCaches test.",
- method = "setUseCaches",
- args = {boolean.class}
- )
- public void test_setUseCachesZ() throws MalformedURLException, IOException {
-
- // Regression for HARMONY-71
- MockURLConnection u = new MockURLConnection(new URL(
- "http://www.apache.org"));
- u.connect();
- try {
- u.setUseCaches(true);
- fail("Assert 0: expected an IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- }
-
- /**
- * @tests {@link java.net.URLConnection#setAllowUserInteraction(boolean)}
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Exceptions checked only.",
- method = "setAllowUserInteraction",
- args = {boolean.class}
- )
- public void test_setAllowUserInteractionZ() throws MalformedURLException,
- IOException {
-
- // Regression for HARMONY-72
- MockURLConnection u = new MockURLConnection(new URL(
- "http://www.apache.org"));
- u.connect();
- try {
- u.setAllowUserInteraction(false);
- fail("Assert 0: expected an IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- }
-
- static class MockURLConnection extends URLConnection {
-
- public MockURLConnection(URL url) {
- super(url);
- }
-
- @Override
- public void connect() {
- connected = true;
- }
- }
-
- static class NewHandler extends URLStreamHandler {
- protected URLConnection openConnection(URL u) throws IOException {
- return new HttpURLConnection(u) {
- @Override
- public void connect() throws IOException {
- connected = true;
- }
-
- @Override
- public void disconnect() {
- // do nothing
- }
-
- @Override
- public boolean usingProxy() {
- return false;
- }
- };
- }
- }
-
- class MockCachedResponseCache extends ResponseCache {
-
- public CacheResponse get(URI arg0, String arg1, Map arg2)
- throws IOException {
- if (null == arg0 || null == arg1 || null == arg2) {
- throw new NullPointerException();
- }
- isGetCalled = true;
- return new MockCacheResponse();
- }
-
- public CacheRequest put(URI arg0, URLConnection arg1)
- throws IOException {
- if (null == arg0 || null == arg1) {
- throw new NullPointerException();
- }
- isPutCalled = true;
- return new MockCacheRequest();
- }
- }
-
- class MockNonCachedResponseCache extends ResponseCache {
-
- public CacheResponse get(URI arg0, String arg1, Map arg2)
- throws IOException {
- isGetCalled = true;
- return null;
- }
-
- public CacheRequest put(URI arg0, URLConnection arg1)
- throws IOException {
- isPutCalled = true;
- return new MockCacheRequest();
- }
- }
-
- class MockCacheRequest extends CacheRequest {
-
- public OutputStream getBody() throws IOException {
- isCacheWriteCalled = true;
- return new MockOutputStream();
- }
-
- public void abort() {
- isAbortCalled = true;
- }
-
- }
-
- class MockInputStream extends InputStream {
-
- public int read() throws IOException {
- return 4711;
- }
-
- public int read(byte[] arg0, int arg1, int arg2) throws IOException {
- return 1;
- }
-
- public int read(byte[] arg0) throws IOException {
- return 1;
- }
-
- }
-
- class MockOutputStream extends OutputStream {
-
- public void write(int b) throws IOException {
- isCacheWriteCalled = true;
- }
-
- public void write(byte[] b, int off, int len) throws IOException {
- isCacheWriteCalled = true;
- }
-
- public void write(byte[] b) throws IOException {
- isCacheWriteCalled = true;
- }
- }
-
- class MockCacheResponse extends CacheResponse {
-
- public Map<String, List<String>> getHeaders() throws IOException {
- return mockHeaderMap;
- }
-
- public InputStream getBody() throws IOException {
- return mockIs;
- }
- }
-
-
- private static int port;
-
- static String getContentType(String fileName) throws IOException {
- String resourceName = "org/apache/harmony/luni/tests/" + fileName;
- URL url = ClassLoader.getSystemClassLoader().getResource(resourceName);
- assertNotNull("Cannot find test resource " + resourceName, url);
- return url.openConnection().getContentType();
- }
-
- URL url;
-
- URL url2;
-
- URLConnection uc;
-
- URLConnection uc2;
-
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
-
-// ftpURL = new URL(Support_Configuration.testFTPURL);
-
-
- url = new URL(Support_Configuration.hTTPURLgoogle);
- uc = url.openConnection();
- url2 = new URL(Support_Configuration.hTTPURLyahoo);
- uc2 = url2.openConnection();
-
- fileURL = createTempHelloWorldFile();
- fileURLCon = fileURL.openConnection();
-
- jarURLCon = openJarURLConnection();
- jarURL = jarURLCon.getURL();
-
- gifURLCon = openGifURLConnection();
- gifURL = gifURLCon.getURL();
-
- port = 80;
-
- }
-
- @Override
- public void tearDown()throws Exception {
- super.tearDown();
- ((HttpURLConnection) uc).disconnect();
- ((HttpURLConnection) uc2).disconnect();
-// if (((FtpURLConnection) ftpURLCon).getInputStream() != null) {
-// ((FtpURLConnection) ftpURLCon).getInputStream().close();
-// }
- }
-
- /**
- * @throws URISyntaxException
- * @throws ClassNotFoundException
- * @tests {@link java.net.URLConnection#addRequestProperty(java.lang.String,java.lang.String)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch.",
- method = "addRequestProperty",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_addRequestPropertyLjava_lang_StringLjava_lang_String()
- throws IOException, ClassNotFoundException, URISyntaxException {
- uc.setRequestProperty("prop", "yo");
- uc.setRequestProperty("prop", "yo2");
- assertEquals("yo2", uc.getRequestProperty("prop"));
- Map<String, List<String>> map = uc.getRequestProperties();
- List<String> props = uc.getRequestProperties().get("prop");
- assertEquals(1, props.size());
-
- try {
- // the map should be unmodifiable
- map.put("hi", Arrays.asList(new String[] { "bye" }));
- fail("could modify map");
- } catch (UnsupportedOperationException e) {
- // Expected
- }
- try {
- // the list should be unmodifiable
- props.add("hi");
- fail("could modify list");
- } catch (UnsupportedOperationException e) {
- // Expected
- }
-
- JarURLConnection con1 = openJarURLConnection();
- map = con1.getRequestProperties();
- assertNotNull(map);
- assertEquals(0, map.size());
- try {
- // the map should be unmodifiable
- map.put("hi", Arrays.asList(new String[] { "bye" }));
- fail();
- } catch (UnsupportedOperationException e) {
- // Expected
- }
- }
-
- /**
- * @throws IOException
- * @tests {@link java.net.URLConnection#getAllowUserInteraction()}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch.",
- method = "getAllowUserInteraction",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "From harmony branch.",
- method = "setAllowUserInteraction",
- args = {boolean.class}
- )
- })
- public void test_getAllowUserInteraction() throws IOException {
- uc.setAllowUserInteraction(false);
- assertFalse("getAllowUserInteraction should have returned false", uc
- .getAllowUserInteraction());
-
- uc.setAllowUserInteraction(true);
- assertTrue("getAllowUserInteraction should have returned true", uc
- .getAllowUserInteraction());
-
- uc.connect();
-
- try {
- uc.setAllowUserInteraction(false);
- fail("Exception expected");
- } catch (IllegalStateException e) {
- //ok
- }
-
- // test if setAllowUserInteraction works
- URL serverURL = new URL("http://onearth.jpl.nasa.gov/landsat.cgi");
-
- // connect to server
- URLConnection uc2 = serverURL.openConnection();
- HttpURLConnection conn = (HttpURLConnection) uc2;
- uc2.setAllowUserInteraction(true);
-
- uc2.setDoInput(true);
- uc2.setDoOutput(true);
-
- // get reference to stream to post to
- OutputStream os = uc2.getOutputStream();
-
- InputStream in = uc2.getInputStream();
-
-
- int contentLength = uc2.getContentLength();
- String contentType = uc2.getContentType();
- int numBytesRead = 0;
- int allBytesRead = 0;
-
- byte[] buffer = new byte[4096];
-
- do {
-
- numBytesRead = in.read(buffer);
- allBytesRead += allBytesRead + numBytesRead;
-
- } while (numBytesRead > 0);
-
- assertTrue(allBytesRead > 0);
-
- uc2.connect();
-
- numBytesRead = in.read(buffer);
-
- assertEquals(-1, numBytesRead);
- }
-
- /**
- * @throws IOException
- * @tests {@link java.net.URLConnection#connect()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "connect",
- args = {}
- )
- public void test_connect() throws IOException {
-
- uc.connect();
- ((HttpURLConnection) uc).disconnect();
- uc.connect();
-
- try {
- uc.setDoOutput(false);
- } catch (Exception e) {
- // ok
- }
- }
-
- /**
- * @tests {@link java.net.URLConnection#getContent()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch.",
- method = "getContent",
- args = {}
- )
- public void test_getContent() throws IOException {
- byte[] ba = new byte[testString.getBytes().length];
- String buf = null;
-
- Object obj = fileURLCon.getContent();
- if (obj instanceof String) {
- buf = (String) obj;
- assertTrue("Incorrect content returned from fileURL: "+buf,
- testString.equals(buf.trim()));
- } else if (obj instanceof InputStream) {
- InputStream i = (InputStream) obj;
- BufferedReader r = new BufferedReader(new InputStreamReader(i),testString.getBytes().length);
- buf = r.readLine();
- assertTrue("Incorrect content returned from fileURL: "+buf,
- testString.equals(buf.trim()));
- } else {
- fail("Some unkown type is returned "+obj.toString());
- }
-
- //Exception test
- URL url = new URL("http://a/b/c/?y");
- URLConnection fakeCon = url.openConnection();
- try {
- fakeCon.getContent();
- } catch (IOException e) {
- //ok
- }
-
- ((HttpURLConnection) uc).disconnect();
- try {
- uc.getContent();
- } catch (IOException e) {
- //ok
- }
-
- }
-
- /**
- * @tests {@link java.net.URLConnection#getContent(Class[])}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch.",
- method = "getContent",
- args = {java.lang.Class[].class}
- )
- public void test_getContent_LjavalangClass() throws IOException {
- byte[] ba = new byte[600];
-
- fileURLCon.setDoInput(true);
- fileURLCon.connect();
-
- InputStream helloWorld2 = (InputStream) fileURLCon.getContent(new Class[] {InputStream.class});
- assertNotNull(helloWorld2);
- BufferedReader r = new BufferedReader(new InputStreamReader(helloWorld2),testString.getBytes().length);
- assertTrue("Incorrect content returned from fileURL",
- testString.equals(r.readLine().trim()));
-
- String test = (String) fileURLCon.getContent(new Class[] {String.class} );
- assertNull(test);
-
- //Exception test
- ((HttpURLConnection) uc).disconnect();
- try {
- uc.getContent();
- } catch (IOException e) {
- //ok
- }
-
- try {
- ((InputStream) fileURLCon.getContent(null)).read(ba, 0, 600);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- ((InputStream) fileURLCon.getContent(new Class[] {})).read(ba, 0, 600);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- ((InputStream) fileURLCon.getContent(new Class[] { Class.class })).read(ba,
- 0, 600);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @throws IOException
- * @tests {@link java.net.URLConnection#getContentEncoding()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getContentEncoding",
- args = {}
- )
- public void test_getContentEncoding() throws IOException {
- // faulty setup
- try {
-
- fileURLCon.getContentEncoding();
- fail("Exception expected");
- } catch (Throwable e) {
- //ok
- }
-
- // positive case
-
- URL url = new URL("http://www.amazon.com/");
-
- URLConnection con = url.openConnection();
- con.setRequestProperty("Accept-Encoding", "gzip");
- con.connect();
-
- assertEquals(con.getContentEncoding(), "gzip");
-
-
- uc2.setRequestProperty("Accept-Encoding", "bla");
- uc2.connect();
-
- assertNull(uc2.getContentEncoding());
-
- }
-
- /**
- * @tests {@link java.net.URLConnection#getContentLength()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getContentLength",
- args = {}
- )
- public void test_getContentLength() {
- assertEquals(testString.getBytes().length, fileURLCon.getContentLength());
- assertEquals("getContentLength failed: " + uc.getContentLength(), -1,
- uc.getContentLength());
-
- assertEquals(-1, uc2.getContentLength());
-
- assertNotNull(jarURLCon.getContentLength());
- assertNotNull(gifURLCon.getContentLength());
- }
-
- /**
- * @tests {@link java.net.URLConnection#getContentType()}
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "only default encoding may be tested",
- method = "getContentType",
- args = {}
- )
- public void test_getContentType() throws IOException, MalformedURLException {
-
- assertTrue("getContentType failed: " + fileURLCon.getContentType(), fileURLCon
- .getContentType().contains("text/plain"));
-
- URLConnection htmlFileCon = openHTMLFile();
- String contentType = htmlFileCon.getContentType();
- if (contentType != null) {
- assertTrue(contentType.equalsIgnoreCase("text/html"));
- }
-
-
- /*
- contentType = uc.getContentType();
- if (contentType != null) {
- assertTrue(contentType.equalsIgnoreCase("text/html"));
- }
-
- contentType = gifURLCon.getContentType();
- if (contentType != null) {
- assertTrue(contentType.equalsIgnoreCase("image/gif"));
- }
- */
-
- }
-
- /**
- * @tests {@link java.net.URLConnection#getDate()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch.",
- method = "getDate",
- args = {}
- )
- public void test_getDate() {
- // should be greater than 930000000000L which represents the past
- if (uc.getDate() == 0) {
- System.out
- .println("WARNING: server does not support 'Date', in test_getDate");
- } else {
- assertTrue("getDate gave wrong date: " + uc.getDate(),
- uc.getDate() > 930000000000L);
- }
- }
-
- /**
- * @throws IOException
- * @tests {@link java.net.URLConnection#getDefaultAllowUserInteraction()}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch.",
- method = "getDefaultAllowUserInteraction",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch.",
- method = "setDefaultAllowUserInteraction",
- args = {boolean.class}
- )
- })
- public void test_getDefaultAllowUserInteraction() throws IOException {
- boolean oldSetting = URLConnection.getDefaultAllowUserInteraction();
-
- URLConnection.setDefaultAllowUserInteraction(false);
- assertFalse(
- "getDefaultAllowUserInteraction should have returned false",
- URLConnection.getDefaultAllowUserInteraction());
-
- URLConnection.setDefaultAllowUserInteraction(true);
- assertTrue("getDefaultAllowUserInteraction should have returned true",
- URLConnection.getDefaultAllowUserInteraction());
-
- URLConnection.setDefaultAllowUserInteraction(oldSetting);
- }
-
- /**
- * @tests {@link java.net.URLConnection#getDefaultRequestProperty(String)}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch.",
- method = "getDefaultRequestProperty",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch.",
- method = "setDefaultRequestProperty",
- args = {java.lang.String.class, java.lang.String.class}
- )
- })
- @SuppressWarnings("deprecation")
- public void test_getDefaultRequestPropertyLjava_lang_String() {
- URLConnection.setDefaultRequestProperty("Shmoo", "Blah");
- assertNull("setDefaultRequestProperty should have returned: null",
- URLConnection.getDefaultRequestProperty("Shmoo"));
-
- URLConnection.setDefaultRequestProperty("Shmoo", "Boom");
- assertNull("setDefaultRequestProperty should have returned: null",
- URLConnection.getDefaultRequestProperty("Shmoo"));
-
- assertNull("setDefaultRequestProperty should have returned: null",
- URLConnection.getDefaultRequestProperty("Kapow"));
-
- URLConnection.setDefaultRequestProperty("Shmoo", null);
- }
-
- /**
- * @throws IOException
- * @tests {@link java.net.URLConnection#getDefaultUseCaches()}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch.",
- method = "getDefaultUseCaches",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch. test fails: throws undocumented exception IllegalAccessException.",
- method = "setDefaultUseCaches",
- args = {boolean.class}
- )
- })
- public void test_getDefaultUseCaches_CachedRC() throws IOException {
- boolean oldSetting = uc.getDefaultUseCaches();
-
- ResponseCache old = ResponseCache.getDefault();
- ResponseCache rc = new MockCachedResponseCache();
- ResponseCache.setDefault(rc);
-
- // Recreate the connection so that we get the cache from ResponseCache.
- uc2 = url2.openConnection();
-
- uc2.setUseCaches(true);
-
- uc.setDefaultUseCaches(false);
-
- // uc unaffected
- assertTrue(uc.getUseCaches());
- // uc2 unaffected
- assertTrue(uc2.getUseCaches());
-
- //test get
- assertFalse("getDefaultUseCaches should have returned false", uc
- .getDefaultUseCaches());
-
- // subsequent connections should have default value
- URL url3 = new URL(Support_Configuration.hTTPURLyahoo);
- URLConnection uc3 = url3.openConnection();
- assertFalse(uc3.getUseCaches());
-
- // test if uc does not chash but uc2 does
- isGetCalled = false;
- isPutCalled = false;
-
- // test uc
- uc.setDoOutput(true);
-
- assertFalse(isGetCalled);
- uc.connect();
- assertFalse(isGetCalled);
- assertFalse(isPutCalled);
- OutputStream os = uc.getOutputStream();
- assertFalse(isPutCalled);
- assertFalse(isGetCalled);
-
- os.close();
-
- isGetCalled = false;
- isPutCalled = false;
-
- //uc2 should be unaffected
- uc2.setDoOutput(true);
- assertFalse(isGetCalled);
- uc2.connect();
- assertTrue(isGetCalled);
- assertFalse(isPutCalled);
-
- uc.setDefaultUseCaches(oldSetting);
- ResponseCache.setDefault(null);
- }
-
- /**
- * @throws IOException
- * @tests {@link java.net.URLConnection#getDoInput()}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch.",
- method = "getDoInput",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch.",
- method = "setDoInput",
- args = {boolean.class}
- )
- })
- public void test_getDoInput() throws IOException {
- assertTrue("Should be set to true by default", uc.getDoInput());
-
- fileURLCon.setDoInput(true);
- assertTrue("Should have been set to true", fileURLCon.getDoInput());
-
- uc2.setDoInput(false);
- assertFalse("Should have been set to false", uc2.getDoInput());
-
- fileURLCon.connect();
- fileURLCon.getInputStream();
-
- uc2.connect();
- try {
- uc2.getInputStream();
- } catch (Throwable e) {
- // ok
- }
-
- }
-
- /**
- * @throws IOException
- * @tests {@link java.net.URLConnection#getDoOutput()}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch.",
- method = "getDoOutput",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch.",
- method = "setDoOutput",
- args = {boolean.class}
- )
- })
- public void test_getDoOutput() throws IOException {
- assertFalse("Should be set to false by default", uc.getDoOutput());
-
- uc.setDoOutput(true);
- assertTrue("Should have been set to true", uc.getDoOutput());
-
- uc.connect();
- uc.getOutputStream();
-
- uc2.setDoOutput(false);
- assertFalse("Should have been set to false", uc2.getDoOutput());
- uc2.connect();
-
- try{
- uc2.getOutputStream();
- } catch (Throwable e) {
- //ok
- }
- }
-
- /**
- * @throws IOException
- * @tests {@link java.net.URLConnection#getExpiration()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch.",
- method = "getExpiration",
- args = {}
- )
- @KnownFailure("URLConnection.getExpiration crashes because the returned" +
- " expiration date doesn't seems to be parsable.")
- public void test_getExpiration() throws IOException {
- URL url3 = new URL(Support_Configuration.hTTPURLwExpiration);
- URLConnection uc3 = url3.openConnection();
-
- uc.connect();
- // should be unknown
- assertEquals("getExpiration returned wrong expiration", 0, uc
- .getExpiration());
-
- uc3.connect();
- assertTrue("getExpiration returned wrong expiration", uc3
- .getExpiration() > 0);
-
- ((HttpURLConnection) uc3).disconnect();
- }
-
- /**
- * @tests {@link java.net.URLConnection#getFileNameMap()}
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "From harmony branch.",
- method = "getFileNameMap",
- args = {}
- )
- public void test_getFileNameMap() {
- // Tests for the standard MIME types -- users may override these
- // in their JRE
-
- FileNameMap mapOld = URLConnection.getFileNameMap();
-
- try {
- // These types are defaulted
- assertEquals("text/html", mapOld.getContentTypeFor(".htm"));
- assertEquals("text/html", mapOld.getContentTypeFor(".html"));
- assertEquals("text/plain", mapOld.getContentTypeFor(".text"));
- assertEquals("text/plain", mapOld.getContentTypeFor(".txt"));
-
- // These types come from the properties file :
- // not black-box testing. Special tests moved to setContentType
- /*
- assertEquals("application/pdf", map.getContentTypeFor(".pdf"));
- assertEquals("application/zip", map.getContentTypeFor(".zip"));
- assertEquals("image/gif", map.getContentTypeFor("gif"));
- */
-
- URLConnection.setFileNameMap(new FileNameMap() {
- public String getContentTypeFor(String fileName) {
- return "Spam!";
- }
- });
-
- assertEquals("Incorrect FileNameMap returned", "Spam!",
- URLConnection.getFileNameMap().getContentTypeFor(null));
- } finally {
- // unset the map so other tests don't fail
- URLConnection.setFileNameMap(mapOld);
- }
- // RI fails since it does not support fileName that does not begin with
- // '.'
-
- }
-
- /**
- * @tests {@link java.net.URLConnection#getHeaderFieldDate(java.lang.String, long)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch.",
- method = "getHeaderFieldDate",
- args = {java.lang.String.class, long.class}
- )
- public void test_getHeaderFieldDateLjava_lang_StringJ() {
-
- if (uc2.getHeaderFieldDate("Date", 22L) == 22L) {
- System.out
- .println("WARNING: Server does not support 'Date', test_getHeaderFieldDateLjava_lang_StringJ not run");
- return;
- }
-
- if (uc2.getIfModifiedSince() > 0) {
-
- long time = uc2.getHeaderFieldDate("Last-Modified", 0);
- assertTrue(time > 0);
- /*
- assertEquals("Wrong date: ", time,
- Support_Configuration.URLConnectionLastModified);
- */
- }
-
- long defaultTime;
-
- if (uc.getIfModifiedSince() == 0) {
- defaultTime = uc.getHeaderFieldDate("Last-Modified", 0);
- assertEquals(defaultTime,0);
- }
- }
-
- /**
- * @tests {@link java.net.URLConnection#getHeaderField(int)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "not supported. Always returns null.From harmony branch.",
- method = "getHeaderField",
- args = {int.class}
- )
- public void DISABLED_test_getHeaderFieldI() {
- int i = 0;
- String hf;
- boolean foundResponse = false;
- while ((hf = uc.getHeaderField(i++)) != null) {
- if (hf.equals(Support_Configuration.HomeAddressSoftware)) {
- foundResponse = true;
- }
- }
- assertTrue("Could not find header field containing \""
- + Support_Configuration.HomeAddressSoftware + "\"",
- foundResponse);
-
- i = 0;
- foundResponse = false;
- while ((hf = uc.getHeaderField(i++)) != null) {
- if (hf.equals(Support_Configuration.HomeAddressResponse)) {
- foundResponse = true;
- }
- }
- assertTrue("Could not find header field containing \""
- + Support_Configuration.HomeAddressResponse + "\"",
- foundResponse);
- }
-
- /**
- * @tests {@link java.net.URLConnection#getHeaderFieldKey(int)}
- */
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "Not supported. Current implementation returns always null according to spec.",
- method = "getHeaderFieldKey",
- args = {int.class}
- )
- public void DISABLED_test_getHeaderFieldKeyI() {
- String hf;
- boolean foundResponse = false;
- for (int i = 0; i < 100; i++) {
- hf = uc.getHeaderFieldKey(i);
- if (hf != null && hf.toLowerCase().equals("content-type")) {
- foundResponse = true;
- break;
- }
- }
- assertTrue(
- "Could not find header field key containing \"content-type\"",
- foundResponse);
- }
-
- /**
- * @throws IOException
- * @tests {@link java.net.URLConnection#getHeaderFieldInt(String, int)}
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "",
- method = "getHeaderFieldInt",
- args = {java.lang.String.class, int.class}
- )
- public void test_getHeaderFieldInt() throws IOException {
- String header;
- URL url3 = new URL(Support_Configuration.hTTPURLwExpiration);
- URLConnection uc3 = url3.openConnection();
-
- int hf = 0;
- hf = uc2.getHeaderFieldInt("Content-Encoding",Integer.MIN_VALUE);
- assertEquals(Integer.MIN_VALUE, hf);
- hf = uc2.getHeaderFieldInt("Content-Length",Integer.MIN_VALUE);
- assertEquals(Integer.MIN_VALUE, hf);
- hf = uc2.getHeaderFieldInt("Content-Type",Integer.MIN_VALUE);
- assertEquals(Integer.MIN_VALUE, hf);
- hf = uc2.getHeaderFieldInt("Date",Integer.MIN_VALUE);
- assertEquals(Integer.MIN_VALUE, hf);
- long exp = uc3.getHeaderFieldDate("Expires", 0);
- assertTrue(exp > 0);
- hf = uc2.getHeaderFieldInt("SERVER",Integer.MIN_VALUE);
- assertEquals(Integer.MIN_VALUE, hf);
- hf = uc2.getHeaderFieldInt("Last-Modified",Integer.MIN_VALUE);
- assertEquals(Integer.MIN_VALUE, hf);
- hf = uc2.getHeaderFieldInt("accept-ranges",Integer.MIN_VALUE);
- assertEquals(Integer.MIN_VALUE, hf);
- hf = uc2.getHeaderFieldInt("DoesNotExist",Integer.MIN_VALUE);
- assertEquals(Integer.MIN_VALUE, hf);
- hf = uc2.getHeaderFieldInt("Age",Integer.MIN_VALUE);
- assertFalse(hf == Integer.MIN_VALUE);
-
- ((HttpURLConnection) uc3).disconnect();
- }
-
- /**
- * @tests {@link java.net.URLConnection#getHeaderField(java.lang.String)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getHeaderField",
- args = {java.lang.String.class}
- )
- @BrokenTest("Flaky due to third party servers used to do the test.")
- public void test_getHeaderFieldLjava_lang_String() {
- String hf;
- int hfDefault;
- hf = uc.getHeaderField("Content-Encoding");
- if (hf != null) {
- assertNull(
- "Wrong value returned for header field 'Content-Encoding': "
- + hf, hf);
- }
- hf = uc.getHeaderField("Content-Length");
- if (hf != null) {
- assertEquals(
- "Wrong value returned for header field 'Content-Length': ",
- "25", hf);
- }
- hf = uc.getHeaderField("Content-Type");
- if (hf != null) {
- assertTrue("Wrong value returned for header field 'Content-Type': "
- + hf, hf.contains("text/html"));
- }
- hf = uc.getHeaderField("content-type");
- if (hf != null) {
- assertTrue("Wrong value returned for header field 'content-type': "
- + hf, hf.contains("text/html"));
- }
- hf = uc.getHeaderField("Date");
- if (hf != null) {
- assertTrue("Wrong value returned for header field 'Date': " + hf,
- Integer.parseInt(hf.substring(hf.length() - 17,
- hf.length() - 13)) >= 1999);
- }
- hf = uc.getHeaderField("Expires");
- if (hf != null) {
- assertNull(
- "Wrong value returned for header field 'Expires': " + hf,
- hf);
- }
- hf = uc.getHeaderField("SERVER");
- assertNotNull(hf);
- hf = uc.getHeaderField("Last-Modified");
- if (hf != null) {
- assertTrue(
- "No valid header field "
- + hf,
- Long.parseLong(hf) > 930000000000L);
- }
- hf = uc.getHeaderField("accept-ranges");
- if (hf != null) {
- assertTrue(
- "Wrong value returned for header field 'accept-ranges': "
- + hf, hf.equals("bytes"));
- }
- hf = uc.getHeaderField("DoesNotExist");
- if (hf != null) {
- assertNull("Wrong value returned for header field 'DoesNotExist': "
- + hf, hf);
- }
- }
-
- /**
- * @throws URISyntaxException
- * @throws ClassNotFoundException
- * @tests {@link java.net.URLConnection#getHeaderFields()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch.",
- method = "getHeaderFields",
- args = {}
- )
- public void test_getHeaderFields() throws IOException, ClassNotFoundException, URISyntaxException {
- try {
- uc2.getInputStream();
- } catch (IOException e) {
- fail("Error in test setup: "+e.getMessage());
- }
-
- Map<String, List<String>> headers = uc2.getHeaderFields();
- assertNotNull(headers);
-
- // 'content-type' is most likely to appear
- List<String> list = headers.get("content-type");
- if (list == null) {
- list = headers.get("Content-Type");
- }
- assertNotNull(list);
- String contentType = (String) list.get(0);
- assertNotNull(contentType);
-
- // there should be at least 2 headers
- assertTrue("Not more than one header in URL connection",headers.size() > 1);
-
- JarURLConnection con1 = openJarURLConnection();
- headers = con1.getHeaderFields();
- assertNotNull(headers);
- assertEquals(0, headers.size());
-
- try {
- // the map should be unmodifiable
- headers.put("hi", Arrays.asList(new String[] { "bye" }));
- fail("The map should be unmodifiable");
- } catch (UnsupportedOperationException e) {
- // Expected
- }
- }
-
- /**
- * @throws IOException
- * @tests {@link java.net.URLConnection#getLastModified()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch.",
- method = "getLastModified",
- args = {}
- )
- public void test_getLastModified() throws IOException {
-
- URL url4 = new URL(Support_Configuration.hTTPURLwLastModified);
- URLConnection uc4 = url4.openConnection();
-
- uc4.connect();
-
- if (uc4.getLastModified() == 0) {
- System.out
- .println("WARNING: Server does not support 'Last-Modified', test_getLastModified() not run");
- return;
- }
-
- long millis = uc4.getHeaderFieldDate("Last-Modified", 0);
-
- assertEquals(
- "Returned wrong getLastModified value. Wanted: "
- + " got: " + uc4.getLastModified(),
- millis, uc4.getLastModified());
-
-
- ((HttpURLConnection) uc).disconnect();
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getOutputStream",
- args = {}
- )
- public void test_getOutputStream() throws IOException {
- String posted = "this is a test";
- uc.setDoOutput(true);
- uc.connect();
-
- BufferedWriter w = new BufferedWriter(new OutputStreamWriter(uc
- .getOutputStream()), posted.getBytes().length);
-
- w.write(posted);
- w.flush();
- w.close();
-
- int code = ((HttpURLConnection) uc).getResponseCode();
-
-
- // writing to url not allowed
- assertEquals("Got different responseCode ", 405, code);
-
-
- // try exception testing
- try {
- fileURLCon.setDoOutput(true);
- fileURLCon.connect();
- fileURLCon.getOutputStream();
- } catch (UnknownServiceException e) {
- // ok cannot write to fileURL
- }
-
- ((HttpURLConnection) uc2).disconnect();
-
- try {
- uc2.getOutputStream();
- fail("Exception expected");
- } catch (IOException e) {
- // ok
- }
- }
-
- /**
- * @tests {@link java.net.URLConnection#getPermission()}
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "From harmony branch.",
- method = "getPermission",
- args = {}
- )
- public void test_getPermission() throws Exception {
- java.security.Permission p = uc.getPermission();
- assertTrue("Permission of wrong type: " + p.toString(),
- p instanceof java.net.SocketPermission);
- assertTrue("Permission has wrong name: " + p.getName(), p.getName()
- .contains("google.com:" + port));
-
- URL fileUrl = new URL("file:myfile");
- Permission perm = new FilePermission("myfile", "read");
- Permission result = fileUrl.openConnection().getPermission();
- assertTrue("Wrong file: permission 1:" + perm + " , " + result, result
- .equals(perm));
-
- fileUrl = new URL("file:/myfile/");
- perm = new FilePermission("/myfile", "read");
- result = fileUrl.openConnection().getPermission();
- assertTrue("Wrong file: permission 2:" + perm + " , " + result, result
- .equals(perm));
-
- fileUrl = new URL("file:///host/volume/file");
- perm = new FilePermission("/host/volume/file", "read");
- result = fileUrl.openConnection().getPermission();
- assertTrue("Wrong file: permission 3:" + perm + " , " + result, result
- .equals(perm));
-
- URL httpUrl = new URL("http://home/myfile/");
- assertTrue("Wrong http: permission", httpUrl.openConnection()
- .getPermission().equals(
- new SocketPermission("home:80", "connect")));
- httpUrl = new URL("http://home2:8080/myfile/");
- assertTrue("Wrong http: permission", httpUrl.openConnection()
- .getPermission().equals(
- new SocketPermission("home2:8080", "connect")));
- URL ftpUrl = new URL("ftp://home/myfile/");
- assertTrue("Wrong ftp: permission", ftpUrl.openConnection()
- .getPermission().equals(
- new SocketPermission("home:21", "connect")));
- ftpUrl = new URL("ftp://home2:22/myfile/");
- assertTrue("Wrong ftp: permission", ftpUrl.openConnection()
- .getPermission().equals(
- new SocketPermission("home2:22", "connect")));
-
- URL jarUrl = new URL("jar:file:myfile!/");
- perm = new FilePermission("myfile", "read");
- result = jarUrl.openConnection().getPermission();
- assertTrue("Wrong jar: permission:" + perm + " , " + result, result
- .equals(new FilePermission("myfile", "read")));
- }
-
- /**
- * @tests {@link java.net.URLConnection#getRequestProperties()}
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "implementation test.From harmony branch.",
- method = "getRequestProperties",
- args = {}
- )
- public void test_getRequestProperties() {
- uc.setRequestProperty("whatever", "you like");
- Map headers = uc.getRequestProperties();
-
- // content-length should always appear
- List header = (List) headers.get("whatever");
- assertNotNull(header);
-
- assertEquals("you like", header.get(0));
-
- assertTrue(headers.size() >= 1);
-
- try {
- // the map should be unmodifiable
- headers.put("hi", "bye");
- fail();
- } catch (UnsupportedOperationException e) {
- }
- try {
- // the list should be unmodifiable
- header.add("hi");
- fail();
- } catch (UnsupportedOperationException e) {
- }
-
- }
-
- /**
- * @tests {@link java.net.URLConnection#getRequestProperties()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Exceptions checked only.From harmony branch.",
- method = "getRequestProperties",
- args = {}
- )
- public void test_getRequestProperties_Exception() throws IOException {
- URL url = new URL("http", "test", 80, "index.html", new NewHandler());
- URLConnection urlCon = url.openConnection();
- urlCon.connect();
-
- try {
- urlCon.getRequestProperties();
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- }
-
- /**
- * @tests {@link java.net.URLConnection#getRequestProperty(java.lang.String)}
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Exceptions checked only.From harmony branch.",
- method = "getRequestProperty",
- args = { String.class }
- )
- public void test_getRequestProperty_LString_Exception() throws IOException {
- URL url = new URL("http", "test", 80, "index.html", new NewHandler());
- URLConnection urlCon = url.openConnection();
- urlCon.setRequestProperty("test", "testProperty");
- assertNull(urlCon.getRequestProperty("test"));
-
- urlCon.connect();
- try {
- urlCon.getRequestProperty("test");
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- }
-
- /**
- * @tests {@link java.net.URLConnection#getRequestProperty(java.lang.String)}
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "From harmony branch.",
- method = "getRequestProperty",
- args = {java.lang.String.class}
- )
- public void test_getRequestPropertyLjava_lang_String() {
- uc.setRequestProperty("Yo", "yo");
- assertTrue("Wrong property returned: " + uc.getRequestProperty("Yo"),
- uc.getRequestProperty("Yo").equals("yo"));
- assertNull("Wrong property returned: " + uc.getRequestProperty("No"),
- uc.getRequestProperty("No"));
- }
-
- /**
- * @tests {@link java.net.URLConnection#getURL()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Exceptions checked only -> only partially implemented. From harmony branch.",
- method = "getURL",
- args = {}
- )
- public void test_getURL() {
- assertTrue("Incorrect URL returned", uc.getURL().equals(url));
- }
-
- /**
- * @throws IOException
- * @tests {@link java.net.URLConnection#getUseCaches()}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Exceptions checked in setUseCaches. From harmony branch.",
- method = "getUseCaches",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Exceptions checked in setUseCaches. From harmony branch.",
- method = "setUseCaches",
- args = {boolean.class}
- )
- })
- public void test_getUseCaches() throws IOException {
- uc2.setUseCaches(false);
- assertTrue("getUseCaches should have returned false", !uc2
- .getUseCaches());
- uc2.setUseCaches(true);
- assertTrue("getUseCaches should have returned true", uc2.getUseCaches());
-
- uc2.connect();
-
-
- try {
- uc2.setUseCaches(false);
- fail("Exception expected");
- } catch (IllegalStateException e) {
- //ok
- }
-
- ((HttpURLConnection) uc2).disconnect();
-
- }
-
- /**
- * @tests {@link java.net.URLConnection#guessContentTypeFromName(String)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "guessContentTypeFromName",
- args = {java.lang.String.class}
- )
- public void test_guessContentTypeFromName()
- throws IOException {
-
- URLConnection htmlFileCon = openHTMLFile();
- String[] expected = new String[] {"text/html",
- "text/plain" };
- String[] resources = new String[] {
- htmlFileCon.getURL().toString(),
- fileURL.toString()
- };
- for (int i = 0; i < resources.length; i++) {
- String mime = URLConnection.guessContentTypeFromName( resources[i]);
- assertEquals("checking " + resources[i] + " expected " + expected[i]+"got " + expected[i],
- expected[i], mime);
- }
-
- // Try simple case
- try {
- URLConnection.guessContentTypeFromStream(null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests {@link java.net.URLConnection#guessContentTypeFromStream(java.io.InputStream)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "test fails at UTF-8 stage. Test from harmony branch",
- method = "guessContentTypeFromStream",
- args = {java.io.InputStream.class}
- )
- @BrokenTest("MIME type application xml is not supported: only text html."+
- " Should be implemented if compatibility is required. The RI" +
- " on the other hand doesn't recognise the '<head' tag.")
- public void test_guessContentTypeFromStreamLjava_io_InputStream()
- throws IOException {
- String[] headers = new String[] { "<html>", "<head>", " <head ",
- "<body", "<BODY ", //"<!DOCTYPE html",
- "<?xml " };
- String[] expected = new String[] { "text/html","text/html", "text/html",
- "text/html","text/html", "application/xml" };
-
- String[] encodings = new String[] { "ASCII", "UTF-8",
- //"UTF-16BE", not supported
- //"UTF-16LE", not supported
- //"UTF-32BE", not supported encoding
- //"UTF-32LE" not supported encoding
- };
- for (int i = 0; i < headers.length; i++) {
- for (String enc : encodings) {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- String encodedString = new String(headers[i].getBytes(), enc);
- InputStream is = new ByteArrayInputStream(encodedString.getBytes());
- String mime = URLConnection.guessContentTypeFromStream(is);
- assertEquals("checking " + headers[i] + " with " + enc,
- expected[i], mime);
- }
- }
-
- // Try simple case
- try {
- URLConnection.guessContentTypeFromStream(null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- /* not supported
- // Test magic bytes
- byte[][] bytes = new byte[][] { { 'P', 'K' }, { 'G', 'I' } };
- expected = new String[] { "application/zip", "image/gif" };
-
- for (int i = 0; i < bytes.length; i++) {
- InputStream is = new ByteArrayInputStream(bytes[i]);
- assertEquals(expected[i], URLConnection
- .guessContentTypeFromStream(is));
- }
- */
- }
-
-// /**
-// * @throws IOException
-// * @throws IllegalAccessException
-// * @throws IllegalArgumentException
-// * @throws URISyntaxException
-// * @throws MalformedURLException
-// * @tests {@link java.net.URLConnection#setContentHandlerFactory(java.net.ContentHandlerFactory)}
-// */
-// @TestTargetNew(
-// level = TestLevel.SUFFICIENT,
-// notes = "test adopted from ConentHandlerFactoryTest.",
-// method = "setContentHandlerFactory",
-// args = {java.net.ContentHandlerFactory.class}
-// )
-// public void testSetContentHandlerFactory() throws IOException,
-// IllegalArgumentException, IllegalAccessException, URISyntaxException {
-// String[] files = {
-// "hyts_checkInput.txt", "hyts_htmltest.html"};
-// ContentHandlerFactory factory = new TestContentHandlerFactory();
-// Field contentHandlerFactoryField = null;
-// int counter = 0;
-//
-//
-// Field[] fields = URLConnection.class.getDeclaredFields();
-//
-//
-// for (Field f : fields) {
-// if (ContentHandlerFactory.class.equals(f.getType())) {
-// counter++;
-// contentHandlerFactoryField = f;
-// }
-// }
-//
-// if (counter != 1) {
-// fail("Error in test setup: not Factory found");
-// }
-//
-// contentHandlerFactoryField.setAccessible(true);
-// ContentHandlerFactory old = (ContentHandlerFactory) contentHandlerFactoryField
-// .get(null);
-//
-// try {
-// contentHandlerFactoryField.set(null, factory);
-//
-// Vector<URL> urls = createContent(files);
-// for (int i = 0; i < urls.size(); i++) {
-// URLConnection urlCon = null;
-// try {
-// urlCon = urls.elementAt(i).openConnection();
-// urlCon.setDoInput(true);
-// Object obj = urlCon.getContent();
-// if (obj instanceof String) {
-// String s = (String) obj;
-// assertTrue("Returned incorrect content for "
-// + urls.elementAt(i) + ": " + s,
-// s.equals("ok"));
-// } else {
-// fail("Got wrong content handler");
-// }
-// } catch (IOException e) {
-// fail("IOException was thrown for URL: "+ urls.elementAt(i).toURI().toString() +" " + e.toString());
-// }
-// }
-// } finally {
-// contentHandlerFactoryField.set(null, old);
-// }
-// }
-
- /**
- * @tests {@link java.net.URLConnection#setConnectTimeout(int)}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setConnectTimeout",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getConnectTimeout",
- args = {}
- )
- })
- public void test_setConnectTimeoutI() throws Exception {
- URLConnection uc = new URL("http://localhost").openConnection();
- assertEquals(0, uc.getConnectTimeout());
- uc.setConnectTimeout(0);
- assertEquals(0, uc.getConnectTimeout());
- try {
- uc.setConnectTimeout(-100);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // correct
- }
- assertEquals(0, uc.getConnectTimeout());
- uc.setConnectTimeout(100);
- assertEquals(100, uc.getConnectTimeout());
- try {
- uc.setConnectTimeout(-1);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // correct
- }
- assertEquals(100, uc.getConnectTimeout());
-
- uc2.setConnectTimeout(2);
-
- try {
- uc2.connect();
- } catch (SocketTimeoutException e) {
- //ok
- }
-
- }
-
- /**
- * @throws IOException
- * @tests {@link java.net.URLConnection#setFileNameMap(java.net.FileNameMap)}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setFileNameMap",
- args = {java.net.FileNameMap.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFileNameMap",
- args = {}
- )
- })
- public void test_setFileNameMapLjava_net_FileNameMap() throws IOException {
- FileNameMap mapOld = URLConnection.getFileNameMap();
- // nothing happens if set null
- URLConnection.setFileNameMap(null);
- // take no effect
- assertNotNull(URLConnection.getFileNameMap());
-
- try {
- URLConnection.setFileNameMap(new java.net.FileNameMap(){
- public String getContentTypeFor(String fileName) {
- if (fileName==null || fileName.length()<1)
- return null;
- String name=fileName.toLowerCase();
- String type=null;
- if (name.endsWith(".xml"))
- type="text/xml";
- else if (name.endsWith(".dtd"))
- type="text/dtd";
- else if (name.endsWith(".pdf"))
- type = "application/pdf";
- else if (name.endsWith(".zip"))
- type = "application/zip";
- else if (name.endsWith(".gif"))
- type = "image/gif";
- else
- type="application/unknown";
- return type;
- }
- });
- FileNameMap mapNew = URLConnection.getFileNameMap();
- assertEquals("application/pdf", mapNew.getContentTypeFor(".pdf"));
- assertEquals("application/zip", mapNew.getContentTypeFor(".zip"));
- assertEquals("image/gif", mapNew.getContentTypeFor(".gif"));
- } finally {
-
- URLConnection.setFileNameMap(mapOld);
- }
- }
-
- /**
- * @tests {@link java.net.URLConnection#setIfModifiedSince(long)}
- */
- @TestTargets ( {
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setIfModifiedSince",
- args = {long.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "From harmony branch.",
- method = "getIfModifiedSince",
- args = {}
- )
- })
- public void test_setIfModifiedSinceJ() throws IOException {
- URL url = new URL("http://localhost:8080/");
- URLConnection connection = url.openConnection();
- Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
- cal.clear();
- cal.set(2000, Calendar.MARCH, 5);
-
- long sinceTime = cal.getTime().getTime();
- connection.setIfModifiedSince(sinceTime);
- assertEquals("Wrong date set", sinceTime, connection
- .getIfModifiedSince());
-
- // content should be returned
-
- uc2.setIfModifiedSince(sinceTime);
- uc2.connect();
-
-
- assertEquals(200,((HttpURLConnection) uc2).getResponseCode());
-
- try {
- uc2.setIfModifiedSince(2);
- fail("Exception expected");
- } catch (IllegalStateException e) {
- //ok
- }
-
- ((HttpURLConnection) uc2).disconnect();
-
-
- }
-
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "test that page was not renewed in time indicated -> page returned event though it should not.",
- method = "getIfModifiedSince",
- args = {}
- )
- public void test_getIfModifiedSinceJ() throws IOException {
-
- uc2.setIfModifiedSince(Calendar.getInstance().getTimeInMillis());
- uc2.connect();
-
- assertEquals(200,((HttpURLConnection) uc2).getResponseCode());
-
- }
-
-
- /**
- * @tests {@link java.net.URLConnection#setReadTimeout(int)}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Test for SocketTimeoutException fails: instead undocumented UnknownServiceException is thrown.",
- method = "setReadTimeout",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Test for SocketTimeoutException fails: instead undocumented UnknownServiceException is thrown.",
- method = "getReadTimeout",
- args = {}
- )
- })
- public void test_setReadTimeoutI() throws Exception {
- assertEquals(0, uc.getReadTimeout());
- uc.setReadTimeout(0);
- assertEquals(0, uc.getReadTimeout());
- try {
- uc.setReadTimeout(-100);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // correct
- }
- assertEquals(0, uc.getReadTimeout());
- uc.setReadTimeout(100);
- assertEquals(100, uc.getReadTimeout());
- try {
- uc.setReadTimeout(-1);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // correct
- }
- assertEquals(100, uc.getReadTimeout());
-
- byte[] ba = new byte[600];
-
- uc2.setReadTimeout(5);
- uc2.setDoInput(true);
- uc2.connect();
-
- try {
- ((InputStream) uc2.getInputStream()).read(ba, 0, 600);
- } catch (SocketTimeoutException e) {
- //ok
- } catch ( UnknownServiceException e) {
- fail(""+e.getMessage());
- }
- }
-
- /**
- * @tests {@link java.net.URLConnection#toString()}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
-
- assertTrue("Wrong toString: " + uc.toString(), uc.toString().indexOf(
- "URLConnection") > 0);
- assertTrue("Wrong toString: " + uc.toString(), uc.toString().indexOf(
- uc.getURL().toString()) > 0);
- }
-
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "protected constructor",
- method = "URLConnection",
- args = {java.net.URL.class}
- )
- public void test_URLConnection() {
- String url = uc2.getURL().toString();
- assertEquals(url2.toString(), url);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInputStream",
- args = {}
- )
- @BrokenTest("Flaky test due to the use of third party servers")
- public void testGetInputStream() throws IOException {
- fileURLCon.setDoInput(true);
- fileURLCon.connect();
-
- BufferedReader buf = new BufferedReader(new InputStreamReader(
- fileURLCon.getInputStream()), testString.getBytes().length);
-
- String nextline;
- while ((nextline = buf.readLine()) != null) {
- assertEquals(testString, nextline);
- }
-
- buf.close();
-
-
- ((HttpURLConnection) uc).disconnect();
-
- try {
- uc.getInputStream();
- fail("Exception expected");
- } catch (IOException e) {
- // ok
- }
-
- uc2.getInputStream();
-
-
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies SecurityException.",
- method = "setContentHandlerFactory",
- args = {java.net.ContentHandlerFactory.class}
- )
- public void test_setContentHandlerFactory() {
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkSetFactory() {
- throw new SecurityException();
- }
- };
- SecurityManager old_sm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- uc.setContentHandlerFactory(null);
- fail("SecurityException was not thrown.");
- } catch(SecurityException se) {
- //exception
- } finally {
- System.setSecurityManager(old_sm);
- }
-
- }
-
- private URLConnection openGifURLConnection() throws IOException {
- String cts = System.getProperty("java.io.tmpdir");
- File tmpDir = new File(cts);
- Support_Resources.copyFile(tmpDir, null, "Harmony.GIF");
- URL fUrl1 = new URL("file:/" + tmpDir.getPath()
- + "/Harmony.GIF");
- URLConnection con1 = fUrl1.openConnection();
- return con1;
- }
-
- private JarURLConnection openJarURLConnection()
- throws MalformedURLException, IOException {
- String cts = System.getProperty("java.io.tmpdir");
- File tmpDir = new File(cts);
- Support_Resources.copyFile(tmpDir, null, "hyts_att.jar");
- URL fUrl1 = new URL("jar:file:" + tmpDir.getPath()
- + "/hyts_att.jar!/");
- JarURLConnection con1 = (JarURLConnection) fUrl1.openConnection();
- return con1;
- }
-
- private URLConnection openHTMLFile() throws IOException {
- String cts = System.getProperty("java.io.tmpdir");
- File tmpDir = new File(cts);
- Support_Resources.copyFile(tmpDir, null, "hyts_htmltest.html");
- URL fUrl1 = new URL("file:/" + tmpDir.getPath()
- + "/hyts_htmltest.html");
- URLConnection con1 = fUrl1.openConnection();
- return con1;
- }
-
- private URL createTempHelloWorldFile() throws MalformedURLException {
- // create content to read
- File tmpDir = new File(System.getProperty("java.io.tmpdir"));
- File sampleFile = null;
- try {
- if (tmpDir.isDirectory()) {
- sampleFile = File.createTempFile("openStreamTest", ".txt",
- tmpDir);
- sampleFile.deleteOnExit();
- } else {
- fail("Error in test setup tmpDir does not exist");
- }
-
- FileWriter fstream = new FileWriter(sampleFile);
- BufferedWriter out = new BufferedWriter(fstream, testString.getBytes().length);
- out.write(testString);
- // Close the output stream
- out.close();
- } catch (Exception e) {// Catch exception if any
- fail("Error: in test setup" + e.getMessage());
- }
-
- // read content from file
- return sampleFile.toURL();
- }
-
-// /**
-// * Method copied form ContentHandlerFactory
-// */
-// private Vector<URL> createContent(String [] files) {
-//
-// File resources = new File(System.getProperty("java.io.tmpdir"));
-//
-// String resPath = resources.toString();
-// if (resPath.charAt(0) == '/' || resPath.charAt(0) == '\\')
-// resPath = resPath.substring(1);
-//
-// Vector<URL> urls = new Vector<URL> ();
-//
-// for(String file:files) {
-// Support_Resources.copyFile(resources, null, file);
-// URL resourceURL;
-// try {
-// resourceURL = new URL("file:/" + resPath + "/"
-// + file);
-// urls.add(resourceURL);
-// } catch (MalformedURLException e) {
-// fail("URL can be created for " + file);
-// }
-//
-// }
-// return urls;
-// }
-//
-// public class TestContentHandler extends ContentHandler {
-//
-// public Object getContent(URLConnection u) {
-//
-// return new String("ok");
-// }
-// }
-//
-//
-// public class TestContentHandlerFactory implements ContentHandlerFactory {
-//
-// final String[] mimeTypes = {
-// "text/plain", "application/xml", "image/gif", "application/zip"};
-//
-// public ContentHandler createContentHandler(String mimetype) {
-// boolean isAllowed = false;
-// for (String mime : mimeTypes) {
-// if (mime.equals(mimetype)) isAllowed = true;
-// }
-// if (isAllowed) {
-// return new TestContentHandler();
-// } else
-// return null;
-// }
-// }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLEncoderTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLEncoderTest.java
deleted file mode 100644
index 52fdf4a..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLEncoderTest.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/* 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.harmony.luni.tests.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(URLEncoder.class)
-public class URLEncoderTest extends TestCase {
-
- /**
- * @tests URLEncoder#encode(String, String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Regression test. Checks UnsupportedEncodingException & NullPointerException",
- method = "encode",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_encodeLjava_lang_StringLjava_lang_String() throws Exception {
- // Regression for HARMONY-24
- try {
- URLEncoder.encode("str","unknown_enc");
- fail("Assert 0: Should throw UEE for invalid encoding");
- } catch (UnsupportedEncodingException e) {
- // expected
- }
- //Regression for HARMONY-1233
- try {
- URLEncoder.encode(null, "harmony");
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLTest.java
deleted file mode 100644
index 1e38d90..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLTest.java
+++ /dev/null
@@ -1,1285 +0,0 @@
-/* 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.harmony.luni.tests.java.net;
-
-import dalvik.annotation.BrokenTest;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import tests.support.Support_Configuration;
-import tests.support.Support_PortManager;
-import tests.support.resource.Support_Resources;
-
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.lang.reflect.Field;
-import java.net.HttpURLConnection;
-import java.net.InetSocketAddress;
-import java.net.MalformedURLException;
-import java.net.Proxy;
-import java.net.ProxySelector;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.SocketAddress;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.net.URLConnection;
-import java.net.URLStreamHandler;
-import java.net.URLStreamHandlerFactory;
-import java.security.Permission;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-@TestTargetClass(URL.class)
-public class URLTest extends TestCase {
-
- private static final String helloWorldString = "Hello World";
- /**
- * @tests java.net.URL#getHost()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Regression test.",
- method = "getHost",
- args = {}
- )
- public void test_getHost() throws MalformedURLException {
- // Regression for HARMONY-60
- String ipv6Host = "FEDC:BA98:7654:3210:FEDC:BA98:7654:3210";
- URL url = new URL("http", ipv6Host, -1, "myfile");
- assertEquals(("[" + ipv6Host + "]"), url.getHost());
- }
-
- /**
- * @tests java.net.URL#URL(java.lang.String, java.lang.String, int, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Regression test.",
- method = "URL",
- args = {java.lang.String.class, java.lang.String.class, int.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_StringILjava_lang_String()
- throws MalformedURLException {
- // Regression for HARMONY-83
- new URL("http", "apache.org", 123456789, "file");
- try {
- new URL("http", "apache.org", -123, "file");
- fail("Assert 0: Negative port should throw exception");
- } catch (MalformedURLException e) {
- // expected
- }
- }
-
- /**
- * @tests java.net.URL#URL(java.lang.String, java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URL",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String() throws MalformedURLException {
- // Strange behavior in reference, the hostname contains a ':' so it gets wrapped in '[', ']'
- URL testURL = new URL("http", "www.apache.org:8082", "test.html#anch");
- assertEquals("Assert 0: wrong protocol", "http", testURL.getProtocol());
- assertEquals("Assert 1: wrong host", "[www.apache.org:8082]", testURL.getHost());
- assertEquals("Assert 2: wrong port", -1, testURL.getPort());
- assertEquals("Assert 3: wrong file", "test.html", testURL.getFile());
- assertEquals("Assert 4: wrong anchor", "anch", testURL.getRef());
-
- try {
- new URL("hftp", "apache.org:8082", "test.html#anch");
- fail("Assert 0: Invalid protocol");
- } catch (MalformedURLException e) {
- // expected
- }
- }
-
- /**
- * @tests java.net.URL#URL(String, String, String)
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Regression test.",
- method = "URL",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_java_protocol_handler_pkgs_prop() throws MalformedURLException {
- // Regression test for Harmony-3094
- final String HANDLER_PKGS = "java.protocol.handler.pkgs";
- String pkgs = System.getProperty(HANDLER_PKGS);
- System.setProperty(HANDLER_PKGS, "fake|org.apache.harmony.luni.tests.java.net");
-
- try {
- new URL("test_protocol", "", "fake.jar");
- } catch (MalformedURLException e) {
- // expected
- } finally {
- if (pkgs == null) {
- System.clearProperty(HANDLER_PKGS);
- } else {
- System.setProperty(HANDLER_PKGS, pkgs);
- }
- }
- }
-
- /**
- * Test method for {@link java.net.URL#hashCode()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void testHashCode() throws MalformedURLException {
- URL testURL1 = new URL("http", "www.apache.org:8080", "test.html#anch");
- URL testURL2 = new URL("http", "www.apache.org:8080", "test.html#anch");
- URL changedURL = new URL("http", "www.apache.org:8082",
- "test.html#anch");
- assertEquals("Assert 0: error in hashCode: not same",
- testURL1.hashCode(), testURL2.hashCode());
- assertFalse("Assert 0: error in hashCode: should be same", testURL1
- .hashCode() == changedURL.hashCode());
- }
-
- /**
- * Test method for {@link java.net.URL#setURLStreamHandlerFactory(java.net.URLStreamHandlerFactory)}.
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "cannot test since no sophisticated StreamHandlerFactory available.",
- method = "setURLStreamHandlerFactory",
- args = {java.net.URLStreamHandlerFactory.class}
- )
- public void testSetURLStreamHandlerFactory() throws MalformedURLException, IOException, IllegalArgumentException, IllegalAccessException {
- URLStreamHandlerFactory factory = new MyURLStreamHandlerFactory();
- Field streamHandlerFactoryField = null;
- int counter = 0;
- File sampleFile = createTempHelloWorldFile();
-
- URL fileURL = sampleFile.toURL();
-
-
- Field[] fields = URL.class.getDeclaredFields();
-
-
- for (Field f : fields) {
- if (URLStreamHandlerFactory.class.equals(f.getType())) {
- counter++;
- streamHandlerFactoryField = f;
- }
- }
-
- if (counter != 1) {
- fail("Error in test setup: not Factory found");
- }
-
- streamHandlerFactoryField.setAccessible(true);
- URLStreamHandlerFactory old = (URLStreamHandlerFactory) streamHandlerFactoryField.get(null);
-
- try {
- streamHandlerFactoryField.set(null, factory);
- BufferedReader buf = new BufferedReader(new InputStreamReader(
- fileURL.openStream()), helloWorldString.getBytes().length);
- String nextline;
- while ((nextline = buf.readLine()) != null) {
- assertEquals(helloWorldString, nextline);
- }
-
- buf.close();
-
- } finally {
-
- streamHandlerFactoryField.set(null, old);
- }
-
- }
-
- /**
- * Test method for {@link java.net.URL#URL(java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URL",
- args = {java.lang.String.class}
- )
- public void testURLString() throws MalformedURLException {
- URL testURL = new URL("ftp://myname@host.dom/etc/motd");
-
- assertEquals("Assert 0: wrong protocol", "ftp", testURL.getProtocol());
- assertEquals("Assert 1: wrong host", "host.dom", testURL.getHost());
- assertEquals("Assert 2: wrong port", -1, testURL.getPort());
- assertEquals("Assert 3: wrong userInfo", "myname", testURL
- .getUserInfo());
- assertEquals("Assert 4: wrong path", "/etc/motd", testURL.getPath());
-
- try {
- new URL("ftpmyname@host.dom/etc/motd");
- fail("Assert 0: malformed URL should throw exception");
- } catch (MalformedURLException e) {
- // expected
- }
-
- }
-
- /**
- * Test method for {@link java.net.URL#URL(java.net.URL, java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URL",
- args = {java.net.URL.class, java.lang.String.class}
- )
- public void testURLURLString() throws MalformedURLException {
-
- URL gamelan = new URL("http://www.gamelan.com/pages/");
-
- URL gamelanNetwork = new URL(gamelan, "Gamelan.net.html");
- URL gamelanNetworkBottom = new URL(gamelanNetwork, "#BOTTOM");
- assertEquals("Assert 0: wrong anchor", "BOTTOM", gamelanNetworkBottom
- .getRef());
- assertEquals("Assert 1: wrong protocol", "http", gamelanNetworkBottom
- .getProtocol());
-
- // same protocol
- URL gamelanNetworBottom2 = new URL(gamelanNetwork,
- "http://www.gamelan.com/pages/Gamelan.net.html#BOTTOM");
- assertEquals(gamelanNetwork.getProtocol(), gamelanNetworBottom2.getProtocol());
-
- // changed protocol
- URL gamelanNetworkBottom3 = new URL(gamelanNetwork,
- "ftp://www.gamelan2.com/pages/Gamelan.net.html#BOTTOM");
- URL absoluteNew = new URL(
- "ftp://www.gamelan2.com/pages/Gamelan.net.html#BOTTOM");
- assertEquals("Host of context URL instead of new URL", "ftp",
- gamelanNetworkBottom3.getProtocol());
- assertTrue("URL is context URL instead of new URL",
- gamelanNetworkBottom3.sameFile(absoluteNew));
-
- // exception testing
- try {
- u = null;
- u1 = new URL(u, "somefile.java");
- fail("didn't throw the expected MalFormedURLException");
- } catch (MalformedURLException e) {
- // ok
- }
-
- // Non existing protocol
- // exception testing
- try {
- u = new URL(gamelanNetwork,
- "someFancyNewProt://www.gamelan2.com/pages/Gamelan.net.html#BOTTOM");
- assertTrue("someFancyNewProt".equalsIgnoreCase(u.getProtocol()));
- } catch (MalformedURLException e) {
- // ok
- }
- }
-
- /**
- * Test method for {@link java.net.URL#set(java.lang.String, java.lang.String, int, java.lang.String, java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "final class protected method",
- method = "set",
- args = {java.lang.String.class, java.lang.String.class, int.class, java.lang.String.class, java.lang.String.class}
- )
- public void testSetStringStringIntStringString() {
-
- }
-
- /**
- * Test method for {@link java.net.URL#equals(java.lang.Object)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void testEqualsObject() throws MalformedURLException {
- URL testURL1 = new URL("http", "www.apache.org:8080", "test.html");
- URL wrongProto = new URL("ftp", "www.apache.org:8080", "test.html");
- URL wrongPort = new URL("http", "www.apache.org:8082", "test.html");
- URL wrongHost = new URL("http", "www.apache2.org:8080", "test.html");
- URL wrongRef = new URL("http", "www.apache.org:8080",
- "test2.html#BOTTOM");
- URL testURL2 = new URL("http://www.apache.org:8080/test.html");
-
-
- assertFalse("Assert 0: error in equals: not same", testURL1
- .equals(wrongProto));
- assertFalse("Assert 1: error in equals: not same", testURL1
- .equals(wrongPort));
- assertFalse("Assert 2: error in equals: not same", testURL1
- .equals(wrongHost));
- assertFalse("Assert 3: error in equals: not same", testURL1
- .equals(wrongRef));
-
- assertFalse("Assert 4: error in equals: not same", testURL1
- .equals(testURL2));
-
- URL testURL3 = new URL("http", "www.apache.org", "/test.html");
- URL testURL4 = new URL("http://www.apache.org/test.html");
- assertTrue("Assert 4: error in equals: same", testURL3
- .equals(testURL4));
- }
-
- /**
- * Test method for {@link java.net.URL#sameFile(java.net.URL)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "non trivial reference test fails",
- method = "sameFile",
- args = {java.net.URL.class}
- )
- public void testSameFile() throws MalformedURLException {
- URL gamelan = new URL("file:///pages/index.html");
- URL gamelanFalse = new URL("file:///pages/out/index.html");
-
- URL gamelanNetwork = new URL(gamelan, "#BOTTOM");
- assertTrue(gamelanNetwork.sameFile(gamelan));
-
- assertFalse(gamelanNetwork.sameFile(gamelanFalse));
-
- // non trivial test
- URL url = new URL("http://web2.javasoft.com/some+file.html");
- URL url1 = new URL("http://web2.javasoft.com/some%20file.html");
-
- assertFalse(url.sameFile(url1));
- }
-
- /**
- * Test method for {@link java.net.URL#getContent()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "image and sound content not testable: mime types",
- method = "getContent",
- args = {}
- )
- public void testGetContent() throws MalformedURLException {
-
- File sampleFile = createTempHelloWorldFile();
-
- // read content from file
- URL fileURL = sampleFile.toURL();
-
- try {
- InputStream output = (InputStream) fileURL.getContent();
- assertTrue(output.available() > 0);
- // ok
- } catch (Exception e) {
- fail("Did not get output type from File URL");
- }
-
- //Exception test
- URL invalidFile = new URL("file:///nonexistenttestdir/tstfile");
-
- try {
- invalidFile.getContent();
- fail("Access to invalid file worked");
- } catch (IOException e) {
- //ok
- }
-
- }
-
- /**
- * Test method for {@link java.net.URL#openStream()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "openStream",
- args = {}
- )
- public void testOpenStream() throws MalformedURLException, IOException {
-
- File sampleFile = createTempHelloWorldFile();
-
- // read content from file
- URL fileURL = sampleFile.toURL();
- BufferedReader dis = null;
- String inputLine;
- StringBuffer buf = new StringBuffer(32);
- try {
- dis = new BufferedReader(
- new InputStreamReader(fileURL.openStream()), 32);
- while ((inputLine = dis.readLine()) != null) {
- buf.append(inputLine);
- }
- dis.close();
- } catch (IOException e) {
- fail("Unexpected error in test setup: " + e.getMessage());
- }
-
- assertTrue("Assert 0: Nothing was read from file ", buf.length() > 0);
- assertEquals("Assert 1: Wrong stream content", "Hello World", buf
- .toString());
-
- // exception test
-
- URL invalidFile = new URL("file:///nonexistenttestdir/tstfile");
-
- try {
- dis = new BufferedReader(
- new InputStreamReader(invalidFile.openStream()), 32);
- while ((inputLine = dis.readLine()) != null) {
- buf.append(inputLine);
- }
- fail("Access to invalid file worked");
- } catch (Exception e) {
- //ok
- } finally {
- dis.close();
- }
- }
-
- /**
- * Test method for {@link java.net.URL#openConnection()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "openConnection",
- args = {}
- )
- public void testOpenConnection() throws MalformedURLException, IOException {
-
- File sampleFile = createTempHelloWorldFile();
-
- byte[] ba;
- InputStream is;
- String s;
- u = sampleFile.toURL();
- u.openConnection();
-
- is = (InputStream) u.getContent(new Class[] { Object.class });
- is.read(ba = new byte[4096]);
- s = new String(ba);
- assertTrue("Incorrect content " + u
- + " does not contain: \"Hello World\"",
- s.indexOf("Hello World") >= 0);
-
- try {
- URL u = new URL("https://a.xy.com/index.html");
- URLConnection conn = u.openConnection();
- conn.connect();
- fail("Should not be able to read from this site.");
- } catch (IOException e) {
- //ok
- }
-
- System.setSecurityManager(new MockSecurityManager());
- try {
- URL u = new URL("http://127.0.0.1");
- URLConnection conn = u.openConnection();
- conn.connect();
- fail("Should not be able to read from this site.");
- } catch (SecurityException e) {
- //ok
- } finally {
- System.setSecurityManager(null);
- }
-
- }
-
- /**
- * Test method for {@link java.net.URL#toURI()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toURI",
- args = {}
- )
- public void testToURI() throws MalformedURLException, URISyntaxException {
- String testHTTPURLString = "http://www.gamelan.com/pages/";
- String testFTPURLString = "ftp://myname@host.dom/etc/motd";
- URL testHTTPURL = new URL(testHTTPURLString);
- URL testFTPURL = new URL(testFTPURLString);
-
- URI testHTTPURI = testHTTPURL.toURI();
- URI testFTPURI = testFTPURL.toURI();
- assertEquals(testHTTPURI.toString(),testHTTPURLString);
- assertEquals(testFTPURI.toString(),testFTPURLString);
-
- //Exception test
- String[] constructorTestsInvalid = new String[] {
- "http:///a path#frag", // space char in path, not in escaped
- // octet form, with no host
- "http://host/a[path#frag", // an illegal char, not in escaped
- // octet form, should throw an
- // exception
- "http://host/a%path#frag", // invalid escape sequence in path
- "http://host/a%#frag", // incomplete escape sequence in path
-
- "http://host#a frag", // space char in fragment, not in
- // escaped octet form, no path
- "http://host/a#fr#ag", // illegal char in fragment
- "http:///path#fr%ag", // invalid escape sequence in fragment,
- // with no host
- "http://host/path#frag%", // incomplete escape sequence in
- // fragment
-
- "http://host/path?a query#frag", // space char in query, not
- // in escaped octet form
- "http://host?query%ag", // invalid escape sequence in query, no
- // path
- "http:///path?query%", // incomplete escape sequence in query,
- // with no host
-
- "mailto:user^name@fklkf.com" // invalid char in scheme
- };
-
- for (String malformedURI : Arrays.asList(constructorTestsInvalid)) {
- try {
- URL urlQuery = new URL("http://host/a%path#frag");
- urlQuery.toURI();
- fail("Exception expected");
- } catch (URISyntaxException e) {
- // ok
- }
- }
- }
-
- /**
- * Test method for {@link java.net.URL#openConnection(java.net.Proxy)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "See ExcludedProxyTest.",
- method = "openConnection",
- args = {java.net.Proxy.class}
- )
- @BrokenTest("the host address isn't working anymore")
- public void testOpenConnectionProxy() throws IOException {
-
- // create Proxy
-
- System.setProperty("http.proxyHost",
- Support_Configuration.ProxyServerTestHost);
- System.setProperty("http.proxyPort", "80");
-
- URL u2 = new URL("http://"
- + Support_Configuration.ProxyServerTestHost
- + "/cgi-bin/test.pl");
-
- SocketAddress addr1 = new InetSocketAddress(Support_Configuration.ProxyServerTestHost, 80);
- Proxy proxy1 = new Proxy(Proxy.Type.HTTP, addr1);
-
- // create test input
- String posted = "just a test";
-
- // perform test
- java.net.HttpURLConnection conn = (java.net.HttpURLConnection) u2
- .openConnection(proxy1);
- conn.setDoOutput(true);
- conn.setRequestMethod("POST");
- conn.setConnectTimeout(3000);
-
- OutputStream out = conn.getOutputStream();
- out.write(posted.getBytes());
- out.close();
-
-
- /*
- InputStream in = conn.getErrorStream();
- if (in != null ){
- BufferedReader r = new BufferedReader(new InputStreamReader(in), 200);
- String line;
- while((line = r.readLine())!= null) {
- System.err.println(line);
- }
- }
- */
-
- conn.getResponseCode();
- InputStream is = conn.getInputStream();
- String response = "";
- byte[] b = new byte[1024];
- int count = 0;
- while ((count = is.read(b)) > 0) {
- response += new String(b, 0, count);
- }
- assertTrue("Response to POST method invalid", response
- .equals(posted));
-
- // Exception test
- URL httpUrl = new URL("http://abc.com");
- URL jarUrl = new URL("jar:"
- + Support_Resources.getResourceURL("/JUC/lf.jar!/plus.bmp"));
- URL ftpUrl = new URL("ftp://" + Support_Configuration.FTPTestAddress
- + "/nettest.txt");
- URL fileUrl = new URL("file://abc");
- URL[] urlList = { httpUrl, jarUrl, ftpUrl, fileUrl };
- for (int i = 0; i < urlList.length; ++i) {
- try {
- urlList[i].openConnection(null);
- } catch (IllegalArgumentException iae) {
- // expected
- }
- }
- // should not throw exception too
- fileUrl.openConnection(Proxy.NO_PROXY);
-
- }
-
- /**
- * Test method for {@link java.net.URL#toString()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void testToString() throws MalformedURLException {
- URL testHTTPURL = new URL("http://www.gamelan.com/pages/");
- URL testFTPURL = new URL("ftp://myname@host.dom/etc/motd");
-
- assertEquals(testHTTPURL.toString(),testHTTPURL.toExternalForm());
- assertEquals(testFTPURL.toString(),testFTPURL.toExternalForm());
-
- assertEquals("http://www.gamelan.com/pages/", testHTTPURL.toString());
- }
-
- /**
- * Test method for {@link java.net.URL#toExternalForm()}.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "simple tests",
- method = "toExternalForm",
- args = {}
- )
- public void testToExternalForm() throws MalformedURLException {
- URL testHTTPURL = new URL("http://www.gamelan.com/pages/");
- URL testFTPURL = new URL("ftp://myname@host.dom/etc/motd");
-
- assertEquals(testHTTPURL.toString(),testHTTPURL.toExternalForm());
- assertEquals(testFTPURL.toString(),testFTPURL.toExternalForm());
-
- assertEquals("http://www.gamelan.com/pages/", testHTTPURL.toExternalForm());
- }
-
- /**
- * Test method for {@link java.net.URL#getFile()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFile",
- args = {}
- )
- public void testGetFile() throws MalformedURLException {
-
- File sampleFile = createTempHelloWorldFile();
-
- // read content from file
- URL fileURL = sampleFile.toURL();
- assertNotNull(fileURL);
- assertEquals(sampleFile.getPath(),fileURL.getFile());
- }
-
- /**
- * Test method for {@link java.net.URL#getPort()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPort",
- args = {}
- )
- public void testGetPort() throws MalformedURLException {
- URL testHTTPURL = new URL("http://www.gamelan.com/pages/");
- URL testFTPURL = new URL("ftp://myname@host.dom/etc/motd");
-
- assertEquals(-1,testFTPURL.getPort());
- assertEquals(-1,testHTTPURL.getPort());
-
- URL testHTTPURL8082 = new URL("http://www.gamelan.com:8082/pages/");
- assertEquals(8082, testHTTPURL8082.getPort());
-
- }
-
- /**
- * Test method for {@link java.net.URL#getProtocol()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getProtocol",
- args = {}
- )
- public void testGetProtocol() throws MalformedURLException {
- URL testHTTPURL = new URL("http://www.gamelan.com/pages/");
- URL testHTTPSURL = new URL("https://www.gamelan.com/pages/");
- URL testFTPURL = new URL("ftp://myname@host.dom/etc/motd");
- URL testFile = new URL("file:///pages/index.html");
- URL testJarURL = new URL("jar:file:///bar.jar!/foo.jar!/Bugs/HelloWorld.class");
-
- assertTrue("http".equalsIgnoreCase(testHTTPURL.getProtocol()));
- assertTrue("https".equalsIgnoreCase(testHTTPSURL.getProtocol()));
- assertTrue("ftp".equalsIgnoreCase(testFTPURL.getProtocol()));
- assertTrue("file".equalsIgnoreCase(testFile.getProtocol()));
- assertTrue("jar".equalsIgnoreCase(testJarURL.getProtocol()));
-
- }
-
- /**
- * Test method for {@link java.net.URL#getRef()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRef",
- args = {}
- )
- public void testGetRef() throws MalformedURLException {
- URL gamelan = new URL("http://www.gamelan.com/pages/");
-
- String output = gamelan.getRef();
- assertTrue(output == null || output.equals(""));
-
- URL gamelanNetwork = new URL(gamelan, "Gamelan.net.html#BOTTOM");
- assertEquals("BOTTOM", gamelanNetwork.getRef());
-
- URL gamelanNetwork2 = new URL("http", "www.gamelan.com",
- "Gamelan.network.html#BOTTOM");
-
- assertEquals("BOTTOM", gamelanNetwork2.getRef());
-
- }
-
- /**
- * Test method for {@link java.net.URL#getQuery()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getQuery",
- args = {}
- )
- public void testGetQuery() throws MalformedURLException {
- URL urlQuery = new URL(
- "http://www.example.com/index.html?attrib1=value1&attrib2=value&attrib3#anchor");
- URL urlNoQuery = new URL(
- "http://www.example.com/index.html#anchor");
-
- assertEquals("attrib1=value1&attrib2=value&attrib3", urlQuery.getQuery());
-
- String output = urlNoQuery.getQuery();
- assertTrue(output == null || "".equals(output));
- }
-
- /**
- * Test method for {@link java.net.URL#getPath()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPath",
- args = {}
- )
- public void testGetPath() throws MalformedURLException {
- URL url = new URL("http://www.example.com");
- String output = url.getPath();
-
- assertTrue("".equals(output) || output == null);
-
- URL url2 = new URL(url,"/foo/index.html");
- assertEquals("/foo/index.html",url2.getPath());
- }
-
- /**
- * Test method for {@link java.net.URL#getUserInfo()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getUserInfo",
- args = {}
- )
- public void testGetUserInfo() throws MalformedURLException {
- URL urlNoUserInfo = new URL("http://www.java2s.com:8080");
- URL url = new URL("ftp://myUser:password@host.dom/etc/motd");
-
- assertEquals("Assert 0: Wrong user","myUser:password",url.getUserInfo());
- String userInfo = urlNoUserInfo.getUserInfo();
- assertTrue("".equals(userInfo) || null == userInfo);
- }
-
- /**
- * Test method for {@link java.net.URL#getAuthority()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAuthority",
- args = {}
- )
- public void testGetAuthority() throws MalformedURLException, URISyntaxException {
- // legal authority information userInfo (user,password),domain,port
-
- URL url = new URL("http://www.java2s.com:8080");
- assertEquals("Assert 0: Wrong authority ", "www.java2s.com:8080", url
- .getAuthority());
-
- URL ftpURL = new URL("ftp://myname@host.dom/etc/motd");
- assertEquals("Assert 1: Wrong authority ", "myname@host.dom", ftpURL
- .getAuthority());
-
- URI testURI = new URI("/relative/URI/with/absolute/path/to/resource.txt");
- String output = testURI.getAuthority();
- assertTrue("".equals(output) || null == output);
- }
-
- /**
- * Test method for {@link java.net.URL#set(java.lang.String, java.lang.String, int, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)}.
- */
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "final class protected method",
- method = "set",
- args = {java.lang.String.class, java.lang.String.class, int.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void testSetStringStringIntStringStringStringStringString() {
-
- }
-
- /**
- * Test method for {@link java.net.URL#getDefaultPort()}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDefaultPort",
- args = {}
- )
- public void testGetDefaultPort() throws MalformedURLException {
- URL testHTTPURL = new URL("http://www.gamelan.com/pages/");
- URL testFTPURL = new URL("ftp://myname@host.dom/etc/motd");
-
- assertEquals(21,testFTPURL.getDefaultPort());
- assertEquals(80,testHTTPURL.getDefaultPort());
- }
-
- private File createTempHelloWorldFile() {
- // create content to read
- File tmpDir = new File(System.getProperty("java.io.tmpdir"));
- File sampleFile = null;
- try {
- if (tmpDir.isDirectory()) {
- sampleFile = File.createTempFile("openStreamTest", ".txt",
- tmpDir);
- sampleFile.deleteOnExit();
- } else {
- fail("Error in test setup java.io.tmpdir does not exist");
- }
-
- FileWriter fstream = new FileWriter(sampleFile);
- BufferedWriter out = new BufferedWriter(fstream, 32);
- out.write(helloWorldString);
- // Close the output stream
- out.close();
- } catch (Exception e) {// Catch exception if any
- fail("Error: in test setup" + e.getMessage());
- }
-
- return sampleFile;
- }
-
- // start HARMONY branch
-
- public static class MyHandler extends URLStreamHandler {
- protected URLConnection openConnection(URL u)
- throws IOException {
- return null;
- }
- }
-
- URL u;
-
- URL u1;
-
- URL u2;
-
- boolean caught = false;
-
- static boolean isSelectCalled;
-
-
-
- static class MockProxySelector extends ProxySelector {
-
- public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
- System.out.println("connection failed");
- }
-
- public List<Proxy> select(URI uri) {
- isSelectCalled = true;
- ArrayList<Proxy> proxyList = new ArrayList<Proxy>(1);
- proxyList.add(Proxy.NO_PROXY);
- return proxyList;
- }
- }
-
- static class MockSecurityManager extends SecurityManager {
-
- public void checkConnect(String host, int port) {
- if ("127.0.0.1".equals(host)) {
- throw new SecurityException("permission is not allowed");
- }
- }
-
- public void checkPermission(Permission permission) {
- if ("setSecurityManager".equals(permission.getName())) {
- return;
- }
- super.checkPermission(permission);
- }
-
- }
-
-
- static class MyURLStreamHandler extends URLStreamHandler {
-
- @Override
- protected URLConnection openConnection(URL arg0) throws IOException {
- try {
- URLConnection con = arg0.openConnection();
- con.setDoInput(true);
- con.connect();
- return con;
- } catch (Throwable e) {
- return null;
- }
- }
-
- public void parse(URL url, String spec, int start, int end) {
- parseURL(url, spec, start, end);
- }
- }
-
- static class MyURLStreamHandlerFactory implements URLStreamHandlerFactory {
-
- public static MyURLStreamHandler handler = new MyURLStreamHandler();
-
- public URLStreamHandler createURLStreamHandler(String arg0) {
- handler = new MyURLStreamHandler();
- return handler;
- }
-
- }
-
- /**
- * URLStreamHandler implementation class necessary for tests.
- */
- private class TestURLStreamHandler extends URLStreamHandler {
- public URLConnection openConnection(URL arg0) throws IOException {
- try {
- URLConnection con = arg0.openConnection();
- con.setDoInput(true);
- con.connect();
- return con;
- } catch (Throwable e) {
- return null;
- }
- }
-
- public URLConnection openConnection(URL arg0, Proxy proxy)
- throws IOException {
- return super.openConnection(u, proxy);
- }
- }
-
- /**
- * Test method for {@link java.net.URL#URL(java.lang.String, java.lang.String, int, java.lang.String, java.net.URLStreamHandler)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch. No meaningful MalformedURLException foundwhich doesn't end as a NullPointerException.",
- method = "URL",
- args = {java.lang.String.class, java.lang.String.class, int.class, java.lang.String.class, java.net.URLStreamHandler.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_StringILjava_lang_StringLjava_net_URLStreamHandler()
- throws Exception {
- u = new URL("http", "www.yahoo.com", 8080, "test.html#foo", null);
- assertEquals("SSISH1 returns a wrong protocol", "http", u.getProtocol());
- assertEquals("SSISH1 returns a wrong host", "www.yahoo.com", u
- .getHost());
- assertEquals("SSISH1 returns a wrong port", 8080, u.getPort());
- assertEquals("SSISH1 returns a wrong file", "test.html", u.getFile());
- assertTrue("SSISH1 returns a wrong anchor: " + u.getRef(), u.getRef()
- .equals("foo"));
-
- u = new URL("http", "www.yahoo.com", 8080, "test.html#foo",
- new MyHandler());
- assertEquals("SSISH2 returns a wrong protocol", "http", u.getProtocol());
- assertEquals("SSISH2 returns a wrong host", "www.yahoo.com", u
- .getHost());
- assertEquals("SSISH2 returns a wrong port", 8080, u.getPort());
- assertEquals("SSISH2 returns a wrong file", "test.html", u.getFile());
- assertTrue("SSISH2 returns a wrong anchor: " + u.getRef(), u.getRef()
- .equals("foo"));
-
- byte[] ba;
- InputStream is;
- String s;
-
- // Cannot make this test fail if no exception is thrown: Debatable
- /*
- try {
- u = new URL("http", "www.yahoo.com", 8080, "test.html#foo",
- null);
- fail("No error occurred");
- } catch (MalformedURLException e) {
- // ok
- } catch (NullPointerException e) {
- // ok
- }
- */
-
- TestURLStreamHandler lh = new TestURLStreamHandler();
-
- u = new URL("http", "www.yahoo.com", 8080, "test.html#foo",
- lh);
-
-
- try {
- new URL(null, "1", 0, "file", lh);
- fail("Exception expected, but nothing was thrown!");
- } catch (MalformedURLException e) {
- // ok
- } catch (NullPointerException e) {
- // Expected NullPointerException
- }
-
- }
-
- /**
- * Test method for {@link java.net.URL#getContent(java.lang.Class[])}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "throws unexpected exception: NullPointerException in first execution",
- method = "getContent",
- args = {java.lang.Class[].class}
- )
- public void test_getContent_LJavaLangClass() throws Exception {
-
- File sampleFile = createTempHelloWorldFile();
-
- byte[] ba;
- String s;
-
- InputStream is = null;
-
- try {
- u = new URL("file:///data/tmp/hyts_htmltest.html");
- is = (InputStream) u.getContent(new Class[] {InputStream.class});
- is.read(ba = new byte[4096]);
- fail("No error occurred reading from nonexisting file");
- } catch (IOException e) {
- // ok
- }
-
- try {
- u = new URL("file:///data/tmp/hyts_htmltest.html");
- is = (InputStream) u.getContent(new Class[] {
- String.class, InputStream.class});
- is.read(ba = new byte[4096]);
- fail("No error occurred reading from nonexisting file");
- } catch (IOException e) {
- // ok
- }
-
- // Check for null
- u = sampleFile.toURL();
- u.openConnection();
- assertNotNull(u);
-
- s = (String) u.getContent(new Class[] {String.class});
- assertNull(s);
-
- }
-
- /**
- * Test method for {@link java.net.URL#URL(java.net.URL, java.lang.String, java.net.URLStreamHandler)}.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "From harmony branch",
- method = "URL",
- args = {java.net.URL.class, java.lang.String.class, java.net.URLStreamHandler.class}
- )
- public void testURLURLStringURLStreamHandler() throws MalformedURLException {
- u = new URL("http://www.yahoo.com");
- // basic ones
- u1 = new URL(u, "file.java", new MyHandler());
- assertEquals("1 returns a wrong protocol", "http", u1.getProtocol());
- assertEquals("1 returns a wrong host", "www.yahoo.com", u1.getHost());
- assertEquals("1 returns a wrong port", -1, u1.getPort());
- assertEquals("1 returns a wrong file", "/file.java", u1.getFile());
- assertNull("1 returns a wrong anchor", u1.getRef());
-
- u1 = new URL(u, "systemresource:/+/FILE0/test.java", new MyHandler());
- assertEquals("2 returns a wrong protocol", "systemresource", u1
- .getProtocol());
- assertTrue("2 returns a wrong host", u1.getHost().equals(""));
- assertEquals("2 returns a wrong port", -1, u1.getPort());
- assertEquals("2 returns a wrong file", "/+/FILE0/test.java", u1
- .getFile());
- assertNull("2 returns a wrong anchor", u1.getRef());
-
- u1 = new URL(u, "dir1/dir2/../file.java", null);
- assertEquals("3 returns a wrong protocol", "http", u1.getProtocol());
- assertEquals("3 returns a wrong host", "www.yahoo.com", u1.getHost());
- assertEquals("3 returns a wrong port", -1, u1.getPort());
- assertEquals("3 returns a wrong file", "/dir1/dir2/../file.java", u1
- .getFile());
- assertNull("3 returns a wrong anchor", u1.getRef());
-
- // test for question mark processing
- u = new URL("http://www.foo.com/d0/d1/d2/cgi-bin?foo=bar/baz");
-
- // test for relative file and out of bound "/../" processing
- u1 = new URL(u, "../dir1/dir2/../file.java", new MyHandler());
- assertTrue("A) returns a wrong file: " + u1.getFile(), u1.getFile()
- .equals("/d0/d1/dir1/file.java"));
-
- // test for absolute and relative file processing
- u1 = new URL(u, "/../dir1/dir2/../file.java", null);
- assertEquals("B) returns a wrong file", "/../dir1/dir2/../file.java",
- u1.getFile());
-
- URL one;
- try {
- one = new URL("http://www.ibm.com");
- } catch (MalformedURLException ex) {
- // Should not happen.
- throw new RuntimeException(ex.getMessage());
- }
- try {
- new URL(one, (String) null, null);
- fail("Specifying null spec on URL constructor should throw MalformedURLException");
- } catch (MalformedURLException e) {
- // expected
- }
-
- }
-
- /**
- * Test method for {@link java.net.URL#toExternalForm()}.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "From harmony branch",
- method = "toExternalForm",
- args = {}
- )
- public void test_toExternalForm_Relative() throws MalformedURLException {
- String strURL = "http://a/b/c/d;p?q";
- String ref = "?y";
- URL url = new URL(new URL(strURL), ref);
- assertEquals("http://a/b/c/?y", url.toExternalForm());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "From harmony branch",
- method = "toExternalForm",
- args = {}
- )
- public void test_toExternalForm_Absolute() throws MalformedURLException {
- String strURL = "http://localhost?name=value";
- URL url = new URL(strURL);
- assertEquals(strURL, url.toExternalForm());
-
- strURL = "http://localhost?name=value/age=12";
- url = new URL(strURL);
- assertEquals(strURL, url.toExternalForm());
- }
-
-
- ServerSocket ss;
-
- Socket s;
-
- Thread t;
-
-
-
- protected void startServer(String name, int port) {
- try {
- ss = new ServerSocket(port, 5);
- } catch (IOException e) {
- fail(name + ": " + e);
- }
- }
-
- class SServer extends Thread implements Runnable {
- Socket s1 = null;
-
- public void run() {
- try {
- ss.setSoTimeout(5000);
- s1 = ss.accept();
- ss.close();
- Thread.sleep(4000);
- } catch (java.io.InterruptedIOException x) {
- System.out.println(Thread.currentThread()
- + ", accept() timeout fired: " + x);
- } catch (InterruptedException x) {
- } catch (Exception e) {
- System.out.println("Unable to accept: " + e.toString());
- } finally {
- try {
- if (s1 != null)
- s1.close();
- } catch (java.io.IOException e) {
- }
- }
- }
- }
-
-
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/test_protocol/Handler.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/test_protocol/Handler.java
deleted file mode 100644
index e868391..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/test_protocol/Handler.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.net.test_protocol;
-
-import java.io.IOException;
-import java.net.URL;
-import java.net.URLConnection;
-import java.net.URLStreamHandler;
-
-public class Handler extends URLStreamHandler {
- protected URLConnection openConnection(URL u) throws IOException {
- return null;
- }
-}
-
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AbstractCollectionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AbstractCollectionTest.java
deleted file mode 100644
index 801727c..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AbstractCollectionTest.java
+++ /dev/null
@@ -1,523 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.AbstractCollection;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import junit.framework.TestCase;
-
-@TestTargetClass(java.util.AbstractCollection.class)
-public class AbstractCollectionTest extends TestCase {
-
- /**
- * @tests java.util.AbstractCollection#add(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.",
- method = "add",
- args = {java.lang.Object.class}
- )
- public void test_addLjava_lang_Object() {
- AbstractCollection<Object> ac = new AbstractCollection<Object>() {
-
- @Override
- public Iterator<Object> iterator() {
- fail("iterator should not get called");
- return null;
- }
-
- @Override
- public int size() {
- fail("size should not get called");
- return 0;
- }
-
- };
- try {
- ac.add(null);
- } catch (UnsupportedOperationException e) {
- }
- }
-
- /**
- * @tests java.util.AbstractCollection#addAll(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.",
- method = "addAll",
- args = {java.util.Collection.class}
- )
- public void test_addAllLjava_util_Collection() {
- final Collection<String> fixtures = Arrays.asList("0", "1", "2");
- AbstractCollection<String> ac = new AbstractCollection<String>() {
-
- @Override
- public boolean add(String object) {
- assertTrue(fixtures.contains(object));
- return true;
- }
-
- @Override
- public Iterator<String> iterator() {
- fail("iterator should not get called");
- return null;
- }
-
- @Override
- public int size() {
- fail("size should not get called");
- return 0;
- }
-
- };
- assertTrue(ac.addAll(fixtures));
- }
-
- /**
- * @tests java.util.AbstractCollection#containsAll(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.",
- method = "containsAll",
- args = {java.util.Collection.class}
- )
- public void test_containsAllLjava_util_Collection() {
- final Collection<String> fixtures = Arrays.asList("0", "1", "2");
- AbstractCollection<String> ac = new AbstractCollection<String>() {
-
- @Override
- public boolean contains(Object object) {
- assertTrue(fixtures.contains(object));
- return true;
- }
-
- @Override
- public Iterator<String> iterator() {
- fail("iterator should not get called");
- return null;
- }
-
- @Override
- public int size() {
- fail("size should not get called");
- return 0;
- }
-
- };
- assertTrue(ac.containsAll(fixtures));
- }
-
- /**
- * @tests java.util.AbstractCollection#isEmpty()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.",
- method = "isEmpty",
- args = {}
- )
- public void test_isEmpty() {
- final boolean[] sizeCalled = new boolean[1];
- AbstractCollection<Object> ac = new AbstractCollection<Object>(){
- @Override
- public Iterator<Object> iterator() {
- fail("iterator should not get called");
- return null;
- }
- @Override
- public int size() {
- sizeCalled[0] = true;
- return 0;
- }
- };
- assertTrue(ac.isEmpty());
- assertTrue(sizeCalled[0]);
- }
-
- /**
- * @tests java.util.AbstractCollection#removeAll(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.",
- method = "removeAll",
- args = {java.util.Collection.class}
- )
- public void test_removeAllLjava_util_Collection() {
- final String[] removed = new String[3];
- AbstractCollection<String> ac = new AbstractCollection<String>() {
-
- @Override
- public Iterator<String> iterator() {
- return new Iterator<String>() {
- String[] values = new String[] {"0", "1", "2"};
- int index;
- public boolean hasNext() {
- return index < values.length;
- }
-
- public String next() {
- return values[index++];
- }
-
- public void remove() {
- removed[index - 1] = values[index - 1];
- }
-
- };
- }
-
- @Override
- public int size() {
- fail("size should not get called");
- return 0;
- }
-
- };
- assertTrue(ac.removeAll(Arrays.asList("0", "1", "2")));
- for (String r : removed) {
- if (!"0".equals(r) && !"1".equals(r) && !"2".equals(r)) {
- fail("an unexpected element was removed");
- }
- }
- }
-
- /**
- * @tests java.util.AbstractCollection#retainAll(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.",
- method = "retainAll",
- args = {java.util.Collection.class}
- )
- public void test_retainAllLjava_util_Collection() {
- final String[] removed = new String[1];
- AbstractCollection<String> ac = new AbstractCollection<String>() {
-
- @Override
- public Iterator<String> iterator() {
- return new Iterator<String>() {
- String[] values = new String[] {"0", "1", "2"};
- int index;
- public boolean hasNext() {
- return index < values.length;
- }
-
- public String next() {
- return values[index++];
- }
-
- public void remove() {
- removed[index - 1] = values[index - 1];
- }
-
- };
- }
-
- @Override
- public int size() {
- fail("size should not get called");
- return 0;
- }
-
- };
- assertTrue(ac.retainAll(Arrays.asList("1", "2")));
- assertEquals("0", removed[0]);
- }
-
- /**
- * @tests java.util.AbstractCollection#toArray()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toArray",
- args = {}
- )
- public void test_toArray() {
- AbstractCollection<String> ac = new AbstractCollection<String>() {
- @Override
- public Iterator<String> iterator() {
- return new Iterator<String>() {
- String[] values = new String[] {"0", "1", "2"};
- int index;
- public boolean hasNext() {
- return index < values.length;
- }
-
- public String next() {
- return values[index++];
- }
-
- public void remove() {
- fail("remove should not get called");
- }
-
- };
- }
-
- @Override
- public int size() {
- return 3;
- }
- };
-
- Object[] array = ac.toArray();
- assertEquals(3, array.length);
- for (Object o : array) {
- if (!"0".equals(o) && !"1".equals(o) && !"2".equals(o)) {
- fail("an unexpected element was removed");
- }
- }
- }
-
- /**
- * @tests java.util.AbstractCollection#toArray(java.lang.Object[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toArray",
- args = {java.lang.Object[].class}
- )
- public void test_toArray$Ljava_lang_Object() {
- AbstractCollection<String> ac = new AbstractCollection<String>() {
- @Override
- public Iterator<String> iterator() {
- return new Iterator<String>() {
- String[] values = new String[] {"0", "1", "2"};
- int index;
- public boolean hasNext() {
- return index < values.length;
- }
-
- public String next() {
- return values[index++];
- }
-
- public void remove() {
- fail("remove should not get called");
- }
-
- };
- }
- @Override
- public int size() {
- return 3;
- }
- };
- try {
- ac.toArray(null);
- fail("No expected NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- ac.toArray(new StringBuffer[ac.size()]);
- fail("No expected ArrayStoreException");
- } catch (ArrayStoreException e) {
- // expected
- }
-
- String[] a = new String[3];
- assertSame(a, ac.toArray(a));
-
- a = new String[0];
- assertNotSame(a, ac.toArray(a));
- a = ac.toArray(a);
- assertEquals(3, a.length);
-
- CharSequence[] csa = new CharSequence[3];
- ac.toArray(csa);
- assertEquals(3, csa.length);
- assertEquals("0", csa[0]);
- assertEquals("1", csa[1]);
- assertEquals("2", csa[2]);
- }
-
- /**
- * @tests java.util.AbstractCollection#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // see HARMONY-1522
- // collection that returns null iterator(this is against the spec.)
- AbstractCollection<?> c = new AbstractCollection<Object>() {
- @Override
- public int size() {
- // return non-zero value to pass 'isEmpty' check
- return 1;
- }
-
- @Override
- public Iterator<Object> iterator() {
- // this violates the spec.
- return null;
- }
- };
-
- try {
- // AbstractCollection.toString() doesn't verify
- // whether iterator() returns null value or not
- c.toString();
- fail("No expected NullPointerException");
- } catch (NullPointerException e) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AbstractCollection",
- args = {}
- )
- public void test_Constructor() {
- AbstractCollection<?> ac = new AbstractCollection<Object>() {
- @Override
- public Iterator<Object> iterator() {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- assertNotNull(ac);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- AbstractCollection<?> ac = new AbstractCollection<Object>() {
- @Override
- public Iterator<Object> iterator() {
- return new Iterator<Object>() {
-
- public boolean hasNext() {
- return false;
- }
-
- public Object next() {
- return null;
- }
-
- public void remove() {
- }
- };
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- ac.clear();
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.",
- method = "contains",
- args = {java.lang.Object.class}
- )
- public void test_containsLjava_lang_Object() {
- AbstractCollection<?> ac = new AbstractCollection<Object>() {
- @Override
- public Iterator<Object> iterator() {
- return new Iterator<Object>() {
-
- public boolean hasNext() {
- return false;
- }
-
- public Object next() {
- return null;
- }
-
- public void remove() {
- }
- };
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- assertFalse(ac.contains(this));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.Vector.",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_removeLjava_lang_Object() {
- AbstractCollection<?> ac = new AbstractCollection<Object>() {
- @Override
- public Iterator<Object> iterator() {
- return new Iterator<Object>() {
-
- public boolean hasNext() {
- return false;
- }
-
- public Object next() {
- return null;
- }
-
- public void remove() {
- }
- };
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- assertFalse(ac.remove(this));
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AbstractMapTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AbstractMapTest.java
deleted file mode 100644
index e5e3c11..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AbstractMapTest.java
+++ /dev/null
@@ -1,533 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.AbstractMap;
-import java.util.AbstractSet;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.IdentityHashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-import java.util.Vector;
-import java.util.WeakHashMap;
-
-@TestTargetClass(java.util.AbstractMap.class)
-public class AbstractMapTest extends junit.framework.TestCase {
-
- static final String specialKey = "specialKey".intern();
-
- static final String specialValue = "specialValue".intern();
-
- // The impl of MyMap is not realistic, but serves to create a type
- // that uses the default remove behavior.
- class MyMap extends AbstractMap {
- final Set mySet = new HashSet(1);
-
- MyMap() {
- mySet.add(new Map.Entry() {
- public Object getKey() {
- return specialKey;
- }
-
- public Object getValue() {
- return specialValue;
- }
-
- public Object setValue(Object object) {
- return null;
- }
- });
- }
-
- public Object put(Object key, Object value) {
- return null;
- }
-
- public Set entrySet() {
- return mySet;
- }
- }
-
- /**
- * @tests java.util.AbstractMap#keySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.HashMap.",
- method = "keySet",
- args = {}
- )
- public void test_keySet() {
- AbstractMap map1 = new HashMap(0);
- assertSame("HashMap(0)", map1.keySet(), map1.keySet());
-
- AbstractMap map2 = new HashMap(10);
- assertSame("HashMap(10)", map2.keySet(), map2.keySet());
-
- Map map3 = Collections.EMPTY_MAP;
- assertSame("EMPTY_MAP", map3.keySet(), map3.keySet());
-
- AbstractMap map4 = new IdentityHashMap(1);
- assertSame("IdentityHashMap", map4.keySet(), map4.keySet());
-
- AbstractMap map5 = new LinkedHashMap(122);
- assertSame("LinkedHashMap", map5.keySet(), map5.keySet());
-
- AbstractMap map6 = new TreeMap();
- assertSame("TreeMap", map6.keySet(), map6.keySet());
-
- AbstractMap map7 = new WeakHashMap();
- assertSame("WeakHashMap", map7.keySet(), map7.keySet());
- }
-
- /**
- * @tests java.util.AbstractMap#remove(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.HashMap.",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_removeLjava_lang_Object() {
- Object key = new Object();
- Object value = new Object();
-
- AbstractMap map1 = new HashMap(0);
- map1.put("key", value);
- assertSame("HashMap(0)", map1.remove("key"), value);
-
- AbstractMap map4 = new IdentityHashMap(1);
- map4.put(key, value);
- assertSame("IdentityHashMap", map4.remove(key), value);
-
- AbstractMap map5 = new LinkedHashMap(122);
- map5.put(key, value);
- assertSame("LinkedHashMap", map5.remove(key), value);
-
- AbstractMap map6 = new TreeMap(new Comparator() {
- // Bogus comparator
- public int compare(Object object1, Object object2) {
- return 0;
- }
- });
- map6.put(key, value);
- assertSame("TreeMap", map6.remove(key), value);
-
- AbstractMap map7 = new WeakHashMap();
- map7.put(key, value);
- assertSame("WeakHashMap", map7.remove(key), value);
-
- AbstractMap aSpecialMap = new MyMap();
- aSpecialMap.put(specialKey, specialValue);
- Object valueOut = aSpecialMap.remove(specialKey);
- assertSame("MyMap", valueOut, specialValue);
- }
-
- /**
- * @tests java.util.AbstractMap#values()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.HashMap.",
- method = "values",
- args = {}
- )
- public void test_values() {
- AbstractMap map1 = new HashMap(0);
- assertSame("HashMap(0)", map1.values(), map1.values());
-
- AbstractMap map2 = new HashMap(10);
- assertSame("HashMap(10)", map2.values(), map2.values());
-
- Map map3 = Collections.EMPTY_MAP;
- assertSame("EMPTY_MAP", map3.values(), map3.values());
-
- AbstractMap map4 = new IdentityHashMap(1);
- assertSame("IdentityHashMap", map4.values(), map4.values());
-
- AbstractMap map5 = new LinkedHashMap(122);
- assertSame("IdentityHashMap", map5.values(), map5.values());
-
- AbstractMap map6 = new TreeMap();
- assertSame("TreeMap", map6.values(), map6.values());
-
- AbstractMap map7 = new WeakHashMap();
- assertSame("WeakHashMap", map7.values(), map7.values());
- }
-
- /**
- * @tests java.util.AbstractMap#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.HashMap.",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- class MyMap extends AbstractMap implements Cloneable {
- private Map map = new HashMap();
-
- public Set entrySet() {
- return map.entrySet();
- }
-
- public Object put(Object key, Object value) {
- return map.put(key, value);
- }
-
- public Map getMap() {
- return map;
- }
-
- public Object clone() {
- try {
- return super.clone();
- } catch (CloneNotSupportedException e) {
- return null;
- }
- }
- }
- ;
- MyMap map = new MyMap();
- map.put("one", "1");
- Map.Entry entry = (Map.Entry) map.entrySet().iterator().next();
- assertTrue("entry not added", entry.getKey() == "one"
- && entry.getValue() == "1");
- MyMap mapClone = (MyMap) map.clone();
- assertTrue("clone not shallow", map.getMap() == mapClone.getMap());
- }
-
- class MocAbstractMap<K, V> extends AbstractMap {
-
- public Set entrySet() {
- Set set = new MySet();
- return set;
- }
-
- class MySet extends HashSet {
- public void clear() {
- throw new UnsupportedOperationException();
- }
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.HashMap.",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- // normal clear()
- AbstractMap map = new HashMap();
- map.put(1, 1);
- map.clear();
- assertTrue(map.isEmpty());
-
- // Special entrySet return a Set with no clear method.
- AbstractMap myMap = new MocAbstractMap();
- try {
- myMap.clear();
- fail("Should throw UnsupportedOprationException");
- } catch (UnsupportedOperationException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.AbstractMap#containsKey(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.HashMap.",
- method = "containsKey",
- args = {java.lang.Object.class}
- )
- public void test_containsKey() {
- AbstractMap map = new AMT();
-
- assertFalse(map.containsKey("k"));
- assertFalse(map.containsKey(null));
-
- map.put("k", "v");
- map.put("key", null);
- map.put(null, "value");
- map.put(null, null);
-
- assertTrue(map.containsKey("k"));
- assertTrue(map.containsKey("key"));
- assertTrue(map.containsKey(null));
- }
-
- /**
- * @tests java.util.AbstractMap#containsValue(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.HashMap.",
- method = "containsValue",
- args = {java.lang.Object.class}
- )
- public void test_containValue() {
- AbstractMap map = new AMT();
-
- assertFalse(map.containsValue("v"));
- assertFalse(map.containsValue(null));
-
- map.put("k", "v");
- map.put("key", null);
- map.put(null, "value");
-
- assertTrue(map.containsValue("v"));
- assertTrue(map.containsValue("value"));
- assertTrue(map.containsValue(null));
- }
-
- /**
- * @tests java.util.AbstractMap#get(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.HashMap.",
- method = "get",
- args = {java.lang.Object.class}
- )
- public void test_get() {
- AbstractMap map = new AMT();
- assertNull(map.get("key"));
- assertNull(map.get(null));
-
- map.put("k", "v");
- map.put("key", null);
- map.put(null, "value");
-
- assertEquals("v", map.get("k"));
- assertNull(map.get("key"));
- assertEquals("value", map.get(null));
- }
-
- public class AMT extends AbstractMap {
-
- // Very crude AbstractMap implementation
- Vector values = new Vector();
-
- Vector keys = new Vector();
-
- public Set entrySet() {
- return new AbstractSet() {
- public Iterator iterator() {
- return new Iterator() {
- int index = 0;
-
- public boolean hasNext() {
- return index < values.size();
- }
-
- public Object next() {
- if (index < values.size()) {
- Map.Entry me = new Map.Entry() {
- Object v = values.elementAt(index);
-
- Object k = keys.elementAt(index);
-
- public Object getKey() {
- return k;
- }
-
- public Object getValue() {
- return v;
- }
-
- public Object setValue(Object value) {
- return null;
- }
- };
- index++;
- return me;
- }
- return null;
- }
-
- public void remove() {
- }
- };
- }
-
- public int size() {
- return values.size();
- }
- };
- }
-
- public Object put(Object k, Object v) {
- keys.add(k);
- values.add(v);
- return v;
- }
- }
-
- /**
- * @tests {@link java.util.AbstractMap#putAll(Map)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.HashMap.",
- method = "putAll",
- args = {java.util.Map.class}
- )
- public void test_putAllLMap() {
- Hashtable ht = new Hashtable();
- AbstractMap amt = new AMT();
- ht.put("this", "that");
- amt.putAll(ht);
- assertEquals("Should be equal", amt, ht);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.HashMap.",
- method = "AbstractMap",
- args = {}
- )
- public void test_Constructor() {
- AMT amt = new AMT();
- assertNotNull(amt);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.HashMap.",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- AbstractMap amt1 = new AMT();
- AbstractMap amt2 = new AMT();
- assertTrue("assert 0", amt1.equals(amt2));
- assertTrue("assert 1", amt1.equals(amt1));
- assertTrue("assert 2", amt2.equals(amt1));
- amt1.put("1", "one");
- assertFalse("assert 3", amt1.equals(amt2));
- amt1.put("2", "two");
- amt1.put("3", "three");
-
- amt2.put("1", "one");
- amt2.put("2", "two");
- amt2.put("3", "three");
- assertTrue("assert 4", amt1.equals(amt2));
- assertFalse("assert 5", amt1.equals(this));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.HashMap.",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- AMT amt1 = new AMT();
- AMT amt2 = new AMT();
- amt1.put("1", "one");
-
- assertNotSame(amt1.hashCode(), amt2.hashCode());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.HashMap.",
- method = "isEmpty",
- args = {}
- )
- public void test_isEmpty() {
- AMT amt = new AMT();
- assertTrue(amt.isEmpty());
- amt.put("1", "one");
- assertFalse(amt.isEmpty());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.HashMap.",
- method = "put",
- args = {java.lang.Object.class, java.lang.Object.class}
- )
- public void test_put() {
- AMT amt = new AMT();
- assertEquals(0, amt.size());
- amt.put("1", "one");
- assertEquals(1, amt.size());
- amt.put("2", "two");
- assertEquals(2, amt.size());
- amt.put("3", "three");
- assertEquals(3, amt.size());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.HashMap.",
- method = "size",
- args = {}
- )
- public void test_size() {
- AMT amt = new AMT();
- assertEquals(0, amt.size());
- amt.put("1", "one");
- assertEquals(1, amt.size());
- amt.put("2", "two");
- assertEquals(2, amt.size());
- amt.put("3", "three");
- assertEquals(3, amt.size());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract. Functionality tested in subclasses for example in java.util.HashMap.",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- AMT amt = new AMT();
- assertEquals("{}", amt.toString());
- amt.put("1", "one");
- assertEquals("{1=one}", amt.toString());
- amt.put("2", "two");
- assertEquals("{1=one, 2=two}", amt.toString());
- amt.put("3", "three");
- assertEquals("{1=one, 2=two, 3=three}", amt.toString());
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AbstractSetTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AbstractSetTest.java
deleted file mode 100644
index e0034d6..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AbstractSetTest.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.AbstractSequentialList;
-import java.util.AbstractSet;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Vector;
-
-@TestTargetClass(AbstractSet.class)
-public class AbstractSetTest extends TestCase {
-
- class Mock_AbstractSet extends AbstractSet{
-
- @Override
- public Iterator iterator() {
- return new Iterator() {
- public boolean hasNext() {
- return false;
- }
-
- public Object next() {
- return null;
- }
-
- public void remove() {
- }
- };
- }
-
- @Override
- public int size() {
- return 0;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void testHashCode() {
- AbstractSet as = new Mock_AbstractSet();
- assertNotNull(as.hashCode());
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AbstractSet",
- args = {}
- )
- })
- public void testEquals() {
- AbstractSet as1 = new Mock_AbstractSet();
- AbstractSet as2 = new Mock_AbstractSet();
-
- assertTrue(as1.equals(as2));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "removeAll",
- args = {java.util.Collection.class}
- )
- public void testRemoveAll() {
- AbstractSet as = new AbstractSet(){
- @Override
- public Iterator iterator() {
- return new Iterator() {
- public boolean hasNext() {
- return true;
- }
-
- public Object next() {
- return null;
- }
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
-
- };
- }
-
- @Override
- public int size() {
- return 10;
- }
- };
-
- try {
- as.removeAll(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- Collection c = new Vector();
- c.add(null);
- try {
- as.removeAll(c);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
-
- as = new Mock_AbstractSet();
-
- as.removeAll(c);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AllTests.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AllTests.java
deleted file mode 100644
index 2bfc7bf..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AllTests.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.util;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-import junit.textui.TestRunner;
-
-/**
- * Listing of all the tests that are to be run.
- */
-public class AllTests {
-
- public static void run() {
- TestRunner.main(new String[] { AllTests.class.getName() });
- }
-
- public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.util");
-
- suite.addTestSuite(AbstractCollectionTest.class);
- suite.addTestSuite(AbstractMapTest.class);
- suite.addTestSuite(AbstractSetTest.class);
- suite.addTestSuite(ArraysTest.class);
- suite.addTestSuite(BitSetTest.class);
- suite.addTestSuite(CollectionsTest.class);
- suite.addTestSuite(DateTest.class);
- suite.addTestSuite(DictionaryTest.class);
- suite.addTestSuite(DuplicateFormatFlagsExceptionTest.class);
- suite.addTestSuite(EventListenerProxyTest.class);
- suite.addTestSuite(FormatFlagsConversionMismatchExceptionTest.class);
- suite.addTestSuite(FormattableTest.class);
- suite.addTestSuite(FormatterClosedExceptionTest.class);
- suite.addTestSuite(FormatterTest.class);
- suite.addTestSuite(HashMapTest.class);
- suite.addTestSuite(IdentityHashMapTest.class);
- suite.addTestSuite(IllegalFormatCodePointExceptionTest.class);
- suite.addTestSuite(IllegalFormatConversionExceptionTest.class);
- suite.addTestSuite(IllegalFormatFlagsExceptionTest.class);
- suite.addTestSuite(IllegalFormatPrecisionExceptionTest.class);
- suite.addTestSuite(IllegalFormatWidthExceptionTest.class);
- suite.addTestSuite(InputMismatchExceptionTest.class);
- suite.addTestSuite(InvalidPropertiesFormatExceptionTest.class);
- suite.addTestSuite(LinkedHashMapTest.class);
- suite.addTestSuite(ListIteratorTest.class);
- suite.addTestSuite(LocaleTest.class);
- suite.addTestSuite(MapEntryTest.class);
- suite.addTestSuite(MissingFormatArgumentExceptionTest.class);
- suite.addTestSuite(MissingFormatWidthExceptionTest.class);
- suite.addTestSuite(ObserverTest.class);
- suite.addTestSuite(UnknownFormatConversionExceptionTest.class);
- suite.addTestSuite(UnknownFormatFlagsExceptionTest.class);
- suite.addTestSuite(UUIDTest.class);
- suite.addTestSuite(VectorTest.class);
- suite.addTestSuite(WeakHashMapTest.class);
-
- return suite;
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArrayListTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArrayListTest.java
deleted file mode 100644
index 96952a9..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArrayListTest.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package org.apache.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.ArrayList;
-
-@TestTargetClass(ArrayList.class)
-public class ArrayListTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Regression test.",
- method = "add",
- args = {java.lang.Object.class}
- )
- public void test_addAllCollectionOfQextendsE() {
- // Regression for HARMONY-539
- // https://issues.apache.org/jira/browse/HARMONY-539
- ArrayList<String> alist = new ArrayList<String>();
- ArrayList<String> blist = new ArrayList<String>();
- alist.add("a");
- alist.add("b");
- blist.add("c");
- blist.add("d");
- blist.remove(0);
- blist.addAll(0, alist);
- assertEquals("a", blist.get(0));
- assertEquals("b", blist.get(1));
- assertEquals("d", blist.get(2));
- }
-
-} \ No newline at end of file
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArraysTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArraysTest.java
deleted file mode 100644
index 3b673f3..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArraysTest.java
+++ /dev/null
@@ -1,588 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.Serializable;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.List;
-import java.util.RandomAccess;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-@TestTargetClass(Arrays.class)
-public class ArraysTest extends TestCase {
-
- /**
- * @tests java.util.Arrays#binarySearch(double[], double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "binarySearch",
- args = {double[].class, double.class}
- )
- public void test_binarySearch$DD() {
- double[] specials = new double[] { Double.NEGATIVE_INFINITY,
- -Double.MAX_VALUE, -2d, -Double.MIN_VALUE, -0d, 0d,
- Double.MIN_VALUE, 2d, Double.MAX_VALUE,
- Double.POSITIVE_INFINITY, Double.NaN };
-
- for (int i = 0; i < specials.length; i++) {
- int result = Arrays.binarySearch(specials, specials[i]);
- assertTrue("Assert 0: " + specials[i] + " invalid: " + result,
- result == i);
- }
- assertEquals("Assert 1: Invalid search index for -1d",
- -4, Arrays.binarySearch(specials, -1d));
- assertEquals("Assert 2: Invalid search index for 1d",
- -8, Arrays.binarySearch(specials, 1d));
- }
-
- /**
- * @tests java.util.Arrays#binarySearch(float[], float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "binarySearch",
- args = {float[].class, float.class}
- )
- public void test_binarySearch$FF() {
- float[] specials = new float[] { Float.NEGATIVE_INFINITY,
- -Float.MAX_VALUE, -2f, -Float.MIN_VALUE, -0f, 0f,
- Float.MIN_VALUE, 2f, Float.MAX_VALUE, Float.POSITIVE_INFINITY,
- Float.NaN };
-
- for (int i = 0; i < specials.length; i++) {
- int result = Arrays.binarySearch(specials, specials[i]);
- assertTrue("Assert 0: " + specials[i] + " invalid: " + result,
- result == i);
- }
- assertEquals("Assert 1: Invalid search index for -1f",
- -4, Arrays.binarySearch(specials, -1f));
- assertEquals("Assert 2: Invalid search index for 1f",
- -8, Arrays.binarySearch(specials, 1f));
- }
-
- /**
- * @tests java.util.Arrays#equals(double[], double[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {double[].class, double[].class}
- )
- public void test_equals$D$D() {
- double d[] = new double[100];
- double x[] = new double[100];
- Arrays.fill(d, Double.MAX_VALUE);
- Arrays.fill(x, Double.MIN_VALUE);
-
- assertTrue("Assert 0: Inequal arrays returned true", !Arrays.equals(d, x));
-
- Arrays.fill(x, Double.MAX_VALUE);
- assertTrue("Assert 1: equal arrays returned false", Arrays.equals(d, x));
-
- assertTrue("Assert 2: should be false",
- !Arrays.equals(new double[] { 1.0 }, new double[] { 2.0 }));
-
- assertTrue("Assert 3: NaN not equals",
- Arrays.equals(new double[] { Double.NaN }, new double[] { Double.NaN }));
- assertTrue("Assert 4: 0d equals -0d",
- !Arrays.equals(new double[] { 0d }, new double[] { -0d }));
- }
-
- /**
- * @tests java.util.Arrays#equals(float[], float[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {float[].class, float[].class}
- )
- public void test_equals$F$F() {
- float d[] = new float[100];
- float x[] = new float[100];
- Arrays.fill(d, Float.MAX_VALUE);
- Arrays.fill(x, Float.MIN_VALUE);
-
- assertTrue("Assert 0: Inequal arrays returned true", !Arrays.equals(d, x));
-
- Arrays.fill(x, Float.MAX_VALUE);
- assertTrue("Assert 1: equal arrays returned false", Arrays.equals(d, x));
-
- assertTrue("Assert 2: NaN not equals",
- Arrays.equals(new float[] { Float.NaN }, new float[] { Float.NaN }));
- assertTrue("Assert 3: 0f equals -0f",
- !Arrays.equals(new float[] { 0f }, new float[] { -0f }));
- }
-
- /**
- * @tests java.util.Arrays#sort(double[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {double[].class}
- )
- public void test_sort$D() {
- // Test a basic sort
- double[] reversedArray = new double[100];
- for (int counter = 0; counter < reversedArray.length; counter ++) {
- reversedArray[counter] = (reversedArray.length - counter - 1);
- }
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < reversedArray.length; counter ++) {
- assertTrue("Assert 0: Resulting array not sorted",
- reversedArray[counter] == counter);
- }
-
- // These have to sort as per the Double compare ordering
- double[] specials1 = new double[]{Double.NaN, Double.MAX_VALUE, Double.MIN_VALUE, 0d, -0d, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY};
- double[] specials2 = new double[]{0d, Double.POSITIVE_INFINITY, -0d, Double.NEGATIVE_INFINITY, Double.MIN_VALUE, Double.NaN, Double.MAX_VALUE};
- double[] answer = new double[]{Double.NEGATIVE_INFINITY, -0d, 0d, Double.MIN_VALUE, Double.MAX_VALUE, Double.POSITIVE_INFINITY, Double.NaN};
-
- Arrays.sort(specials1);
- Object[] print1 = new Object[specials1.length];
- for (int i = 0; i < specials1.length; i++) {
- print1[i] = new Double(specials1[i]);
- }
- assertTrue("Assert 1: specials sort incorrectly" + Arrays.asList(print1),
- Arrays.equals(specials1, answer));
-
- Arrays.sort(specials2);
- Object[] print2 = new Object[specials2.length];
- for (int i = 0; i < specials2.length; i++) {
- print2[i] = new Double(specials2[i]);
- }
- assertTrue("Assert 2: specials sort incorrectly " + Arrays.asList(print2),
- Arrays.equals(specials2, answer));
- }
-
- /**
- * @tests java.util.Arrays#sort(float[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {float[].class}
- )
- public void test_sort$F() {
- // Test a basic sort
- float[] reversedArray = new float[100];
- for (int counter = 0; counter < reversedArray.length; counter ++) {
- reversedArray[counter] = (reversedArray.length - counter - 1);
- }
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < reversedArray.length; counter ++) {
- assertTrue("Assert 0: Resulting array not sorted",
- reversedArray[counter] == counter);
- }
-
- float[] specials1 = new float[]{Float.NaN, Float.MAX_VALUE, Float.MIN_VALUE, 0f, -0f, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY};
- float[] specials2 = new float[]{0f, Float.POSITIVE_INFINITY, -0f, Float.NEGATIVE_INFINITY, Float.MIN_VALUE, Float.NaN, Float.MAX_VALUE};
- float[] answer = new float[]{Float.NEGATIVE_INFINITY, -0f, 0f, Float.MIN_VALUE, Float.MAX_VALUE, Float.POSITIVE_INFINITY, Float.NaN};
-
- Arrays.sort(specials1);
- Object[] print1 = new Object[specials1.length];
- for (int i = 0; i < specials1.length; i++) {
- print1[i] = new Float(specials1[i]);
- }
- assertTrue("Assert 1: specials sort incorrectly" + Arrays.asList(print1),
- Arrays.equals(specials1, answer));
-
- Arrays.sort(specials2);
- Object[] print2 = new Object[specials2.length];
- for (int i = 0; i < specials2.length; i++) {
- print2[i] = new Float(specials2[i]);
- }
- assertTrue("Assert 2: specials sort incorrectly" + Arrays.asList(print2),
- Arrays.equals(specials2, answer));
- }
-
- /**
- * @tests java.util.Arrays#toString(boolean[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {boolean[].class}
- )
- public void test_toString$Z() {
- assertEquals("null", Arrays.toString((boolean[])null));
- assertEquals("[]", Arrays.toString(new boolean[] {}));
- assertEquals("[true]", Arrays.toString(new boolean[] {true}));
- assertEquals("[true, false]", Arrays.toString(new boolean[] {true,false}));
- assertEquals("[true, false, true]", Arrays.toString(new boolean[] {true,false,true}));
- }
-
- /**
- * @tests java.util.Arrays#toString(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {byte[].class}
- )
- public void test_toString$B() {
- assertEquals("null", Arrays.toString((byte[])null));
- assertEquals("[]", Arrays.toString(new byte[] {}));
- assertEquals("[0]", Arrays.toString(new byte[] {0}));
- assertEquals("[-1, 0]", Arrays.toString(new byte[] {-1,0}));
- assertEquals("[-1, 0, 1]", Arrays.toString(new byte[] {-1,0,1}));
- }
-
- /**
- * @tests java.util.Arrays#toString(char[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {char[].class}
- )
- public void test_toString$C() {
- assertEquals("null", Arrays.toString((char[])null));
- assertEquals("[]", Arrays.toString(new char[] {}));
- assertEquals("[a]", Arrays.toString(new char[] {'a'}));
- assertEquals("[a, b]", Arrays.toString(new char[] {'a','b'}));
- assertEquals("[a, b, c]", Arrays.toString(new char[] {'a','b','c'}));
- }
-
- /**
- * @tests java.util.Arrays#toString(double[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {double[].class}
- )
- public void test_toString$D() {
- assertEquals("null", Arrays.toString((double[])null));
- assertEquals("[]", Arrays.toString(new double[] {}));
- assertEquals("[0.0]", Arrays.toString(new double[] {0.0D}));
- assertEquals("[-1.0, 0.0]", Arrays.toString(new double[] {-1.0D, 0.0D}));
- assertEquals("[-1.0, 0.0, 1.0]", Arrays.toString(new double[] {-1.0D, 0.0D, 1.0D}));
- }
-
- /**
- * @tests java.util.Arrays#toString(float[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {float[].class}
- )
- public void test_toString$F() {
- assertEquals("null", Arrays.toString((float[])null));
- assertEquals("[]", Arrays.toString(new float[] {}));
- assertEquals("[0.0]", Arrays.toString(new float[] {0.0F}));
- assertEquals("[-1.0, 0.0]", Arrays.toString(new float[] {-1.0F, 0.0F}));
- assertEquals("[-1.0, 0.0, 1.0]", Arrays.toString(new float[] {-1.0F, 0.0F, 1.0F}));
- }
-
- /**
- * @tests java.util.Arrays#toString(int[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {int[].class}
- )
- public void test_toString$I() {
- assertEquals("null", Arrays.toString((int[])null));
- assertEquals("[]", Arrays.toString(new int[] {}));
- assertEquals("[0]", Arrays.toString(new int[] {0}));
- assertEquals("[-1, 0]", Arrays.toString(new int[] {-1, 0}));
- assertEquals("[-1, 0, 1]", Arrays.toString(new int[] {-1, 0, 1}));
- }
-
- /**
- * @tests java.util.Arrays#toString(long[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {long[].class}
- )
- public void test_toString$J() {
- assertEquals("null", Arrays.toString((long[])null));
- assertEquals("[]", Arrays.toString(new long[] {}));
- assertEquals("[0]", Arrays.toString(new long[] {0}));
- assertEquals("[-1, 0]", Arrays.toString(new long[] {-1, 0}));
- assertEquals("[-1, 0, 1]", Arrays.toString(new long[] {-1, 0, 1}));
- }
-
- /**
- * @tests java.util.Arrays#toString(short[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {short[].class}
- )
- public void test_toString$S() {
- assertEquals("null", Arrays.toString((short[])null));
- assertEquals("[]", Arrays.toString(new short[] {}));
- assertEquals("[0]", Arrays.toString(new short[] {0}));
- assertEquals("[-1, 0]", Arrays.toString(new short[] {-1, 0}));
- assertEquals("[-1, 0, 1]", Arrays.toString(new short[] {-1, 0, 1}));
- }
-
- /**
- * @tests java.util.Arrays#toString(Object[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {java.lang.Object[].class}
- )
- public void test_toString$Ljava_lang_Object() {
- assertEquals("null", Arrays.toString((Object[])null));
- assertEquals("[]", Arrays.toString(new Object[] {}));
- assertEquals("[fixture]", Arrays.toString(new Object[] {"fixture"}));
- assertEquals("[fixture, null]", Arrays.toString(new Object[] {"fixture", null}));
- assertEquals("[fixture, null, fixture]", Arrays.toString(new Object[] {"fixture", null, "fixture"}));
- }
-
- /**
- * @tests java.util.Arrays#deepToString(Object[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "deepToString",
- args = {java.lang.Object[].class}
- )
- public void test_deepToString$java_lang_Object() {
- assertEquals("null", Arrays.deepToString((Object[])null));
- assertEquals("[]", Arrays.deepToString(new Object[] {}));
- assertEquals("[fixture]", Arrays.deepToString(new Object[] {"fixture"}));
- assertEquals("[fixture, null]", Arrays.deepToString(new Object[] {"fixture", null}));
- assertEquals("[fixture, null, fixture]", Arrays.deepToString(new Object[] {"fixture", null, "fixture"}));
-
- Object[] fixture = new Object[1];
- fixture[0] = fixture;
- assertEquals("[[...]]", Arrays.deepToString(fixture));
-
- fixture = new Object[2];
- fixture[0] = "fixture";
- fixture[1] = fixture;
- assertEquals("[fixture, [...]]", Arrays.deepToString(fixture));
-
- fixture = new Object[10];
- fixture[0] = new boolean[] {true, false};
- fixture[1] = new byte[] {0, 1};
- fixture[2] = new char[] {'a', 'b'};
- fixture[3] = new double[] {0.0D, 1.0D};
- fixture[4] = new float[] {0.0F, 1.0F};
- fixture[5] = new int[] {0, 1};
- fixture[6] = new long[] {0L, 1L};
- fixture[7] = new short[] {0, 1};
- fixture[8] = fixture[0];
- fixture[9] = new Object[9];
- ((Object[])fixture[9])[0] = fixture;
- ((Object[])fixture[9])[1] = fixture[1];
- ((Object[])fixture[9])[2] = fixture[2];
- ((Object[])fixture[9])[3] = fixture[3];
- ((Object[])fixture[9])[4] = fixture[4];
- ((Object[])fixture[9])[5] = fixture[5];
- ((Object[])fixture[9])[6] = fixture[6];
- ((Object[])fixture[9])[7] = fixture[7];
- Object[] innerFixture = new Object[4];
- innerFixture[0] = "innerFixture0";
- innerFixture[1] = innerFixture;
- innerFixture[2] = fixture;
- innerFixture[3] = "innerFixture3";
- ((Object[])fixture[9])[8] = innerFixture;
-
- String expected = "[[true, false], [0, 1], [a, b], [0.0, 1.0], [0.0, 1.0], [0, 1], [0, 1], [0, 1], [true, false], [[...], [0, 1], [a, b], [0.0, 1.0], [0.0, 1.0], [0, 1], [0, 1], [0, 1], [innerFixture0, [...], [...], innerFixture3]]]";
-
- assertEquals(expected, Arrays.deepToString(fixture));
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "asList",
- args = {java.lang.Object[].class}
- )
- public void test_asListTvararg() throws Exception {
- List<String> stringsList = Arrays.asList("0", "1");
- assertEquals(2, stringsList.size());
- assertEquals("0", stringsList.get(0));
- assertEquals("1", stringsList.get(1));
- assertTrue(stringsList instanceof RandomAccess);
- assertTrue(stringsList instanceof Serializable);
-
- assertEquals(stringsList, SerializationTest
- .copySerializable((Serializable) stringsList));
-
- //test from javadoc
- List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
- assertEquals(3, stooges.size());
- assertEquals("Larry", stooges.get(0));
- assertEquals("Moe", stooges.get(1));
- assertEquals("Curly", stooges.get(2));
-
- stringsList = Arrays.asList((String)null);
- assertEquals(1, stringsList.size());
- assertEquals((String)null, stringsList.get(0));
-
- try {
- Arrays.asList((Object[])null);
- fail("No NPE");
- } catch (NullPointerException e) {}
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "binarySearch",
- args = {java.lang.Object[].class, java.lang.Object.class, java.util.Comparator.class}
- )
- public void test_binarySearch$TTLjava_util_ComparatorsuperT() {
- String[] strings = new String[] { "a", "B", "c", "D" };
- Arrays.sort(strings, String.CASE_INSENSITIVE_ORDER);
- assertEquals(0, Arrays.binarySearch(strings, "a",
- String.CASE_INSENSITIVE_ORDER));
- assertEquals(0, Arrays.binarySearch(strings, "A",
- String.CASE_INSENSITIVE_ORDER));
- assertEquals(1, Arrays.binarySearch(strings, "b",
- String.CASE_INSENSITIVE_ORDER));
- assertEquals(1, Arrays.binarySearch(strings, "B",
- String.CASE_INSENSITIVE_ORDER));
- assertEquals(2, Arrays.binarySearch(strings, "c",
- String.CASE_INSENSITIVE_ORDER));
- assertEquals(2, Arrays.binarySearch(strings, "C",
- String.CASE_INSENSITIVE_ORDER));
- assertEquals(3, Arrays.binarySearch(strings, "d",
- String.CASE_INSENSITIVE_ORDER));
- assertEquals(3, Arrays.binarySearch(strings, "D",
- String.CASE_INSENSITIVE_ORDER));
-
-
- assertTrue(Arrays.binarySearch(strings, "e",
- String.CASE_INSENSITIVE_ORDER) < 0);
- assertTrue(Arrays.binarySearch(strings, "" + ('A' - 1),
- String.CASE_INSENSITIVE_ORDER) < 0);
-
- //test with null comparator, which switches back to Comparable
- Arrays.sort(strings, null);
- //B, D, a, c
- assertEquals(2, Arrays.binarySearch(strings, "a", (Comparator<String>)null));
- assertEquals(-1, Arrays.binarySearch(strings, "A", (Comparator<String>)null));
- assertEquals(-4, Arrays.binarySearch(strings, "b", (Comparator<String>)null));
- assertEquals(0, Arrays.binarySearch(strings, "B", (Comparator<String>)null));
- assertEquals(3, Arrays.binarySearch(strings, "c", (Comparator<String>)null));
- assertEquals(-2, Arrays.binarySearch(strings, "C", (Comparator<String>)null));
- assertEquals(-5, Arrays.binarySearch(strings, "d", (Comparator<String>)null));
- assertEquals(1, Arrays.binarySearch(strings, "D", (Comparator<String>)null));
-
- assertTrue(Arrays.binarySearch(strings, "e", null) < 0);
- assertTrue(Arrays.binarySearch(strings, "" + ('A' - 1), null) < 0);
-
- try {
- Arrays.binarySearch((String[])null, "A", String.CASE_INSENSITIVE_ORDER);
- fail("No NPE");
- } catch (NullPointerException e) {}
-
- try {
- Arrays.binarySearch(strings, (String)null, String.CASE_INSENSITIVE_ORDER);
- fail("No NPE");
- } catch (NullPointerException e) {}
-
- try {
- Arrays.binarySearch(strings, (String)null, (Comparator<String>)null);
- fail("No NPE");
- } catch (NullPointerException e) {}
-
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ClassCastException.",
- method = "sort",
- args = {java.lang.Object[].class, java.util.Comparator.class}
- )
- public void test_sort$TLjava_lang_ComparatorsuperT() {
- String[] strings = new String[] { "a", "B", "c", "D" };
- Arrays.sort(strings, String.CASE_INSENSITIVE_ORDER);
- assertEquals("a", strings[0]);
- assertEquals("B", strings[1]);
- assertEquals("c", strings[2]);
- assertEquals("D", strings[3]);
-
- //test with null comparator, which switches back to Comparable
- Arrays.sort(strings, null);
- //B, D, a, c
- assertEquals("B", strings[0]);
- assertEquals("D", strings[1]);
- assertEquals("a", strings[2]);
- assertEquals("c", strings[3]);
-
- try {
- Arrays.sort((String[])null, String.CASE_INSENSITIVE_ORDER);
- fail("No NPE");
- } catch (NullPointerException e) {}
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify IllegalArgumentException, ArrayIndexOutOfBoundsException, ClassCastException.",
- method = "sort",
- args = {java.lang.Object[].class, int.class, int.class}
- )
- public void test_sort$TIILjava_lang_ComparatorsuperT() {
- String[] strings = new String[] { "a", "B", "c", "D" };
- Arrays.sort(strings, 0, strings.length, String.CASE_INSENSITIVE_ORDER);
- assertEquals("a", strings[0]);
- assertEquals("B", strings[1]);
- assertEquals("c", strings[2]);
- assertEquals("D", strings[3]);
-
- //test with null comparator, which switches back to Comparable
- Arrays.sort(strings, 0, strings.length, null);
- //B, D, a, c
- assertEquals("B", strings[0]);
- assertEquals("D", strings[1]);
- assertEquals("a", strings[2]);
- assertEquals("c", strings[3]);
-
- try {
- Arrays.sort((String[])null, String.CASE_INSENSITIVE_ORDER);
- fail("No NPE");
- } catch (NullPointerException e) {}
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/BitSetTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/BitSetTest.java
deleted file mode 100644
index 769e31f..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/BitSetTest.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.BitSet;
-
-@TestTargetClass(BitSet.class)
-public class BitSetTest extends TestCase {
-
- /**
- * @tests java.util.BitSet#clear(int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IndexOutOfBoundsException is not verified.",
- method = "clear",
- args = {int.class, int.class}
- )
- public void test_clearII() {
- // Regression for HARMONY-98
- BitSet bitset = new BitSet();
- for (int i = 0; i < 20; i++) {
- bitset.set(i);
- }
- bitset.clear(10, 10);
- }
-
- /**
- * @tests java.util.BitSet#flip(int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IndexOutOfBoundsException is not verified.",
- method = "flip",
- args = {int.class, int.class}
- )
- public void test_flipII() {
- BitSet bitset = new BitSet();
- for (int i = 0; i < 20; i++) {
- bitset.set(i);
- }
- bitset.flip(10, 10);
- }
-
- /**
- * @tests java.util.BitSet#get(int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IndexOutOfBoundsException is not verified.",
- method = "get",
- args = {int.class, int.class}
- )
- public void test_getII() {
- BitSet bitset = new BitSet(30);
- bitset.get(3, 3);
- }
-
- /**
- * @tests java.util.BitSet#set(int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IndexOutOfBoundsException is not verified.",
- method = "set",
- args = {int.class, int.class}
- )
- public void test_setII() {
- BitSet bitset = new BitSet(30);
- bitset.set(29, 29);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/CollectionsTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/CollectionsTest.java
deleted file mode 100644
index 7085c31..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/CollectionsTest.java
+++ /dev/null
@@ -1,1003 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.RandomAccess;
-import java.util.Set;
-import java.util.SortedMap;
-import java.util.SortedSet;
-import java.util.TreeMap;
-import java.util.TreeSet;
-import java.util.Vector;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-import tests.util.SerializationTester;
-
-@TestTargetClass(Collections.class)
-public class CollectionsTest extends TestCase {
-
- private static final SerializableAssert comparator = new SerializableAssert() {
- public void assertDeserialized(Serializable reference, Serializable test) {
- assertSame(reference, test);
- }
- };
-
- /**
- * @tests java.util.Collections#binarySearch(java.util.List,
- * java.lang.Object, java.util.Comparator)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "binarySearch",
- args = {java.util.List.class, java.lang.Object.class, java.util.Comparator.class}
- )
- public void test_binarySearchLjava_util_ListLjava_lang_ObjectLjava_util_Comparator() {
- // Regression for HARMONY-94
- LinkedList<Integer> lst = new LinkedList<Integer>();
- lst.add(new Integer(30));
- Collections.sort(lst, null);
- int index = Collections.binarySearch(lst, new Integer(2), null);
- assertEquals(-1, index);
-
- LinkedList<String> lls = new LinkedList<String>();
- lls.add("1");
- lls.add("2");
- lls.add("3");
- lls.add("4");
- lls.add("");
- LinkedList<String> ll = lls;
-
- try {
- Collections.binarySearch(ll, new Integer(10), null);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Collections#binarySearch(java.util.List,
- * java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "binarySearch",
- args = {java.util.List.class, java.lang.Object.class}
- )
- @SuppressWarnings("unchecked")
- public void test_binarySearchLjava_util_ListLjava_lang_Object() {
- // regression for Harmony-1367
- List localList = new LinkedList();
- assertEquals(-1, Collections.binarySearch(localList, new Object()));
- localList.add(new Object());
- try {
- Collections.binarySearch(localList, new Integer(1));
- fail("Should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
-
- LinkedList<String> lls = new LinkedList<String>();
- lls.add("1");
- lls.add("2");
- lls.add("3");
- lls.add("4");
- lls.add("");
- LinkedList ll = lls;
-
- try {
- Collections.binarySearch(ll, new Integer(10));
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Collections#rotate(java.util.List, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "UnsupportedOperationException is not tested.",
- method = "rotate",
- args = {java.util.List.class, int.class}
- )
- public void test_rotateLjava_util_ListI() {
- // Regression for HARMONY-19 Rotate an *empty* list
- Collections.rotate(new ArrayList<Object>(), 25);
-
- // Regression for HARMONY-20
- List<String> list = new ArrayList<String>();
- list.add(0, "zero");
- list.add(1, "one");
- list.add(2, "two");
- list.add(3, "three");
- list.add(4, "four");
-
- Collections.rotate(list, Integer.MIN_VALUE);
- assertEquals("Rotated incorrectly at position 0, ", "three",
- list.get(0));
- assertEquals("Rotated incorrectly at position 1, ", "four",
- list.get(1));
- assertEquals("Rotated incorrectly at position 2, ", "zero",
- list.get(2));
- assertEquals("Rotated incorrectly at position 3, ", "one",
- list.get(3));
- assertEquals("Rotated incorrectly at position 4, ", "two",
- list.get(4));
- }
-
- /**
- * @tests java.util.Collections#synchronizedCollection(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "synchronizedCollection",
- args = {java.util.Collection.class}
- )
- public void test_synchronizedCollectionLjava_util_Collection() {
- try {
- // Regression for HARMONY-93
- Collections.synchronizedCollection(null);
- fail("Assert 0: synchronizedCollection(null) must throw NPE");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Collections#synchronizedSortedMap(java.util.SortedMap)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "synchronizedSortedMap",
- args = {java.util.SortedMap.class}
- )
- public void test_synchronizedSortedMapLjava_util_SortedMap() {
- try {
- // Regression for HARMONY-93
- Collections.synchronizedSortedMap(null);
- fail("Assert 0: synchronizedSortedMap(null) must throw NPE");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Collections#synchronizedMap(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "synchronizedMap",
- args = {java.util.Map.class}
- )
- public void test_synchronizedMapLjava_util_Map() {
- try {
- // Regression for HARMONY-93
- Collections.synchronizedMap(null);
- fail("Assert 0: synchronizedMap(map) must throw NPE");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Collections#synchronizedSet(java.util.Set)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "synchronizedSet",
- args = {java.util.Set.class}
- )
- public void test_synchronizedSetLjava_util_Set() {
- try {
- // Regression for HARMONY-93
- Collections.synchronizedSet(null);
- fail("Assert 0: synchronizedSet(set) must throw NPE");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Collections#synchronizedSortedSet(java.util.SortedSet)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "synchronizedSortedSet",
- args = {java.util.SortedSet.class}
- )
- public void test_synchronizedSortedSetLjava_util_SortedSet() {
- try {
- // Regression for HARMONY-93
- Collections.synchronizedSortedSet(null);
- fail("Assert 0: synchronizedSortedSet(null) must throw NPE");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Collections#unmodifiableCollection(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "unmodifiableCollection",
- args = {java.util.Collection.class}
- )
- public void test_unmodifiableCollectionLjava_util_Collection() {
- try {
- // Regression for HARMONY-93
- Collections.unmodifiableCollection(null);
- fail("Assert 0: unmodifiableCollection(null) must throw NPE");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Collections#unmodifiableMap(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "unmodifiableMap",
- args = {java.util.Map.class}
- )
- public void test_unmodifiableMapLjava_util_Map() {
- try {
- // Regression for HARMONY-93
- Collections.unmodifiableMap(null);
- fail("Assert 0: unmodifiableMap(null) must throw NPE");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Collections#unmodifiableSet(java.util.Set)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "unmodifiableSet",
- args = {java.util.Set.class}
- )
- public void test_unmodifiableSetLjava_util_Set() {
- try {
- // Regression for HARMONY-93
- Collections.unmodifiableSet(null);
- fail("Assert 0: unmodifiableSet(null) must throw NPE");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Collections#unmodifiableSortedMap(java.util.SortedMap)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "unmodifiableSortedMap",
- args = {java.util.SortedMap.class}
- )
- public void test_unmodifiableSortedMapLjava_util_SortedMap() {
- try {
- // Regression for HARMONY-93
- Collections.unmodifiableSortedMap(null);
- fail("Assert 0: unmodifiableSortedMap(null) must throw NPE");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Collections#unmodifiableSortedSet(java.util.SortedSet)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "unmodifiableSortedSet",
- args = {java.util.SortedSet.class}
- )
- public void test_unmodifiableSortedSetLjava_util_SortedSet() {
- try {
- // Regression for HARMONY-93
- Collections.unmodifiableSortedSet(null);
- fail("Assert 0: unmodifiableSortedSet(null) must throw NPE");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Collections#frequency(java.util.Collection,Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "frequency",
- args = {java.util.Collection.class, java.lang.Object.class}
- )
- public void test_frequencyLjava_util_CollectionLint() {
- try {
- Collections.frequency(null, null);
- fail("Assert 0: frequency(null,<any>) must throw NPE");
- } catch (NullPointerException e) {}
-
- List<String> strings = Arrays.asList(new String[] { "1", "2", "3", "1", "1" });
-
- assertEquals("Assert 1: did not find three \"1\" strings", 3,
- Collections.frequency(strings, "1"));
-
- assertEquals("Assert 2: did not find one \"2\" strings", 1, Collections
- .frequency(strings, "2"));
-
- assertEquals("Assert 3: did not find three \"3\" strings", 1,
- Collections.frequency(strings, "3"));
-
- assertEquals("Assert 4: matched on null when there are none", 0,
- Collections.frequency(strings, null));
-
- List<Object> objects = Arrays.asList(new Object[] { new Integer(1), null, null,
- new Long(1) });
-
- assertEquals("Assert 5: did not find one Integer(1)", 1, Collections
- .frequency(objects, new Integer(1)));
-
- assertEquals("Assert 6: did not find one Long(1)", 1, Collections
- .frequency(objects, new Long(1)));
-
- assertEquals("Assert 7: did not find two null references", 2,
- Collections.frequency(objects, null));
- }
-
- /**
- * @tests java.util.Collections#reverseOrder()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reverseOrder",
- args = {}
- )
- public void test_reverseOrder() {
- Comparator<String> roc = Collections.reverseOrder();
- assertNotNull("Assert 0: comparator must not be null", roc);
-
- assertTrue("Assert 1: comparator must implement Serializable",
- roc instanceof Serializable);
-
- String[] fixtureDesc = new String[] { "2", "1", "0" };
- String[] numbers = new String[] { "0", "1", "2" };
- Arrays.sort(numbers, roc);
- assertTrue("Assert 2: the arrays are not equal, the sort failed",
- Arrays.equals(fixtureDesc, numbers));
- }
-
- /**
- * @tests java.util.Collections#reverseOrder(java.util.Comparator)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reverseOrder",
- args = {java.util.Comparator.class}
- )
- public void test_reverseOrderLjava_util_Comparator() {
- Comparator<String> roc = Collections
- .reverseOrder(String.CASE_INSENSITIVE_ORDER);
- assertNotNull("Assert 0: comparator must not be null", roc);
-
- assertTrue("Assert 1: comparator must implement Serializable",
- roc instanceof Serializable);
-
- String[] fixtureDesc = new String[] { "2", "1", "0" };
- String[] numbers = new String[] { "0", "1", "2" };
- Arrays.sort(numbers, roc);
- assertTrue("Assert 2: the arrays are not equal, the sort failed",
- Arrays.equals(fixtureDesc, numbers));
-
- roc = Collections.reverseOrder(null);
- assertNotNull("Assert 3: comparator must not be null", roc);
-
- assertTrue("Assert 4: comparator must implement Serializable",
- roc instanceof Serializable);
-
- numbers = new String[] { "0", "1", "2" };
- Arrays.sort(numbers, roc);
- assertTrue("Assert 5: the arrays are not equal, the sort failed",
- Arrays.equals(fixtureDesc, numbers));
- }
-
- class Mock_Collection implements Collection {
- public boolean add(Object o) {
- throw new UnsupportedOperationException();
- }
-
- public boolean addAll(Collection c) {
- return false;
- }
-
- public void clear() {
- }
-
- public boolean contains(Object o) {
- return false;
- }
-
- public boolean containsAll(Collection c) {
- return false;
- }
-
- public boolean isEmpty() {
- return false;
- }
-
- public Iterator iterator() {
- return null;
- }
-
- public boolean remove(Object o) {
- return false;
- }
-
- public boolean removeAll(Collection c) {
- return false;
- }
-
- public boolean retainAll(Collection c) {
- return false;
- }
-
- public int size() {
- return 0;
- }
-
- public Object[] toArray() {
- return null;
- }
-
- public Object[] toArray(Object[] a) {
- return null;
- }
- }
-
- class Mock_WrongCollection implements Collection {
- final String wrongElement = "Wrong element";
- public boolean add(Object o) {
- if (o.equals(wrongElement)) throw new IllegalArgumentException();
- if (o == null) throw new NullPointerException();
- return false;
- }
-
- public boolean addAll(Collection c) {
- return false;
- }
-
- public void clear() {
- }
-
- public boolean contains(Object o) {
- return false;
- }
-
- public boolean containsAll(Collection c) {
- return false;
- }
-
- public boolean isEmpty() {
- return false;
- }
-
- public Iterator iterator() {
- return null;
- }
-
- public boolean remove(Object o) {
- return false;
- }
-
- public boolean removeAll(Collection c) {
- return false;
- }
-
- public boolean retainAll(Collection c) {
- return false;
- }
-
- public int size() {
- return 0;
- }
-
- public Object[] toArray() {
- return null;
- }
-
- public Object[] toArray(Object[] a) {
- return null;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addAll",
- args = {java.util.Collection.class, java.lang.Object[].class}
- )
- public void test_AddAll() {
- List<Object> l = new ArrayList<Object>();
- assertFalse(Collections.addAll(l, new Object[] {}));
- assertTrue(l.isEmpty());
- assertTrue(Collections.addAll(l, new Object[] { new Integer(1),
- new Integer(2), new Integer(3) }));
- assertFalse(l.isEmpty());
- assertTrue(l.equals(Arrays.asList(new Object[] { new Integer(1),
- new Integer(2), new Integer(3) })));
-
- try {
- Collections.addAll(null,new Object[] { new Integer(1),
- new Integer(2), new Integer(3) });
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //fail
- }
-
- Collection c = new Mock_Collection();
- try {
- Collections.addAll(c, new Object[] { new Integer(1),
- new Integer(2), new Integer(3) });
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
-
- c = new Mock_WrongCollection ();
-
- try {
- Collections.addAll(c, new String[] { "String",
- "Correct element", null });
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //fail
- }
-
- try {
- Collections.addAll(c, new String[] { "String",
- "Wrong element", "Correct element" });
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //fail
- }
-
- Collections.addAll(c, new String[] { "String",
- "", "Correct element" });
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "disjoint",
- args = {java.util.Collection.class, java.util.Collection.class}
- )
- public void test_Disjoint() {
- Object[] arr1 = new Object[10];
- for (int i = 0; i < arr1.length; i++) {
- arr1[i] = new Integer(i);
- }
- Object[] arr2 = new Object[20];
- for (int i = 0; i < arr2.length; i++) {
- arr2[i] = new Integer(100 + i);
- }
- Collection<Object> c1 = new ArrayList<Object>();
- Collection<Object> c2 = new ArrayList<Object>();
- Collections.addAll(c1, arr1);
- Collections.addAll(c2, arr2);
- assertTrue(Collections.disjoint(c1, c2));
- c1.add(arr2[10]);
- assertFalse(Collections.disjoint(c1, c2));
-
- c1 = new LinkedList<Object>();
- c2 = new LinkedList<Object>();
- Collections.addAll(c1, arr1);
- Collections.addAll(c2, arr2);
- assertTrue(Collections.disjoint(c1, c2));
- c1.add(arr2[10]);
- assertFalse(Collections.disjoint(c1, c2));
-
- c1 = new TreeSet<Object>();
- c2 = new TreeSet<Object>();
- Collections.addAll(c1, arr1);
- Collections.addAll(c2, arr2);
- assertTrue(Collections.disjoint(c1, c2));
- c1.add(arr2[10]);
- assertFalse(Collections.disjoint(c1, c2));
-
- c1 = new HashSet<Object>();
- c2 = new HashSet<Object>();
- Collections.addAll(c1, arr1);
- Collections.addAll(c2, arr2);
- assertTrue(Collections.disjoint(c1, c2));
- c1.add(arr2[10]);
- assertFalse(Collections.disjoint(c1, c2));
-
- c1 = new LinkedList<Object>();
- c2 = new TreeSet<Object>();
- Collections.addAll(c1, arr1);
- Collections.addAll(c2, arr2);
- assertTrue(Collections.disjoint(c1, c2));
- c1.add(arr2[10]);
- assertFalse(Collections.disjoint(c1, c2));
-
- c1 = new Vector<Object>();
- c2 = new HashSet<Object>();
- Collections.addAll(c1, arr1);
- Collections.addAll(c2, arr2);
- assertTrue(Collections.disjoint(c1, c2));
- c1.add(arr2[10]);
- assertFalse(Collections.disjoint(c1, c2));
-
- try {
- Collections.disjoint(c1, null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- try {
- Collections.disjoint(null, c2);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Collections.EmptyList#readResolve()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
- public void test_EmptyList_readResolve() throws Exception {
- SerializationTest.verifySelf(Collections.EMPTY_LIST, comparator);
- }
-
- /**
- * @tests java.util.Collections.EmptyMap#readResolve()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
- public void test_EmptyMap_readResolve() throws Exception {
- SerializationTest.verifySelf(Collections.EMPTY_MAP, comparator);
- }
-
- /**
- * @tests java.util.Collections.EmptySet#readResolve()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
- public void test_EmptySet_readResolve() throws Exception {
- SerializationTest.verifySelf(Collections.EMPTY_SET, comparator);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void test_checkedCollectionSerializationCompatability() throws Exception {
- Collection<String> c = Collections.emptySet();
- c = Collections.checkedCollection(c, String.class);
- SerializationTester.assertCompabilityEquals(c, "/serialization/org/apache/harmony/luni/tests/java/util/Collections_CheckedCollection.golden.ser");
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void test_checkedListRandomAccessSerializationCompatability() throws Exception {
- List<String> c = new ArrayList<String>();
- assertTrue(c instanceof RandomAccess);
- c = Collections.checkedList(c, String.class);
- SerializationTester.assertCompabilityEquals(c, "/serialization/org/apache/harmony/luni/tests/java/util/Collections_CheckedListRandomAccess.golden.ser");
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void test_checkedListSerializationCompatability() throws Exception {
- List<String> c = new LinkedList<String>();
- assertFalse(c instanceof RandomAccess);
- c = Collections.checkedList(c, String.class);
- SerializationTester.assertCompabilityEquals(c, "/serialization/org/apache/harmony/luni/tests/java/util/Collections_CheckedList.golden.ser");
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void test_checkedSetSerializationCompatability() throws Exception {
- Set<String> c = new HashSet<String>();
- assertFalse(c instanceof SortedSet);
- c = Collections.checkedSet(c, String.class);
- SerializationTester.assertCompabilityEquals(c, "/serialization/org/apache/harmony/luni/tests/java/util/Collections_CheckedSet.golden.ser");
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void test_checkedMapSerializationCompatability() throws Exception {
- Map<String, String> c = new HashMap<String, String>();
- assertFalse(c instanceof SortedMap);
- c = Collections.checkedMap(c, String.class, String.class);
- SerializationTester.assertCompabilityEquals(c, "/serialization/org/apache/harmony/luni/tests/java/util/Collections_CheckedMap.golden.ser");
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void test_checkedSortedSetSerializationCompatability() throws Exception {
- SortedSet<String> c = new TreeSet<String>();
- c = Collections.checkedSortedSet(c, String.class);
- SerializationTester.assertCompabilityEquals(c, "/serialization/org/apache/harmony/luni/tests/java/util/Collections_CheckedSortedSet.golden.ser");
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void test_checkedSortedMapSerializationCompatability() throws Exception {
- SortedMap<String, String> c = new TreeMap<String, String>();
- c = Collections.checkedSortedMap(c, String.class, String.class);
- SerializationTester.assertCompabilityEquals(c, "/serialization/org/apache/harmony/luni/tests/java/util/Collections_CheckedSortedMap.golden.ser");
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkedCollection",
- args = {java.util.Collection.class, java.lang.Class.class}
- )
- public void test_checkedCollectionLjava_util_CollectionLjava_lang_Class() {
- ArrayList al = new ArrayList<Integer>();
-
- Collection c = Collections.checkedCollection(al, Integer.class);
-
- c.add(new Integer(1));
-
- try {
- c.add(new Double(3.14));
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkedList",
- args = {java.util.List.class, java.lang.Class.class}
- )
- public void test_checkedListLjava_util_ListLjava_lang_Class() {
- ArrayList al = new ArrayList<Integer>();
-
- List l = Collections.checkedList(al, Integer.class);
-
- l.add(new Integer(1));
-
- try {
- l.add(new Double(3.14));
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkedMap",
- args = {java.util.Map.class, java.lang.Class.class, java.lang.Class.class}
- )
- public void test_checkedMapLjava_util_MapLjava_lang_ClassLjava_lang_Class() {
- HashMap hm = new HashMap<Integer, String>();
-
- Map m = Collections.checkedMap(hm, Integer.class, String.class);
-
- m.put(1, "one");
- m.put(2, "two");
-
- try {
- m.put("wron key", null);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- try {
- m.put(3, new Double(3.14));
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkedSet",
- args = {java.util.Set.class, java.lang.Class.class}
- )
- public void test_checkedSetLjava_util_SetLjava_lang_Class() {
- HashSet hs = new HashSet<Integer>();
-
- Set s = Collections.checkedSet(hs, Integer.class);
-
- s.add(new Integer(1));
-
- try {
- s.add(new Double(3.14));
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkedSortedMap",
- args = {java.util.SortedMap.class, java.lang.Class.class, java.lang.Class.class}
- )
- public void test_checkedSortedMapLjava_util_SortedMapLjava_lang_ClassLjava_lang_Class() {
- TreeMap tm = new TreeMap<Integer, String>();
-
- SortedMap sm = Collections.checkedSortedMap(tm, Integer.class, String.class);
-
- sm.put(1, "one");
- sm.put(2, "two");
-
- try {
- sm.put("wron key", null);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- try {
- sm.put(3, new Double(3.14));
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkedSortedSet",
- args = {java.util.SortedSet.class, java.lang.Class.class}
- )
- public void test_checkedSortedSetLjava_util_SortedSetLjava_lang_Class() {
- TreeSet ts = new TreeSet<Integer>();
-
- SortedSet ss = Collections.checkedSortedSet(ts, Integer.class);
-
- ss.add(new Integer(1));
-
- try {
- ss.add(new Double(3.14));
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "emptyList",
- args = {}
- )
- public void test_emptyList() {
- List<String> ls = Collections.emptyList();
- List<Integer> li = Collections.emptyList();
-
- assertTrue(ls.equals(li));
- assertTrue(li.equals(Collections.EMPTY_LIST));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "emptyMap",
- args = {}
- )
- public void test_emptyMap() {
- Map<Integer, String> mis = Collections.emptyMap();
- Map<String, Integer> msi = Collections.emptyMap();
-
- assertTrue(mis.equals(msi));
- assertTrue(msi.equals(Collections.EMPTY_MAP));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "emptySet",
- args = {}
- )
- public void test_emptySet() {
- Set<String> ss = Collections.emptySet();
- Set<Integer> si = Collections.emptySet();
-
- assertTrue(ss.equals(si));
- assertTrue(si.equals(Collections.EMPTY_SET));
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/DateTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/DateTest.java
deleted file mode 100644
index cb4097b..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/DateTest.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/* 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.Date;
-
-@TestTargetClass(Date.class)
-public class DateTest extends TestCase {
-
- /**
- * @tests java.util.Date#parse(String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Special regression test. Doesn't verify all cases according to the specification.",
- method = "parse",
- args = {java.lang.String.class}
- )
- @SuppressWarnings("deprecation")
- public void test_parseLjava_lang_String() {
- // Regression for HARMONY-102
- assertEquals("Assert 0: parse failure",
- -5400000, Date.parse("Sat, 1 Jan 1970 +0130 00:00:00"));
- assertEquals("Assert 1: parse failure",
- 858600000, Date.parse("00:00:00 GMT +0130 Sat, 11 Jan 1970"));
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/DictionaryTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/DictionaryTest.java
deleted file mode 100644
index 9b30e45..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/DictionaryTest.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.Date;
-import java.util.Dictionary;
-import java.util.Enumeration;
-
-@TestTargetClass(Dictionary.class)
-public class DictionaryTest extends TestCase {
-
- class Mock_Dictionary extends Dictionary {
-
- @Override
- public Enumeration elements() {
- return null;
- }
-
- @Override
- public Object get(Object arg0) {
- return null;
- }
-
- @Override
- public boolean isEmpty() {
- return false;
- }
-
- @Override
- public Enumeration keys() {
- return null;
- }
-
- @Override
- public Object put(Object arg0, Object arg1) {
- return null;
- }
-
- @Override
- public Object remove(Object arg0) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Dictionary",
- args = {}
- )
- public void testDictionary() {
- Dictionary md = new Mock_Dictionary();
- assertNotNull(md);
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/DuplicateFormatFlagsExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/DuplicateFormatFlagsExceptionTest.java
deleted file mode 100644
index e700fff..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/DuplicateFormatFlagsExceptionTest.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/* 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.Serializable;
-import java.util.DuplicateFormatFlagsException;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(DuplicateFormatFlagsException.class)
-public class DuplicateFormatFlagsExceptionTest extends TestCase {
-
- /**
- * @tests java.util.DuplicateFormatFlagsException#DuplicateFormatFlagsException(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "DuplicateFormatFlagsException",
- args = {java.lang.String.class}
- )
- public void test_duplicateFormatFlagsException() {
- try {
- new DuplicateFormatFlagsException(null);
- fail("should throw NullPointerException.");
- } catch (NullPointerException e) {
- // desired
- }
-
- assertNotNull(new DuplicateFormatFlagsException("String"));
- }
-
- /**
- * @tests java.util.DuplicateFormatFlagsException#getFlags()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFlags",
- args = {}
- )
- public void test_getFlags() {
- String strFlags = "MYTESTFLAGS";
- DuplicateFormatFlagsException duplicateFormatException = new DuplicateFormatFlagsException(
- strFlags);
- assertEquals(strFlags, duplicateFormatException.getFlags());
- }
-
- /**
- * @tests java.util.DuplicateFormatFlagsException#getMessage()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
- public void test_getMessage() {
- String strFlags = "MYTESTFLAGS";
- DuplicateFormatFlagsException duplicateFormatException = new DuplicateFormatFlagsException(
- strFlags);
- assertTrue(null != duplicateFormatException.getFlags());
-
- }
-
- // comparator for DuplicateFormatFlagsException objects
- private static final SerializableAssert exComparator = new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
-
- SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
- deserialized);
-
- DuplicateFormatFlagsException initEx = (DuplicateFormatFlagsException) initial;
- DuplicateFormatFlagsException desrEx = (DuplicateFormatFlagsException) deserialized;
-
- assertEquals("Flags", initEx.getFlags(), desrEx.getFlags());
- }
- };
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new DuplicateFormatFlagsException(
- "TESTDESC"), exComparator);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new DuplicateFormatFlagsException(
- "TESTDESC"), exComparator);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/EventListenerProxyTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/EventListenerProxyTest.java
deleted file mode 100644
index 3269941..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/EventListenerProxyTest.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.EventListener;
-import java.util.EventListenerProxy;
-
-@TestTargetClass(EventListenerProxy.class)
-public class EventListenerProxyTest extends TestCase {
-
- class Mock_EventListener implements EventListener {
-
- }
-
- class Mock_EventListenerProxy extends EventListenerProxy {
-
- public Mock_EventListenerProxy(EventListener listener) {
- super(listener);
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "EventListenerProxy",
- args = {java.util.EventListener.class}
- )
- public void testEventListenerProxy() {
- assertNotNull(new Mock_EventListenerProxy(null));
- assertNotNull(new Mock_EventListenerProxy(new Mock_EventListener()));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getListener",
- args = {}
- )
- public void testGetListener() {
- EventListener el = new Mock_EventListener();
- EventListenerProxy elp = new Mock_EventListenerProxy(el);
-
- assertSame(el, elp.getListener());
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatFlagsConversionMismatchExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatFlagsConversionMismatchExceptionTest.java
deleted file mode 100644
index a76ff54..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatFlagsConversionMismatchExceptionTest.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/* 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.Serializable;
-import java.util.FormatFlagsConversionMismatchException;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(FormatFlagsConversionMismatchException.class)
-public class FormatFlagsConversionMismatchExceptionTest extends TestCase {
-
- /**
- * @tests java.util.FormatFlagsConversionMismatchException#FormatFlagsConversionMismatchException(String,
- * char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "FormatFlagsConversionMismatchException",
- args = {java.lang.String.class, char.class}
- )
- public void test_formatFlagsConversionMismatchException() {
- try {
- new FormatFlagsConversionMismatchException(null, ' ');
- fail("should throw NullPointerException.");
- } catch (NullPointerException e) {
- // expected
- }
-
- assertNotNull(new FormatFlagsConversionMismatchException("String", ' '));
- }
-
- /**
- * @tests java.util.FormatFlagsConversionMismatchException#getFlags()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFlags",
- args = {}
- )
- public void test_getFlags() {
- String flags = "MYTESTFLAGS";
- char conversion = 'T';
- FormatFlagsConversionMismatchException formatFlagsConversionMismatchException = new FormatFlagsConversionMismatchException(
- flags, conversion);
- assertEquals(flags, formatFlagsConversionMismatchException.getFlags());
- }
-
- /**
- * @tests java.util.FormatFlagsConversionMismatchException#getConversion()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getConversion",
- args = {}
- )
- public void test_getConversion() {
- String flags = "MYTESTFLAGS";
- char conversion = 'T';
- FormatFlagsConversionMismatchException
- formatFlagsConversionMismatchException =
- new FormatFlagsConversionMismatchException(
- flags, conversion);
- assertEquals(conversion, formatFlagsConversionMismatchException
- .getConversion());
-
- }
-
- /**
- * @tests java.util.FormatFlagsConversionMismatchException#getMessage()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
- public void test_getMessage() {
- String flags = "MYTESTFLAGS";
- char conversion = 'T';
- FormatFlagsConversionMismatchException formatFlagsConversionMismatchException = new FormatFlagsConversionMismatchException(
- flags, conversion);
- assertTrue(null != formatFlagsConversionMismatchException.getMessage());
-
- }
-
- // comparator for FormatFlagsConversionMismatchException objects
- private static final SerializableAssert exComparator = new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
-
- SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
- deserialized);
-
- FormatFlagsConversionMismatchException initEx = (FormatFlagsConversionMismatchException) initial;
- FormatFlagsConversionMismatchException desrEx = (FormatFlagsConversionMismatchException) deserialized;
-
- assertEquals("Flags", initEx.getFlags(), desrEx.getFlags());
- assertEquals("Conversion", initEx.getConversion(), desrEx
- .getConversion());
- }
- };
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(
- new FormatFlagsConversionMismatchException("MYTESTFLAGS", 'T'),
- exComparator);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this,
- new FormatFlagsConversionMismatchException("MYTESTFLAGS", 'T'),
- exComparator);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormattableTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormattableTest.java
deleted file mode 100644
index 7dec15d..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormattableTest.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.Formattable;
-import java.util.Formatter;
-
-@TestTargetClass(Formattable.class)
-public class FormattableTest extends TestCase {
-
- class Mock_Formattable implements Formattable {
- boolean flag = false;
-
- public void formatTo(Formatter arg0, int arg1, int arg2, int arg3) {
- StringBuilder sb = new StringBuilder();
-
- if (arg3 == 1) {
- sb.append("single precision ");
- }
- if (arg3 == 2) {
- sb.append("double precision ");
- }
-
- arg0.format(sb.toString());
- flag = true;
- }
-
- public boolean isFormatToCalled() {
- return flag;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "formatTo",
- args = {java.util.Formatter.class, int.class, int.class, int.class}
- )
- public void testFormatTo() {
- Formatter fmt = new Formatter();
- Mock_Formattable mf = new Mock_Formattable();
-
- assertTrue(fmt.format("%1.1s", mf).toString().equals("single precision "));
- assertTrue(fmt.format("%2.1s", mf).toString().equals("single precision single precision "));
- assertTrue(fmt.format("%2.2s", mf).toString().equals("single precision single precision double precision "));
- assertTrue(mf.isFormatToCalled());
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatterClosedExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatterClosedExceptionTest.java
deleted file mode 100644
index 97273f4..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatterClosedExceptionTest.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/* 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.FormatterClosedException;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(FormatterClosedException.class)
-public class FormatterClosedExceptionTest extends TestCase {
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new FormatterClosedException());
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new FormatterClosedException());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "FormatterClosedException",
- args = {}
- )
- public void test_constructor() {
- assertNotNull(new FormatterClosedException());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatterTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatterTest.java
deleted file mode 100644
index 5a2ec99..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatterTest.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/* 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.Formatter.BigDecimalLayoutForm;
-
-@TestTargetClass(java.util. Formatter.BigDecimalLayoutForm.class)
-public class FormatterTest extends TestCase {
-
- /**
- * @tests java.util.Formatter.BigDecimalLayoutForm#values()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
- public void test_values() {
- BigDecimalLayoutForm[] vals = BigDecimalLayoutForm.values();
- assertEquals("Invalid length of enum values", 2, vals.length);
- assertEquals("Wrong scientific value in enum",
- BigDecimalLayoutForm.SCIENTIFIC, vals[0]);
- assertEquals("Wrong dec float value in enum",
- BigDecimalLayoutForm.DECIMAL_FLOAT, vals[1]);
- }
-
- /**
- * @tests java.util.Formatter.BigDecimalLayoutForm#valueOf(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {java.lang.String.class}
- )
- public void test_valueOfLjava_lang_String() {
- BigDecimalLayoutForm sci = BigDecimalLayoutForm.valueOf("SCIENTIFIC");
- assertEquals("Wrong scientific value in enum", BigDecimalLayoutForm.SCIENTIFIC, sci);
-
- BigDecimalLayoutForm decFloat = BigDecimalLayoutForm.valueOf("DECIMAL_FLOAT");
- assertEquals("Wrong dec float value from valueOf ", BigDecimalLayoutForm.DECIMAL_FLOAT, decFloat);
-
- try {
- decFloat = BigDecimalLayoutForm.valueOf("Wrong format");
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/HashMapTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/HashMapTest.java
deleted file mode 100644
index 56ba684..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/HashMapTest.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/* 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-@TestTargetClass(HashMap.class)
-public class HashMapTest extends TestCase {
- class SubMap<K, V> extends HashMap<K, V> {
- public SubMap(Map<? extends K, ? extends V> m) {
- super(m);
- }
-
- public V put(K key, V value) {
- throw new UnsupportedOperationException();
- }
- }
-
- /**
- * @tests java.util.HashMap#HashMap(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "NullPointerException is not verified.",
- method = "HashMap",
- args = {java.util.Map.class}
- )
- public void test_ConstructorLjava_util_Map() {
- HashMap map = new HashMap();
- map.put("a", "a");
- SubMap map2 = new SubMap(map);
- assertTrue(map2.containsKey("a"));
- assertTrue(map2.containsValue("a"));
- }
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
- HashMap<String, String> hm = new HashMap<String, String>();
- hm.put("key", "value");
-
- SerializationTest.verifySelf(hm);
-
- // regression for HARMONY-1583
- hm.put(null, "null");
- SerializationTest.verifySelf(hm);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
- HashMap<String, String> hm = new HashMap<String, String>();
- hm.put("key", "value");
-
- SerializationTest.verifyGolden(this, hm);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IdentityHashMapTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IdentityHashMapTest.java
deleted file mode 100644
index 43bb856..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IdentityHashMapTest.java
+++ /dev/null
@@ -1,511 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.Serializable;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.IdentityHashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(IdentityHashMap.class)
-public class IdentityHashMapTest extends junit.framework.TestCase {
-
- /**
- * @tests java.util.IdentityHashMap#containsKey(java.lang.Object)
- * @tests java.util.IdentityHashMap#containsValue(java.lang.Object)
- * @tests java.util.IdentityHashMap#put(java.lang.Object, java.lang.Object)
- * @tests java.util.IdentityHashMap#get(java.lang.Object)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks null as a parameter.",
- method = "containsKey",
- args = {java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks null as a parameter.",
- method = "containsValue",
- args = {java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks null as a parameter.",
- method = "put",
- args = {java.lang.Object.class, java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks null as a parameter.",
- method = "get",
- args = {java.lang.Object.class}
- )
- })
- public void test_null_Keys_and_Values() {
- // tests with null keys and values
- IdentityHashMap map = new IdentityHashMap();
- Object result;
-
- // null key and null value
- result = map.put(null, null);
- assertTrue("testA can not find null key", map.containsKey(null));
- assertTrue("testA can not find null value", map.containsValue(null));
- assertNull("testA can not get null value for null key",
- map.get(null));
- assertNull("testA put returned wrong value", result);
-
- // null value
- String value = "a value";
- result = map.put(null, value);
- assertTrue("testB can not find null key", map.containsKey(null));
- assertTrue("testB can not find a value with null key", map
- .containsValue(value));
- assertTrue("testB can not get value for null key",
- map.get(null) == value);
- assertNull("testB put returned wrong value", result);
-
- // a null key
- String key = "a key";
- result = map.put(key, null);
- assertTrue("testC can not find a key with null value", map
- .containsKey(key));
- assertTrue("testC can not find null value", map.containsValue(null));
- assertNull("testC can not get null value for key", map.get(key));
- assertNull("testC put returned wrong value", result);
-
- // another null key
- String anothervalue = "another value";
- result = map.put(null, anothervalue);
- assertTrue("testD can not find null key", map.containsKey(null));
- assertTrue("testD can not find a value with null key", map
- .containsValue(anothervalue));
- assertTrue("testD can not get value for null key",
- map.get(null) == anothervalue);
- assertTrue("testD put returned wrong value", result == value);
-
- // remove a null key
- result = map.remove(null);
- assertTrue("testE remove returned wrong value", result == anothervalue);
- assertTrue("testE should not find null key", !map.containsKey(null));
- assertTrue("testE should not find a value with null key", !map
- .containsValue(anothervalue));
- assertNull("testE should not get value for null key",
- map.get(null));
- }
-
- /**
- * @tests java.util.IdentityHashMap#put(java.lang.Object, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks null as a parameter.",
- method = "put",
- args = {java.lang.Object.class, java.lang.Object.class}
- )
- public void test_putLjava_lang_ObjectLjava_lang_Object() {
- IdentityHashMap<Object, Object> map = new IdentityHashMap<Object, Object>();
-
- // Test null as a key.
- Object value = "Some value";
- map.put(null, value);
- assertSame("Assert 0: Failure getting null key", value, map.get(null));
-
- // Test null as a value
- Object key = "Some key";
- map.put(key, null);
- assertNull("Assert 1: Failure getting null value", map.get(key));
- }
-
- /**
- * @tests java.util.IdentityHashMap#remove(java.lang.Object)
- * @tests java.util.IdentityHashMap#keySet()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify removed value.",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_remove() {
- IdentityHashMap map = new IdentityHashMap();
- map.put(null, null);
- map.put("key1", "value1");
- map.put("key2", "value2");
- map.remove("key1");
-
- assertTrue("Did not remove key1", !map.containsKey("key1"));
- assertTrue("Did not remove the value for key1", !map
- .containsValue("value1"));
-
- assertTrue("Modified key2", map.get("key2") != null
- && map.get("key2") == "value2");
- assertNull("Modified null entry", map.get(null));
- }
-
- /**
- * @tests java.util.IdentityHashMapTest#remove(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test.",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_removeLjava_lang_Object() {
- // Regression for HARMONY-37
- IdentityHashMap<String, String> hashMap = new IdentityHashMap<String, String>();
- hashMap.remove("absent");
- assertEquals("Assert 0: Size is incorrect", 0, hashMap.size());
-
- hashMap.put("key", "value");
- hashMap.remove("key");
- assertEquals("Assert 1: After removing non-null element size is incorrect", 0, hashMap.size());
-
- hashMap.put(null, null);
- assertEquals("Assert 2: adding literal null failed", 1, hashMap.size());
- hashMap.remove(null);
- assertEquals("Assert 3: After removing null element size is incorrect", 0, hashMap.size());
- }
-
- /**
- * @tests java.util.IdentityHashMap#entrySet()
- * @tests java.util.IdentityHashMap#keySet()
- * @tests java.util.IdentityHashMap#values()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "keySet",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "entrySet",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
- })
- public void test_sets() {
- // tests with null keys and values
- IdentityHashMap map = new IdentityHashMap();
-
- // null key and null value
- map.put("key", "value");
- map.put(null, null);
- map.put("a key", null);
- map.put("another key", null);
-
- Set keyset = map.keySet();
- Collection valueset = map.values();
- Set entries = map.entrySet();
- Iterator it = entries.iterator();
- while (it.hasNext()) {
- Map.Entry entry = (Map.Entry) it.next();
- assertTrue("EntrySetIterator can not find entry ", entries
- .contains(entry));
-
- assertTrue("entry key not found in map", map.containsKey(entry
- .getKey()));
- assertTrue("entry value not found in map", map.containsValue(entry
- .getValue()));
-
- assertTrue("entry key not found in the keyset", keyset
- .contains(entry.getKey()));
- assertTrue("entry value not found in the valueset", valueset
- .contains(entry.getValue()));
- }
- }
-
- /**
- * @tests java.util.IdentityHashMap#entrySet()
- * @tests java.util.IdentityHashMap#remove(java.lang.Object)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies positive functionality. Doesn't verify that remove method returns null if there was no entry for key.",
- method = "entrySet",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies positive functionality. Doesn't verify that remove method returns null if there was no entry for key.",
- method = "remove",
- args = {java.lang.Object.class}
- )
- })
- public void test_entrySet_removeAll() {
- IdentityHashMap map = new IdentityHashMap();
- for (int i = 0; i < 1000; i++) {
- map.put(new Integer(i), new Integer(i));
- }
- Set set = map.entrySet();
-
- set.removeAll(set);
- assertEquals("did not remove all elements in the map", 0, map.size());
- assertTrue("did not remove all elements in the entryset", set.isEmpty());
-
- Iterator it = set.iterator();
- assertTrue("entrySet iterator still has elements", !it.hasNext());
- }
-
- /**
- * @tests java.util.IdentityHashMap#keySet()
- * @tests java.util.IdentityHashMap#clear()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_keySet_clear() {
- IdentityHashMap map = new IdentityHashMap();
- for (int i = 0; i < 1000; i++) {
- map.put(new Integer(i), new Integer(i));
- }
- Set set = map.keySet();
- set.clear();
-
- assertEquals("did not remove all elements in the map", 0, map.size());
- assertTrue("did not remove all elements in the keyset", set.isEmpty());
-
- Iterator it = set.iterator();
- assertTrue("keySet iterator still has elements", !it.hasNext());
- }
-
- /**
- * @tests java.util.IdentityHashMap#values()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
- public void test_values() {
-
- IdentityHashMap map = new IdentityHashMap();
- for (int i = 0; i < 10; i++) {
- map.put(new Integer(i), new Integer(i));
- }
-
- Integer key = new Integer(20);
- Integer value = new Integer(40);
- map.put(key, value);
-
- Collection vals = map.values();
- boolean result = vals.remove(key);
- assertTrue("removed entries incorrectly", map.size() == 11 && !result);
- assertTrue("removed key incorrectly", map.containsKey(key));
- assertTrue("removed value incorrectly", map.containsValue(value));
-
- result = vals.remove(value);
- assertTrue("Did not remove entry as expected", map.size() == 10
- && result);
- assertTrue("Did not remove key as expected", !map.containsKey(key));
- assertTrue("Did not remove value as expected", !map
- .containsValue(value));
-
- // put an equivalent key to a value
- key = new Integer(1);
- value = new Integer(100);
- map.put(key, value);
-
- result = vals.remove(key);
- assertTrue("TestB. removed entries incorrectly", map.size() == 11
- && !result);
- assertTrue("TestB. removed key incorrectly", map.containsKey(key));
- assertTrue("TestB. removed value incorrectly", map.containsValue(value));
-
- result = vals.remove(value);
- assertTrue("TestB. Did not remove entry as expected", map.size() == 10
- && result);
- assertTrue("TestB. Did not remove key as expected", !map
- .containsKey(key));
- assertTrue("TestB. Did not remove value as expected", !map
- .containsValue(value));
-
- vals.clear();
- assertEquals("Did not remove all entries as expected", 0, map.size());
- }
-
- /**
- * @tests java.util.IdentityHashMap#keySet()
- * @tests java.util.IdentityHashMap#remove(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "keySet",
- args = {}
- )
- public void test_keySet_removeAll() {
- IdentityHashMap map = new IdentityHashMap();
- for (int i = 0; i < 1000; i++) {
- map.put(new Integer(i), new Integer(i));
- }
- Set set = map.keySet();
- set.removeAll(set);
-
- assertEquals("did not remove all elements in the map", 0, map.size());
- assertTrue("did not remove all elements in the keyset", set.isEmpty());
-
- Iterator it = set.iterator();
- assertTrue("keySet iterator still has elements", !it.hasNext());
- }
-
- /**
- * @tests java.util.IdentityHashMap#keySet()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "keySet",
- args = {}
- )
- public void test_keySet_retainAll() {
- IdentityHashMap map = new IdentityHashMap();
- for (int i = 0; i < 1000; i++) {
- map.put(new Integer(i), new Integer(i));
- }
- Set set = map.keySet();
-
- // retain all the elements
- boolean result = set.retainAll(set);
- assertTrue("retain all should return false", !result);
- assertEquals("did not retain all", 1000, set.size());
-
- // send empty set to retainAll
- result = set.retainAll(new TreeSet());
- assertTrue("retain all should return true", result);
- assertEquals("did not remove all elements in the map", 0, map.size());
- assertTrue("did not remove all elements in the keyset", set.isEmpty());
-
- Iterator it = set.iterator();
- assertTrue("keySet iterator still has elements", !it.hasNext());
- }
-
- /**
- * @tests java.util.IdentityHashMap#keySet()
- * @tests java.util.IdentityHashMap#remove(java.lang.Object)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "keySet",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "remove",
- args = {java.lang.Object.class}
- )
- })
- public void test_keyset_remove() {
- IdentityHashMap map = new IdentityHashMap();
-
- Integer key = new Integer(21);
-
- map.put(new Integer(1), null);
- map.put(new Integer(11), null);
- map.put(key, null);
- map.put(new Integer(31), null);
- map.put(new Integer(41), null);
- map.put(new Integer(51), null);
- map.put(new Integer(61), null);
- map.put(new Integer(71), null);
- map.put(new Integer(81), null);
- map.put(new Integer(91), null);
-
- Set set = map.keySet();
-
- Set newset = new HashSet();
- Iterator it = set.iterator();
- while (it.hasNext()) {
- Object element = it.next();
- if (element == key) {
- it.remove();
- } else
- newset.add(element);
- }
- int size = newset.size();
- assertTrue("keyset and newset don't have same size",
- newset.size() == size);
- assertTrue("element is in newset ", !newset.contains(key));
- assertTrue("element not removed from keyset", !set.contains(key));
- assertTrue("element not removed from map", !map.containsKey(key));
-
- assertTrue("newset and keyset do not have same elements 1", newset
- .equals(set));
- assertTrue("newset and keyset do not have same elements 2", set
- .equals(newset));
- }
-
- // comparator for IdentityHashMap objects
- private static final SerializableAssert COMPARATOR = new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
-
- IdentityHashMap init = (IdentityHashMap) initial;
- IdentityHashMap desr = (IdentityHashMap) deserialized;
-
- assertEquals("Size", init.size(), desr.size());
- }
- };
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
- IdentityHashMap<String, String> identityHashMap = new IdentityHashMap<String, String>();
- identityHashMap.put("key1", "value1");
- identityHashMap.put("key2", "value2");
- identityHashMap.put("key3", "value3");
-
- SerializationTest.verifyGolden(this, identityHashMap, COMPARATOR);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatCodePointExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatCodePointExceptionTest.java
deleted file mode 100644
index 602d1db..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatCodePointExceptionTest.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/* 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.Serializable;
-import java.util.IllegalFormatCodePointException;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(IllegalFormatCodePointException.class)
-public class IllegalFormatCodePointExceptionTest extends TestCase {
-
- /**
- * @tests java.util.IllegalFormatCodePointException.IllegalFormatCodePointException(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalFormatCodePointException",
- args = {int.class}
- )
- public void test_illegalFormatCodePointException() {
- IllegalFormatCodePointException illegalFormatCodePointException = new IllegalFormatCodePointException(
- -1);
- assertTrue(null != illegalFormatCodePointException);
- }
-
- /**
- * @tests java.util.IllegalFormatCodePointException.getCodePoint()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCodePoint",
- args = {}
- )
- public void test_getCodePoint() {
- int codePoint = 12345;
- IllegalFormatCodePointException illegalFormatCodePointException = new IllegalFormatCodePointException(
- codePoint);
- assertEquals(codePoint, illegalFormatCodePointException.getCodePoint());
- }
-
- /**
- * @tests java.util.IllegalFormatCodePointException.getMessage()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
- public void test_getMessage() {
- int codePoint = 12345;
- IllegalFormatCodePointException illegalFormatCodePointException = new IllegalFormatCodePointException(
- codePoint);
- assertTrue(null != illegalFormatCodePointException.getMessage());
- }
-
- // comparator for IllegalFormatCodePointException objects
- private static final SerializableAssert exComparator = new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
-
- SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
- deserialized);
-
- IllegalFormatCodePointException initEx = (IllegalFormatCodePointException) initial;
- IllegalFormatCodePointException desrEx = (IllegalFormatCodePointException) deserialized;
-
- assertEquals("CodePoint", initEx.getCodePoint(), desrEx
- .getCodePoint());
- }
- };
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(
- new IllegalFormatCodePointException(12345), exComparator);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this,
- new IllegalFormatCodePointException(12345), exComparator);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatConversionExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatConversionExceptionTest.java
deleted file mode 100644
index 22a845d..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatConversionExceptionTest.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/* 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.Serializable;
-import java.util.IllegalFormatConversionException;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(IllegalFormatConversionException.class)
-public class IllegalFormatConversionExceptionTest extends TestCase {
-
- /**
- * @tests java.util.IllegalFormatConversionException#IllegalFormatConversionException(char,
- * Class)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalFormatConversionException",
- args = {char.class, java.lang.Class.class}
- )
- public void test_illegalFormatConversionException() {
- try {
- new IllegalFormatConversionException(' ', null);
- fail("should throw NullPointerExcetpion.");
- } catch (NullPointerException e) {
- // desired
- }
-
- assertNotNull(new IllegalFormatConversionException(' ', String.class));
- }
-
- /**
- * @tests java.util.IllegalFormatConversionException#getArgumentClass()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getArgumentClass",
- args = {}
- )
- public void test_getArgumentClass() {
- char c = '*';
- Class<String> argClass = String.class;
- IllegalFormatConversionException illegalFormatConversionException = new IllegalFormatConversionException(
- c, argClass);
- assertEquals(argClass, illegalFormatConversionException
- .getArgumentClass());
-
- }
-
- /**
- * @tests java.util.IllegalFormatConversionException#getConversion()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getConversion",
- args = {}
- )
- public void test_getConversion() {
- char c = '*';
- Class<String> argClass = String.class;
- IllegalFormatConversionException illegalFormatConversionException = new IllegalFormatConversionException(
- c, argClass);
- assertEquals(c, illegalFormatConversionException.getConversion());
-
- }
-
- /**
- * @tests java.util.IllegalFormatConversionException#getMessage()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
- public void test_getMessage() {
- char c = '*';
- Class<String> argClass = String.class;
- IllegalFormatConversionException illegalFormatConversionException = new IllegalFormatConversionException(
- c, argClass);
- assertTrue(null != illegalFormatConversionException.getMessage());
-
- }
-
- // comparator for IllegalFormatConversionException objects
- private static final SerializableAssert exComparator = new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
-
- SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
- deserialized);
-
- IllegalFormatConversionException initEx = (IllegalFormatConversionException) initial;
- IllegalFormatConversionException desrEx = (IllegalFormatConversionException) deserialized;
-
- assertEquals("ArgumentClass", initEx.getArgumentClass(), desrEx
- .getArgumentClass());
- assertEquals("Conversion", initEx.getConversion(), desrEx
- .getConversion());
- }
- };
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new IllegalFormatConversionException('*',
- String.class), exComparator);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this,
- new IllegalFormatConversionException('*', String.class),
- exComparator);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatFlagsExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatFlagsExceptionTest.java
deleted file mode 100644
index 8ae825c..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatFlagsExceptionTest.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/* 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.Serializable;
-import java.util.IllegalFormatFlagsException;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(IllegalFormatFlagsException.class)
-public class IllegalFormatFlagsExceptionTest extends TestCase {
-
- /**
- * @tests java.util.IllegalFormatFlagsException#IllegalFormatFlagsException(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalFormatFlagsException",
- args = {java.lang.String.class}
- )
- public void test_illegalFormatFlagsException() {
- try {
- new IllegalFormatFlagsException(null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- assertNotNull(new IllegalFormatFlagsException("String"));
- }
-
- /**
- * @tests java.util.IllegalFormatFlagsException.getFlags()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFlags",
- args = {}
- )
- public void test_getFlags() {
- String flags = "TESTFLAGS";
- IllegalFormatFlagsException illegalFormatFlagsException = new IllegalFormatFlagsException(
- flags);
- assertEquals(flags, illegalFormatFlagsException.getFlags());
- }
-
- /**
- * @tests java.util.IllegalFormatFlagsException.getMessage()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
- public void test_getMessage() {
- String flags = "TESTFLAGS";
- IllegalFormatFlagsException illegalFormatFlagsException = new IllegalFormatFlagsException(
- flags);
- assertTrue(null != illegalFormatFlagsException.getMessage());
-
- }
-
- // comparator for IllegalFormatFlagsException objects
- private static final SerializableAssert exComparator = new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
-
- SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
- deserialized);
-
- IllegalFormatFlagsException initEx = (IllegalFormatFlagsException) initial;
- IllegalFormatFlagsException desrEx = (IllegalFormatFlagsException) deserialized;
-
- assertEquals("Flags", initEx.getFlags(), desrEx.getFlags());
- }
- };
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new IllegalFormatFlagsException(
- "TESTFLAGS"), exComparator);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new IllegalFormatFlagsException(
- "TESTFLAGS"), exComparator);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatPrecisionExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatPrecisionExceptionTest.java
deleted file mode 100644
index 823473e..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatPrecisionExceptionTest.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/* 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.Serializable;
-import java.util.IllegalFormatPrecisionException;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(IllegalFormatPrecisionException.class)
-public class IllegalFormatPrecisionExceptionTest extends TestCase {
-
- /**
- * @tests java.util.IllegalFormatPrecisionException#IllegalFormatPrecisionException(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalFormatPrecisionException",
- args = {int.class}
- )
- public void test_illegalFormatPrecisionException() {
- IllegalFormatPrecisionException illegalFormatPrecisionException = new IllegalFormatPrecisionException(
- Integer.MIN_VALUE);
- assertEquals(Integer.MIN_VALUE, illegalFormatPrecisionException
- .getPrecision());
- }
-
- /**
- * @tests java.util.IllegalFormatPrecisionException#getPrecision()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPrecision",
- args = {}
- )
- public void test_getPrecision() {
- int precision = 12345;
- IllegalFormatPrecisionException illegalFormatPrecisionException = new IllegalFormatPrecisionException(
- precision);
- assertEquals(precision, illegalFormatPrecisionException.getPrecision());
- }
-
- /**
- * @tests method for 'java.util.IllegalFormatPrecisionException#getMessage()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
- public void test_getMessage() {
- int precision = 12345;
- IllegalFormatPrecisionException illegalFormatPrecisionException = new IllegalFormatPrecisionException(
- precision);
- assertTrue(null != illegalFormatPrecisionException.getMessage());
-
- }
-
- // comparator for IllegalFormatPrecisionException objects
- private static final SerializableAssert exComparator = new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
-
- SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
- deserialized);
-
- IllegalFormatPrecisionException initEx = (IllegalFormatPrecisionException) initial;
- IllegalFormatPrecisionException desrEx = (IllegalFormatPrecisionException) deserialized;
-
- assertEquals("Precision", initEx.getPrecision(), desrEx
- .getPrecision());
- }
- };
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(
- new IllegalFormatPrecisionException(12345), exComparator);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this,
- new IllegalFormatPrecisionException(12345), exComparator);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatWidthExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatWidthExceptionTest.java
deleted file mode 100644
index 6885a4e..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatWidthExceptionTest.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/* 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.Serializable;
-import java.util.IllegalFormatWidthException;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(IllegalFormatWidthException.class)
-public class IllegalFormatWidthExceptionTest extends TestCase {
-
- /**
- * @tests java.util.IllegalFormatWidthException#IllegalFormatWidthException(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IllegalFormatWidthException",
- args = {int.class}
- )
- public void test_illegalFormatWidthException() {
- int width = Integer.MAX_VALUE;
- IllegalFormatWidthException illegalFormatWidthException = new IllegalFormatWidthException(
- width);
- assertEquals(width, illegalFormatWidthException.getWidth());
-
- }
-
- /**
- * @tests java.util.IllegalFormatWidthException#getWidth()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getWidth",
- args = {}
- )
- public void test_getWidth() {
- int width = 12345;
- IllegalFormatWidthException illegalFormatWidthException = new IllegalFormatWidthException(
- width);
- assertEquals(width, illegalFormatWidthException.getWidth());
-
- }
-
- /**
- * @tests java.util.IllegalFormatWidthException#getMessage()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
- public void test_getMessage() {
- int width = 12345;
- IllegalFormatWidthException illegalFormatWidthException = new IllegalFormatWidthException(
- width);
- assertTrue(null != illegalFormatWidthException.getMessage());
-
- }
-
- // comparator for IllegalFormatWidthException objects
- private static final SerializableAssert exComparator = new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
-
- SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
- deserialized);
-
- IllegalFormatWidthException initEx = (IllegalFormatWidthException) initial;
- IllegalFormatWidthException desrEx = (IllegalFormatWidthException) deserialized;
-
- assertEquals("Width", initEx.getWidth(), desrEx.getWidth());
- }
- };
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new IllegalFormatWidthException(12345),
- exComparator);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new IllegalFormatWidthException(
- 12345), exComparator);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/InputMismatchExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/InputMismatchExceptionTest.java
deleted file mode 100644
index e14987e..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/InputMismatchExceptionTest.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/* 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.Serializable;
-import java.util.InputMismatchException;
-import java.util.NoSuchElementException;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-@TestTargetClass(InputMismatchException.class)
-public class InputMismatchExceptionTest extends TestCase {
-
- private static final String ERROR_MESSAGE = "for serialization test"; //$NON-NLS-1$
-
- /**
- * @tests java.util.InputMismatchException#InputMismatchException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InputMismatchException",
- args = {}
- )
- @SuppressWarnings("cast")
- public void test_Constructor() {
- InputMismatchException exception = new InputMismatchException();
- assertNotNull(exception);
- assertTrue(exception instanceof NoSuchElementException);
- assertTrue(exception instanceof Serializable);
- }
-
- /**
- * @tests java.util.InputMismatchException#InputMismatchException(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InputMismatchException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- InputMismatchException exception = new InputMismatchException(
- ERROR_MESSAGE);
- assertNotNull(exception);
- assertEquals(ERROR_MESSAGE, exception.getMessage());
- }
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new InputMismatchException(ERROR_MESSAGE));
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new InputMismatchException(
- ERROR_MESSAGE));
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/InvalidPropertiesFormatExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/InvalidPropertiesFormatExceptionTest.java
deleted file mode 100644
index 0996a24..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/InvalidPropertiesFormatExceptionTest.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.InvalidPropertiesFormatException;
-
-@TestTargetClass(InvalidPropertiesFormatException.class)
-public class InvalidPropertiesFormatExceptionTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InvalidPropertiesFormatException",
- args = {java.lang.Throwable.class}
- )
- public void testInvalidPropertiesFormatExceptionThrowable() {
- assertNotNull(new InvalidPropertiesFormatException(new Exception()));
- assertNotNull(new InvalidPropertiesFormatException((Throwable)null));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InvalidPropertiesFormatException",
- args = {java.lang.String.class}
- )
- public void testInvalidPropertiesFormatExceptionString() {
- assertNotNull(new InvalidPropertiesFormatException("String"));
- assertNotNull(new InvalidPropertiesFormatException((String)null));
- }
-
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/LinkedHashMapTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/LinkedHashMapTest.java
deleted file mode 100644
index e3e94d2..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/LinkedHashMapTest.java
+++ /dev/null
@@ -1,846 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.AbstractMap;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.ConcurrentModificationException;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
-import tests.support.Support_MapTest2;
-import tests.support.Support_UnmodifiableCollectionTest;
-
-/**
- * @tests java.util.LinkedHashMap
- */
-@TestTargetClass(LinkedHashMap.class)
-public class LinkedHashMapTest extends junit.framework.TestCase {
-
- LinkedHashMap hm;
-
- final static int hmSize = 1000;
-
- static Object[] objArray;
-
- static Object[] objArray2;
- {
- objArray = new Object[hmSize];
- objArray2 = new Object[hmSize];
- for (int i = 0; i < objArray.length; i++) {
- objArray[i] = new Integer(i);
- objArray2[i] = objArray[i].toString();
- }
- }
-
- static final class CacheMap extends LinkedHashMap {
- protected boolean removeEldestEntry(Map.Entry e) {
- return size() > 5;
- }
- }
-
- private static class MockMapNull extends AbstractMap {
- @Override
- public Set entrySet() {
- return null;
- }
-
- @Override
- public int size() {
- return 10;
- }
- }
-
- /**
- * @tests java.util.LinkedHashMap#LinkedHashMap()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "LinkedHashMap",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.LinkedHashMap()
- new Support_MapTest2(new LinkedHashMap()).runTest();
-
- LinkedHashMap hm2 = new LinkedHashMap();
- assertEquals("Created incorrect LinkedHashMap", 0, hm2.size());
- }
-
- /**
- * @tests java.util.LinkedHashMap#LinkedHashMap(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "LinkedHashMap",
- args = {int.class}
- )
- public void test_ConstructorI() {
- // Test for method java.util.LinkedHashMap(int)
- LinkedHashMap hm2 = new LinkedHashMap(5);
- assertEquals("Created incorrect LinkedHashMap", 0, hm2.size());
- try {
- new LinkedHashMap(-1);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- LinkedHashMap empty = new LinkedHashMap(0);
- assertNull("Empty LinkedHashMap access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
- }
-
- /**
- * @tests java.util.LinkedHashMap#LinkedHashMap(int, float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "LinkedHashMap",
- args = {int.class, float.class}
- )
- public void test_ConstructorIF() {
- // Test for method java.util.LinkedHashMap(int, float)
- LinkedHashMap hm2 = new LinkedHashMap(5, (float) 0.5);
- assertEquals("Created incorrect LinkedHashMap", 0, hm2.size());
- try {
- new LinkedHashMap(0, 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- LinkedHashMap empty = new LinkedHashMap(0, 0.75f);
- assertNull("Empty hashtable access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
- }
-
- /**
- * @tests java.util.LinkedHashMap#LinkedHashMap(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "LinkedHashMap",
- args = {java.util.Map.class}
- )
- public void test_ConstructorLjava_util_Map() {
- // Test for method java.util.LinkedHashMap(java.util.Map)
- Map myMap = new TreeMap();
- for (int counter = 0; counter < hmSize; counter++)
- myMap.put(objArray2[counter], objArray[counter]);
- LinkedHashMap hm2 = new LinkedHashMap(myMap);
- for (int counter = 0; counter < hmSize; counter++)
- assertTrue("Failed to construct correct LinkedHashMap", hm
- .get(objArray2[counter]) == hm2.get(objArray2[counter]));
-
- try {
- new LinkedHashMap(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.LinkedHashMap#get(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {java.lang.Object.class}
- )
- public void test_getLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.LinkedHashMap.get(java.lang.Object)
- assertNull("Get returned non-null for non existent key",
- hm.get("T"));
- hm.put("T", "HELLO");
- assertEquals("Get returned incorecct value for existing key", "HELLO", hm.get("T")
- );
-
- LinkedHashMap m = new LinkedHashMap();
- m.put(null, "test");
- assertEquals("Failed with null key", "test", m.get(null));
- assertNull("Failed with missing key matching null hash", m
- .get(new Integer(0)));
- }
-
- /**
- * @tests java.util.LinkedHashMap#put(java.lang.Object, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "put",
- args = {java.lang.Object.class, java.lang.Object.class}
- )
- public void test_putLjava_lang_ObjectLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.LinkedHashMap.put(java.lang.Object, java.lang.Object)
- hm.put("KEY", "VALUE");
- assertEquals("Failed to install key/value pair",
- "VALUE", hm.get("KEY"));
-
- LinkedHashMap m = new LinkedHashMap();
- m.put(new Short((short) 0), "short");
- m.put(null, "test");
- m.put(new Integer(0), "int");
- assertEquals("Failed adding to bucket containing null", "short", m.get(
- new Short((short) 0)));
- assertEquals("Failed adding to bucket containing null2", "int", m.get(
- new Integer(0)));
- }
-
- /**
- * @tests java.util.LinkedHashMap#putAll(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies only positive functionality.",
- method = "putAll",
- args = {java.util.Map.class}
- )
- public void test_putAllLjava_util_Map() {
- // Test for method void java.util.LinkedHashMap.putAll(java.util.Map)
- LinkedHashMap hm2 = new LinkedHashMap();
- hm2.putAll(hm);
- for (int i = 0; i < 1000; i++)
- assertTrue("Failed to clear all elements", hm2.get(
- new Integer(i).toString()).equals((new Integer(i))));
- }
-
- /**
- * @tests java.util.LinkedHashMap#putAll(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "putAll",
- args = {java.util.Map.class}
- )
- public void test_putAll_Ljava_util_Map_Null() {
- LinkedHashMap linkedHashMap = new LinkedHashMap();
- try {
- linkedHashMap.putAll(new MockMapNull());
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected.
- }
-
- try {
- linkedHashMap = new LinkedHashMap(new MockMapNull());
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected.
- }
- }
-
- /**
- * @tests java.util.LinkedHashMap#entrySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "entrySet",
- args = {}
- )
- public void test_entrySet() {
- // Test for method java.util.Set java.util.LinkedHashMap.entrySet()
- Set s = hm.entrySet();
- Iterator i = s.iterator();
- assertTrue("Returned set of incorrect size", hm.size() == s.size());
- while (i.hasNext()) {
- Map.Entry m = (Map.Entry) i.next();
- assertTrue("Returned incorrect entry set", hm.containsKey(m
- .getKey())
- && hm.containsValue(m.getValue()));
- }
- }
-
- /**
- * @tests java.util.LinkedHashMap#keySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "keySet",
- args = {}
- )
- public void test_keySet() {
- // Test for method java.util.Set java.util.LinkedHashMap.keySet()
- Set s = hm.keySet();
- assertTrue("Returned set of incorrect size()", s.size() == hm.size());
- for (int i = 0; i < objArray.length; i++)
- assertTrue("Returned set does not contain all keys", s
- .contains(objArray[i].toString()));
-
- LinkedHashMap m = new LinkedHashMap();
- m.put(null, "test");
- assertTrue("Failed with null key", m.keySet().contains(null));
- assertNull("Failed with null key", m.keySet().iterator().next());
-
- Map map = new LinkedHashMap(101);
- map.put(new Integer(1), "1");
- map.put(new Integer(102), "102");
- map.put(new Integer(203), "203");
- Iterator it = map.keySet().iterator();
- Integer remove1 = (Integer) it.next();
- it.hasNext();
- it.remove();
- Integer remove2 = (Integer) it.next();
- it.remove();
- ArrayList list = new ArrayList(Arrays.asList(new Integer[] {
- new Integer(1), new Integer(102), new Integer(203) }));
- list.remove(remove1);
- list.remove(remove2);
- assertTrue("Wrong result", it.next().equals(list.get(0)));
- assertEquals("Wrong size", 1, map.size());
- assertTrue("Wrong contents", map.keySet().iterator().next().equals(
- list.get(0)));
-
- Map map2 = new LinkedHashMap(101);
- map2.put(new Integer(1), "1");
- map2.put(new Integer(4), "4");
- Iterator it2 = map2.keySet().iterator();
- Integer remove3 = (Integer) it2.next();
- Integer next;
- if (remove3.intValue() == 1)
- next = new Integer(4);
- else
- next = new Integer(1);
- it2.hasNext();
- it2.remove();
- assertTrue("Wrong result 2", it2.next().equals(next));
- assertEquals("Wrong size 2", 1, map2.size());
- assertTrue("Wrong contents 2", map2.keySet().iterator().next().equals(
- next));
- }
-
- /**
- * @tests java.util.LinkedHashMap#values()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
- public void test_values() {
- // Test for method java.util.Collection java.util.LinkedHashMap.values()
- Collection c = hm.values();
- assertTrue("Returned collection of incorrect size()", c.size() == hm
- .size());
- for (int i = 0; i < objArray.length; i++)
- assertTrue("Returned collection does not contain all keys", c
- .contains(objArray[i]));
-
- LinkedHashMap myLinkedHashMap = new LinkedHashMap();
- for (int i = 0; i < 100; i++)
- myLinkedHashMap.put(objArray2[i], objArray[i]);
- Collection values = myLinkedHashMap.values();
- new Support_UnmodifiableCollectionTest(
- "Test Returned Collection From LinkedHashMap.values()", values)
- .runTest();
- values.remove(new Integer(0));
- assertTrue(
- "Removing from the values collection should remove from the original map",
- !myLinkedHashMap.containsValue(new Integer(0)));
-
- }
-
- /**
- * @tests java.util.LinkedHashMap#remove(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_removeLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.LinkedHashMap.remove(java.lang.Object)
- int size = hm.size();
- Integer y = new Integer(9);
- Integer x = ((Integer) hm.remove(y.toString()));
- assertTrue("Remove returned incorrect value", x.equals(new Integer(9)));
- assertNull("Failed to remove given key", hm.get(new Integer(9)));
- assertTrue("Failed to decrement size", hm.size() == (size - 1));
- assertNull("Remove of non-existent key returned non-null", hm
- .remove("LCLCLC"));
-
- LinkedHashMap m = new LinkedHashMap();
- m.put(null, "test");
- assertNull("Failed with same hash as null",
- m.remove(new Integer(0)));
- assertEquals("Failed with null key", "test", m.remove(null));
- }
-
- /**
- * @tests java.util.LinkedHashMap#clear()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- // Test for method void java.util.LinkedHashMap.clear()
- hm.clear();
- assertEquals("Clear failed to reset size", 0, hm.size());
- for (int i = 0; i < hmSize; i++)
- assertNull("Failed to clear all elements",
- hm.get(objArray2[i]));
-
- }
-
- /**
- * @tests java.util.LinkedHashMap#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- // Test for method java.lang.Object java.util.LinkedHashMap.clone()
- LinkedHashMap hm2 = (LinkedHashMap) hm.clone();
- assertTrue("Clone answered equivalent LinkedHashMap", hm2 != hm);
- for (int counter = 0; counter < hmSize; counter++)
- assertTrue("Clone answered unequal LinkedHashMap", hm
- .get(objArray2[counter]) == hm2.get(objArray2[counter]));
-
- LinkedHashMap map = new LinkedHashMap();
- map.put("key", "value");
- // get the keySet() and values() on the original Map
- Set keys = map.keySet();
- Collection values = map.values();
- assertEquals("values() does not work",
- "value", values.iterator().next());
- assertEquals("keySet() does not work",
- "key", keys.iterator().next());
- AbstractMap map2 = (AbstractMap) map.clone();
- map2.put("key", "value2");
- Collection values2 = map2.values();
- assertTrue("values() is identical", values2 != values);
-
- // values() and keySet() on the cloned() map should be different
- assertEquals("values() was not cloned",
- "value2", values2.iterator().next());
- map2.clear();
- map2.put("key2", "value3");
- Set key2 = map2.keySet();
- assertTrue("keySet() is identical", key2 != keys);
- assertEquals("keySet() was not cloned",
- "key2", key2.iterator().next());
- }
-
- /**
- * @tests java.util.LinkedHashMap#containsKey(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "containsKey",
- args = {java.lang.Object.class}
- )
- public void test_containsKeyLjava_lang_Object() {
- // Test for method boolean
- // java.util.LinkedHashMap.containsKey(java.lang.Object)
- assertTrue("Returned false for valid key", hm.containsKey(new Integer(
- 876).toString()));
- assertTrue("Returned true for invalid key", !hm.containsKey("KKDKDKD"));
-
- LinkedHashMap m = new LinkedHashMap();
- m.put(null, "test");
- assertTrue("Failed with null key", m.containsKey(null));
- assertTrue("Failed with missing key matching null hash", !m
- .containsKey(new Integer(0)));
- }
-
- /**
- * @tests java.util.LinkedHashMap#containsValue(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "containsValue",
- args = {java.lang.Object.class}
- )
- public void test_containsValueLjava_lang_Object() {
- // Test for method boolean
- // java.util.LinkedHashMap.containsValue(java.lang.Object)
- assertTrue("Returned false for valid value", hm
- .containsValue(new Integer(875)));
- assertTrue("Returned true for invalid valie", !hm
- .containsValue(new Integer(-9)));
- }
-
- /**
- * @tests java.util.LinkedHashMap#isEmpty()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isEmpty",
- args = {}
- )
- public void test_isEmpty() {
- // Test for method boolean java.util.LinkedHashMap.isEmpty()
- assertTrue("Returned false for new map", new LinkedHashMap().isEmpty());
- assertTrue("Returned true for non-empty", !hm.isEmpty());
- }
-
- /**
- * @tests java.util.LinkedHashMap#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- public void test_size() {
- // Test for method int java.util.LinkedHashMap.size()
- assertTrue("Returned incorrect size",
- hm.size() == (objArray.length + 2));
- }
-
- /**
- * @tests java.util.LinkedHashMap#entrySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "entrySet",
- args = {}
- )
- public void test_ordered_entrySet() {
- int i;
- int sz = 100;
- LinkedHashMap lhm = new LinkedHashMap();
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lhm.put(ii, ii.toString());
- }
-
- Set s1 = lhm.entrySet();
- Iterator it1 = s1.iterator();
- assertTrue("Returned set of incorrect size 1", lhm.size() == s1.size());
- for (i = 0; it1.hasNext(); i++) {
- Map.Entry m = (Map.Entry) it1.next();
- Integer jj = (Integer) m.getKey();
- assertTrue("Returned incorrect entry set 1", jj.intValue() == i);
- }
-
- LinkedHashMap lruhm = new LinkedHashMap(200, .75f, true);
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lruhm.put(ii, ii.toString());
- }
-
- Set s3 = lruhm.entrySet();
- Iterator it3 = s3.iterator();
- assertTrue("Returned set of incorrect size 2", lruhm.size() == s3
- .size());
- for (i = 0; i < sz && it3.hasNext(); i++) {
- Map.Entry m = (Map.Entry) it3.next();
- Integer jj = (Integer) m.getKey();
- assertTrue("Returned incorrect entry set 2", jj.intValue() == i);
- }
-
- /* fetch the even numbered entries to affect traversal order */
- int p = 0;
- for (i = 0; i < sz; i += 2) {
- String ii = (String) lruhm.get(new Integer(i));
- p = p + Integer.parseInt(ii);
- }
- assertEquals("invalid sum of even numbers", 2450, p);
-
- Set s2 = lruhm.entrySet();
- Iterator it2 = s2.iterator();
- assertTrue("Returned set of incorrect size 3", lruhm.size() == s2
- .size());
- for (i = 1; i < sz && it2.hasNext(); i += 2) {
- Map.Entry m = (Map.Entry) it2.next();
- Integer jj = (Integer) m.getKey();
- assertTrue("Returned incorrect entry set 3", jj.intValue() == i);
- }
- for (i = 0; i < sz && it2.hasNext(); i += 2) {
- Map.Entry m = (Map.Entry) it2.next();
- Integer jj = (Integer) m.getKey();
- assertTrue("Returned incorrect entry set 4", jj.intValue() == i);
- }
- assertTrue("Entries left to iterate on", !it2.hasNext());
- }
-
- /**
- * @tests java.util.LinkedHashMap#keySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "keySet",
- args = {}
- )
- public void test_ordered_keySet() {
- int i;
- int sz = 100;
- LinkedHashMap lhm = new LinkedHashMap();
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lhm.put(ii, ii.toString());
- }
-
- Set s1 = lhm.keySet();
- Iterator it1 = s1.iterator();
- assertTrue("Returned set of incorrect size", lhm.size() == s1.size());
- for (i = 0; it1.hasNext(); i++) {
- Integer jj = (Integer) it1.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i);
- }
-
- LinkedHashMap lruhm = new LinkedHashMap(200, .75f, true);
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lruhm.put(ii, ii.toString());
- }
-
- Set s3 = lruhm.keySet();
- Iterator it3 = s3.iterator();
- assertTrue("Returned set of incorrect size", lruhm.size() == s3.size());
- for (i = 0; i < sz && it3.hasNext(); i++) {
- Integer jj = (Integer) it3.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i);
- }
-
- /* fetch the even numbered entries to affect traversal order */
- int p = 0;
- for (i = 0; i < sz; i += 2) {
- String ii = (String) lruhm.get(new Integer(i));
- p = p + Integer.parseInt(ii);
- }
- assertEquals("invalid sum of even numbers", 2450, p);
-
- Set s2 = lruhm.keySet();
- Iterator it2 = s2.iterator();
- assertTrue("Returned set of incorrect size", lruhm.size() == s2.size());
- for (i = 1; i < sz && it2.hasNext(); i += 2) {
- Integer jj = (Integer) it2.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i);
- }
- for (i = 0; i < sz && it2.hasNext(); i += 2) {
- Integer jj = (Integer) it2.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i);
- }
- assertTrue("Entries left to iterate on", !it2.hasNext());
- }
-
- /**
- * @tests java.util.LinkedHashMap#values()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
- public void test_ordered_values() {
- int i;
- int sz = 100;
- LinkedHashMap lhm = new LinkedHashMap();
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lhm.put(ii, new Integer(i * 2));
- }
-
- Collection s1 = lhm.values();
- Iterator it1 = s1.iterator();
- assertTrue("Returned set of incorrect size 1", lhm.size() == s1.size());
- for (i = 0; it1.hasNext(); i++) {
- Integer jj = (Integer) it1.next();
- assertTrue("Returned incorrect entry set 1", jj.intValue() == i * 2);
- }
-
- LinkedHashMap lruhm = new LinkedHashMap(200, .75f, true);
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lruhm.put(ii, new Integer(i * 2));
- }
-
- Collection s3 = lruhm.values();
- Iterator it3 = s3.iterator();
- assertTrue("Returned set of incorrect size", lruhm.size() == s3.size());
- for (i = 0; i < sz && it3.hasNext(); i++) {
- Integer jj = (Integer) it3.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i * 2);
- }
-
- // fetch the even numbered entries to affect traversal order
- int p = 0;
- for (i = 0; i < sz; i += 2) {
- Integer ii = (Integer) lruhm.get(new Integer(i));
- p = p + ii.intValue();
- }
- assertTrue("invalid sum of even numbers", p == 2450 * 2);
-
- Collection s2 = lruhm.values();
- Iterator it2 = s2.iterator();
- assertTrue("Returned set of incorrect size", lruhm.size() == s2.size());
- for (i = 1; i < sz && it2.hasNext(); i += 2) {
- Integer jj = (Integer) it2.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i * 2);
- }
- for (i = 0; i < sz && it2.hasNext(); i += 2) {
- Integer jj = (Integer) it2.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i * 2);
- }
- assertTrue("Entries left to iterate on", !it2.hasNext());
- }
-
- /**
- * @tests java.util.LinkedHashMap#removeEldestEntry(java.util.Map$Entry)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify null as a parameter.",
- method = "removeEldestEntry",
- args = {java.util.Map.Entry.class}
- )
- public void test_remove_eldest() {
- int i;
- int sz = 10;
- CacheMap lhm = new CacheMap();
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lhm.put(ii, new Integer(i * 2));
- }
-
- Collection s1 = lhm.values();
- Iterator it1 = s1.iterator();
- assertTrue("Returned set of incorrect size 1", lhm.size() == s1.size());
- for (i = 5; it1.hasNext(); i++) {
- Integer jj = (Integer) it1.next();
- assertTrue("Returned incorrect entry set 1", jj.intValue() == i * 2);
- }
- assertTrue("Entries left in map", !it1.hasNext());
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "LinkedHashMap",
- args = {int.class, float.class, boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "put",
- args = {java.lang.Object.class, java.lang.Object.class}
- )
- })
- // BEGIN android-added
- public void testLinkedHashMap() {
- // we want to test the LinkedHashMap in access ordering mode.
- LinkedHashMap map = new LinkedHashMap<String, String>(10, 0.75f, true);
-
- map.put("key1", "value1");
- map.put("key2", "value2");
- map.put("key3", "value3");
-
- Iterator iterator = map.keySet().iterator();
- String id = (String) iterator.next();
- map.get(id);
- try {
- iterator.next();
- // A LinkedHashMap is supposed to throw this Exception when a
- // iterator.next() Operation takes place after a get
- // Operation. This is because the get Operation is considered
- // a structural modification if the LinkedHashMap is in
- // access order mode.
- fail("expected ConcurrentModificationException was not thrown.");
- } catch(ConcurrentModificationException e) {
- // expected
- }
-
- LinkedHashMap mapClone = (LinkedHashMap) map.clone();
-
- iterator = map.keySet().iterator();
- id = (String) iterator.next();
- mapClone.get(id);
- try {
- iterator.next();
- } catch(ConcurrentModificationException e) {
- fail("expected ConcurrentModificationException was not thrown.");
- }
-
- try {
- new LinkedHashMap<String, String>(-10, 0.75f, true);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new LinkedHashMap<String, String>(10, -0.75f, true);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
- // END android-added
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- hm = new LinkedHashMap();
- for (int i = 0; i < objArray.length; i++)
- hm.put(objArray2[i], objArray[i]);
- hm.put("test", null);
- hm.put(null, "test");
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ListIteratorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ListIteratorTest.java
deleted file mode 100644
index 522ff76..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ListIteratorTest.java
+++ /dev/null
@@ -1,313 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.LinkedList;
-import java.util.ListIterator;
-import java.util.NoSuchElementException;
-
-@TestTargetClass(ListIterator.class)
-public class ListIteratorTest extends TestCase {
-
- ListIterator<Integer> l = null;
-
- static Object[] objArray;
- {
- objArray = new Object[100];
- for (int i = 0; i < objArray.length; i++)
- objArray[i] = new Integer(i);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasNext",
- args = {}
- )
- public void testHasNext() {
- for (int i = 0; i < objArray.length; i++) {
- assertTrue(l.hasNext());
- l.next();
- }
- assertFalse(l.hasNext());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "next",
- args = {}
- )
- public void testNext() {
- for (int i = 0; i < objArray.length; i++) {
- assertTrue(objArray[i].equals(l.next()));
- }
-
- try {
- l.next();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- class Mock_ListIterator implements ListIterator {
- public void add(Object o) {
- if(((String) o).equals("Wrong element")) throw new IllegalArgumentException();
- if(o.getClass() == Double.class) throw new ClassCastException();
- throw new UnsupportedOperationException();
- }
-
- public boolean hasNext() {
- return false;
- }
-
- public boolean hasPrevious() {
- return false;
- }
-
- public Object next() {
- return null;
- }
-
- public int nextIndex() {
- return 0;
- }
-
- public Object previous() {
- return null;
- }
-
- public int previousIndex() {
- return 0;
- }
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
-
- public void set(Object o) {
- if(((String) o).equals("Wrong element")) throw new IllegalArgumentException();
- if(o.getClass() == Double.class) throw new ClassCastException();
- throw new UnsupportedOperationException();
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {}
- )
- public void testRemove() {
- try {
- l.remove();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- for (int i = 0; i < objArray.length; i++) {
- l.next();
- l.remove();
- assertFalse(l.hasPrevious());
- }
-
- try {
- l.remove();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
-
- Mock_ListIterator ml = new Mock_ListIterator();
- try {
- ml.remove();
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasPrevious",
- args = {}
- )
- public void testHasPrevious() {
- assertFalse(l.hasPrevious());
- for (int i = 0; i < objArray.length; i++) {
- l.next();
- assertTrue(l.hasPrevious());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "previous",
- args = {}
- )
- public void testPrevious() {
- try {
- l.previous();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- while(l.hasNext()) {
- l.next();
- }
-
- for (int i = objArray.length - 1; i > -1 ; i--) {
- assertTrue(objArray[i].equals(l.previous()));
- }
-
- try {
- l.previous();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextIndex",
- args = {}
- )
- public void testNextIndex() {
- for (int i = 0; i < objArray.length; i++) {
- assertTrue(objArray[i].equals(l.nextIndex()));
- l.next();
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "previousIndex",
- args = {}
- )
- public void testPreviousIndex() {
- for (int i = 0; i < objArray.length; i++) {
- assertTrue(objArray[i].equals(l.previousIndex() + 1));
- l.next();
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "set",
- args = {java.lang.Object.class}
- )
- public void testSet() {
- try {
- l.set(new Integer(1));
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
-
- for (int i = 0; i < objArray.length; i++) {
- l.next();
- l.set((Integer)objArray[objArray.length - i - 1]);
- }
-
- l.remove();
- try {
- l.set(new Integer(1));
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
-
- Mock_ListIterator ml = new Mock_ListIterator();
- ml.next();
- try {
- ml.set("Wrong element");
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- ml.set(new Double("3.14"));
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- try {
- ml.set("");
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "add",
- args = {java.lang.Object.class}
- )
- public void testAdd() {
- l.add(new Integer(33));
-
- Mock_ListIterator ml = new Mock_ListIterator();
- ml.next();
- try {
- ml.add("Wrong element");
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- ml.add(new Double("3.14"));
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- try {
- ml.add("");
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- protected void setUp() throws Exception {
- super.setUp();
- LinkedList ll = new LinkedList();
- for (int i = 0; i < objArray.length; i++) {
- ll.add(objArray[i]);
- }
- l = ll.listIterator();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/LocaleTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/LocaleTest.java
deleted file mode 100644
index 5acb81c..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/LocaleTest.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/* 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.Locale;
-
-@TestTargetClass(Locale.class)
-public class LocaleTest extends TestCase {
-
- /**
- * @tests java.util.Locale#getAvailableLocales()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAvailableLocales",
- args = {}
- )
- public void test_getAvailableLocales() {
- Locale[] locales = Locale.getAvailableLocales();
- // Assumes that there will be a decent number of locales
- // BEGIN android-changed
- // this assumption is wrong. Android has a reduced locale repository.
- // was >100, now it's >10
- assertTrue("Assert 0: Cannot find locales", locales.length > 10);
- // END android-changed
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/MapEntryTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/MapEntryTest.java
deleted file mode 100644
index 96b26e1..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/MapEntryTest.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-@TestTargetClass(Map.Entry.class)
-public class MapEntryTest extends TestCase {
- Map.Entry me = null;
- HashMap hm = null;
- Iterator i = null;
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getKey",
- args = {}
- )
- public void testGetKey() {
- assertTrue(hm.containsKey(me.getKey()));
- hm.clear();
- try {
- me.getKey();
- //expected
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getValue",
- args = {}
- )
- public void testGetValue() {
- assertTrue(hm.containsValue(me.getValue()));
- hm.clear();
- try {
- me.getValue();
- //expected
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- class Mock_HashMap extends HashMap {
- @Override
- public Object put(Object key, Object val) {
- if (val == null) throw new NullPointerException();
- if (val.getClass() == Double.class) throw new ClassCastException();
- if (((String)val).equals("Wrong element")) throw new IllegalArgumentException();
- throw new UnsupportedOperationException();
- }
-
- public Object fakePut(Object key, Object val) {
- return super.put(key, val);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "RI does not throw following exceptions: UnsupportedOperationException,ClassCastException, IllegalArgumentException and NullPointerException",
- method = "setValue",
- args = {java.lang.Object.class}
- )
- public void testSetValue() {
- Mock_HashMap mhm = new Mock_HashMap();
-
- mhm.fakePut(new Integer(1), "One");
- mhm.fakePut(new Integer(2), "Two");
-
- i = mhm.entrySet().iterator();
- me = (Map.Entry)i.next();
-
- me.setValue("Wrong element");
-
- hm.clear();
- try {
- me.setValue("");
- //expected
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void testEquals() {
- Map.Entry me1 = (Map.Entry)i.next();
- assertFalse(me.equals(me1));
- assertFalse(me.equals(this));
- me1 = me;
- assertTrue(me.equals(me1));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void testHashCode() {
- Map.Entry me1 = (Map.Entry)i.next();
- assertTrue(me.hashCode() != me1.hashCode());
- }
-
- protected void setUp() throws Exception {
- hm = new HashMap();
-
- hm.put(new Integer(1), "one");
- hm.put(new Integer(2), "two");
-
- i = hm.entrySet().iterator();
- me = (Map.Entry)i.next();
-
- super.setUp();
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/MissingFormatArgumentExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/MissingFormatArgumentExceptionTest.java
deleted file mode 100644
index d93b069..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/MissingFormatArgumentExceptionTest.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/* 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.Serializable;
-import java.util.MissingFormatArgumentException;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(MissingFormatArgumentException.class)
-public class MissingFormatArgumentExceptionTest extends TestCase {
-
- /**
- * @tests java.util.MissingFormatArgumentException#MissingFormatArgumentException(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "MissingFormatArgumentException",
- args = {java.lang.String.class}
- )
- public void test_missingFormatArgumentException() {
- assertNotNull(new MissingFormatArgumentException("String"));
-
- try {
- new MissingFormatArgumentException(null);
- fail("should throw NullPointerExcepiton.");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.MissingFormatArgumentException#getFormatSpecifier()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFormatSpecifier",
- args = {}
- )
- public void test_getFormatSpecifier() {
- String s = "MYTESTSTRING";
- MissingFormatArgumentException missingFormatArgumentException = new MissingFormatArgumentException(
- s);
- assertEquals(s, missingFormatArgumentException.getFormatSpecifier());
- }
-
- /**
- * @tests java.util.MissingFormatArgumentException#getMessage()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
- public void test_getMessage() {
- String s = "MYTESTSTRING";
- MissingFormatArgumentException missingFormatArgumentException = new MissingFormatArgumentException(
- s);
- assertTrue(null != missingFormatArgumentException.getMessage());
-
- }
-
- // comparator for comparing MissingFormatArgumentException objects
- private static final SerializableAssert exComparator = new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
-
- SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
- deserialized);
-
- MissingFormatArgumentException initEx = (MissingFormatArgumentException) initial;
- MissingFormatArgumentException desrEx = (MissingFormatArgumentException) deserialized;
-
- assertEquals("FormatSpecifier", initEx.getFormatSpecifier(), desrEx
- .getFormatSpecifier());
- }
- };
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new MissingFormatArgumentException(
- "MYTESTSTRING"), exComparator);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this,
- new MissingFormatArgumentException("MYTESTSTRING"),
- exComparator);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/MissingFormatWidthExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/MissingFormatWidthExceptionTest.java
deleted file mode 100644
index be94d1c..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/MissingFormatWidthExceptionTest.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/* 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.Serializable;
-import java.util.MissingFormatWidthException;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(MissingFormatWidthException.class)
-public class MissingFormatWidthExceptionTest extends TestCase {
-
- /**
- * @tests java.util.MissingFormatWidthException#MissingFormatWidthException(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "MissingFormatWidthException",
- args = {java.lang.String.class}
- )
- public void test_missingFormatWidthException() {
- assertNotNull(new MissingFormatWidthException("String"));
- try {
- new MissingFormatWidthException(null);
- fail("should throw NullPointerExcepiton");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.MissingFormatWidthException#getFormatSpecifier()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFormatSpecifier",
- args = {}
- )
- public void test_getFormatSpecifier() {
- String s = "MYTESTSTRING";
- MissingFormatWidthException missingFormatWidthException = new MissingFormatWidthException(
- s);
- assertEquals(s, missingFormatWidthException.getFormatSpecifier());
-
- }
-
- /**
- * @tests java.util.MissingFormatWidthException#getMessage()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
- public void test_getMessage() {
- String s = "MYTESTSTRING";
- MissingFormatWidthException missingFormatWidthException = new MissingFormatWidthException(
- s);
- assertTrue(null != missingFormatWidthException.getMessage());
-
- }
-
- // comparator for comparing MissingFormatWidthException objects
- private static final SerializableAssert exComparator = new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
-
- SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
- deserialized);
-
- MissingFormatWidthException initEx = (MissingFormatWidthException) initial;
- MissingFormatWidthException desrEx = (MissingFormatWidthException) deserialized;
-
- assertEquals("FormatSpecifier", initEx.getFormatSpecifier(), desrEx
- .getFormatSpecifier());
- }
- };
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new MissingFormatWidthException(
- "MYTESTSTRING"), exComparator);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new MissingFormatWidthException(
- "MYTESTSTRING"), exComparator);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ObserverTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ObserverTest.java
deleted file mode 100644
index cb36136..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/ObserverTest.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.apache.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.Observable;
-import java.util.Observer;
-
-@TestTargetClass(Observer.class)
-public class ObserverTest extends TestCase {
-
- class Mock_Observer implements Observer {
- int updateCount = 0;
-
- public void update(Observable observed, Object arg) {
- ++updateCount;
- }
-
- public int getUpdateCount() {
- return updateCount;
- }
- }
-
- class TestObservable extends Observable {
- public void doChange() {
- setChanged();
- }
-
- public void clearChange() {
- clearChanged();
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "update",
- args = {java.util.Observable.class, java.lang.Object.class}
- )
- public void testUpdate() {
- TestObservable observable = new TestObservable();
- Mock_Observer observer = null;
- observable.addObserver(observer = new Mock_Observer());
- observable.notifyObservers();
- assertEquals("Notified when unchnaged", 0, observer.getUpdateCount());
- observable.doChange();
- observable.notifyObservers();
- assertEquals("Failed to notify", 1, observer.getUpdateCount());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UUIDTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UUIDTest.java
deleted file mode 100644
index 562da42..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UUIDTest.java
+++ /dev/null
@@ -1,571 +0,0 @@
-/*
- * 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.UUID;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-@TestTargetClass(UUID.class)
-public class UUIDTest extends TestCase {
-
- /**
- * @see UUID#UUID(long, long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UUID",
- args = {long.class, long.class}
- )
- public void test_ConstructurJJ() {
- UUID uuid = new UUID(0xf81d4fae7dec11d0L, 0xa76500a0c91e6bf6L);
- assertEquals(2, uuid.variant());
- assertEquals(1, uuid.version());
- assertEquals(0x1d07decf81d4faeL, uuid.timestamp());
- assertEquals(130742845922168750L, uuid.timestamp());
- assertEquals(0x2765, uuid.clockSequence());
- assertEquals(0xA0C91E6BF6L, uuid.node());
- }
-
- /**
- * @see UUID#getLeastSignificantBits()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLeastSignificantBits",
- args = {}
- )
- public void test_getLeastSignificantBits() {
- UUID uuid = new UUID(0, 0);
- assertEquals(0, uuid.getLeastSignificantBits());
- uuid = new UUID(0, Long.MIN_VALUE);
- assertEquals(Long.MIN_VALUE, uuid.getLeastSignificantBits());
- uuid = new UUID(0, Long.MAX_VALUE);
- assertEquals(Long.MAX_VALUE, uuid.getLeastSignificantBits());
- }
-
- /**
- * @see UUID#getMostSignificantBits()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMostSignificantBits",
- args = {}
- )
- public void test_getMostSignificantBits() {
- UUID uuid = new UUID(0, 0);
- assertEquals(0, uuid.getMostSignificantBits());
- uuid = new UUID(Long.MIN_VALUE, 0);
- assertEquals(Long.MIN_VALUE, uuid.getMostSignificantBits());
- uuid = new UUID(Long.MAX_VALUE, 0);
- assertEquals(Long.MAX_VALUE, uuid.getMostSignificantBits());
- }
-
- /**
- * @see UUID#version()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "version",
- args = {}
- )
- public void test_version() {
- UUID uuid = new UUID(0, 0);
- assertEquals(0, uuid.version());
- uuid = new UUID(0x0000000000001000L, 0);
- assertEquals(1, uuid.version());
- uuid = new UUID(0x0000000000002000L, 0);
- assertEquals(2, uuid.version());
- uuid = new UUID(0x0000000000003000L, 0);
- assertEquals(3, uuid.version());
- uuid = new UUID(0x0000000000004000L, 0);
- assertEquals(4, uuid.version());
- uuid = new UUID(0x0000000000005000L, 0);
- assertEquals(5, uuid.version());
- }
-
- /**
- * @see UUID#variant()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "variant",
- args = {}
- )
- public void test_variant() {
- UUID uuid = new UUID(0, 0x0000000000000000L);
- assertEquals(0, uuid.variant());
- uuid = new UUID(0, 0x7000000000000000L);
- assertEquals(0, uuid.variant());
- uuid = new UUID(0, 0x3000000000000000L);
- assertEquals(0, uuid.variant());
- uuid = new UUID(0, 0x1000000000000000L);
- assertEquals(0, uuid.variant());
-
- uuid = new UUID(0, 0x8000000000000000L);
- assertEquals(2, uuid.variant());
- uuid = new UUID(0, 0xB000000000000000L);
- assertEquals(2, uuid.variant());
- uuid = new UUID(0, 0xA000000000000000L);
- assertEquals(2, uuid.variant());
- uuid = new UUID(0, 0x9000000000000000L);
- assertEquals(2, uuid.variant());
-
- uuid = new UUID(0, 0xC000000000000000L);
- assertEquals(6, uuid.variant());
- uuid = new UUID(0, 0xD000000000000000L);
- assertEquals(6, uuid.variant());
-
- uuid = new UUID(0, 0xE000000000000000L);
- assertEquals(7, uuid.variant());
- uuid = new UUID(0, 0xF000000000000000L);
- assertEquals(7, uuid.variant());
- }
-
- /**
- * @see UUID#timestamp()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "timestamp",
- args = {}
- )
- public void test_timestamp() {
- UUID uuid = new UUID(0x0000000000001000L, 0x8000000000000000L);
- assertEquals(0x0, uuid.timestamp());
-
- uuid = new UUID(0x7777777755551333L, 0x8000000000000000L);
- assertEquals(0x333555577777777L, uuid.timestamp());
-
- uuid = new UUID(0x0000000000000000L, 0x8000000000000000L);
- try {
- uuid.timestamp();
- fail("No UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {}
-
- uuid = new UUID(0x0000000000002000L, 0x8000000000000000L);
- try {
- uuid.timestamp();
- fail("No UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {}
- }
-
- /**
- * @see UUID#clockSequence()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clockSequence",
- args = {}
- )
- public void test_clockSequence() {
- UUID uuid = new UUID(0x0000000000001000L, 0x8000000000000000L);
- assertEquals(0x0, uuid.clockSequence());
-
- uuid = new UUID(0x0000000000001000L, 0x8FFF000000000000L);
- assertEquals(0x0FFF, uuid.clockSequence());
-
- uuid = new UUID(0x0000000000001000L, 0xBFFF000000000000L);
- assertEquals(0x3FFF, uuid.clockSequence());
-
- uuid = new UUID(0x0000000000000000L, 0x8000000000000000L);
- try {
- uuid.clockSequence();
- fail("No UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {}
-
- uuid = new UUID(0x0000000000002000L, 0x8000000000000000L);
- try {
- uuid.clockSequence();
- fail("No UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {}
- }
-
- /**
- * @see UUID#node()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "node",
- args = {}
- )
- public void test_node() {
- UUID uuid = new UUID(0x0000000000001000L, 0x8000000000000000L);
- assertEquals(0x0, uuid.node());
-
- uuid = new UUID(0x0000000000001000L, 0x8000FFFFFFFFFFFFL);
- assertEquals(0xFFFFFFFFFFFFL, uuid.node());
-
- uuid = new UUID(0x0000000000000000L, 0x8000000000000000L);
- try {
- uuid.node();
- fail("No UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {}
-
- uuid = new UUID(0x0000000000002000L, 0x8000000000000000L);
- try {
- uuid.node();
- fail("No UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {}
- }
-
- /**
- * @see UUID#compareTo(UUID)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.util.UUID.class}
- )
- public void test_compareTo() {
- UUID uuid1 = new UUID(0, 0);
- assertEquals(0, uuid1.compareTo(uuid1));
- UUID uuid2 = new UUID(1, 0);
- assertEquals(-1, uuid1.compareTo(uuid2));
- assertEquals(1, uuid2.compareTo(uuid1));
-
- uuid2 = new UUID(0, 1);
- assertEquals(-1, uuid1.compareTo(uuid2));
- assertEquals(1, uuid2.compareTo(uuid1));
- }
-
- /**
- * @see UUID#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- UUID uuid = new UUID(0, 0);
- assertEquals(0, uuid.hashCode());
- uuid = new UUID(123, 123);
- UUID uuidClone = new UUID(123, 123);
- assertEquals(uuid.hashCode(), uuidClone.hashCode());
- }
-
- /**
- * @see UUID#equals(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsObject() {
- UUID uuid1 = new UUID(0, 0);
- assertEquals(uuid1, uuid1);
- assertFalse(uuid1.equals(null));
- assertFalse(uuid1.equals("NOT A UUID"));
- UUID uuid2 = new UUID(0, 0);
- assertEquals(uuid1, uuid2);
- assertEquals(uuid2, uuid1);
-
- uuid1 = new UUID(0xf81d4fae7dec11d0L, 0xa76500a0c91e6bf6L);
- uuid2 = new UUID(0xf81d4fae7dec11d0L, 0xa76500a0c91e6bf6L);
- assertEquals(uuid1, uuid2);
- assertEquals(uuid2, uuid1);
-
- uuid2 = new UUID(0xf81d4fae7dec11d0L, 0xa76500a0c91e6bf7L);
- assertFalse(uuid1.equals(uuid2));
- assertFalse(uuid2.equals(uuid1));
- }
-
- /**
- * @see UUID#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- UUID uuid = new UUID(0xf81d4fae7dec11d0L, 0xa76500a0c91e6bf6L);
- String actual = uuid.toString();
- assertEquals("f81d4fae-7dec-11d0-a765-00a0c91e6bf6", actual);
-
- uuid = new UUID(0x0000000000001000L, 0x8000000000000000L);
- actual = uuid.toString();
- assertEquals("00000000-0000-1000-8000-000000000000", actual);
- }
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
- SerializationTest.verifySelf(new UUID(0xf81d4fae7dec11d0L,
- 0xa76500a0c91e6bf6L));
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
- SerializationTest.verifyGolden(this, new UUID(0xf81d4fae7dec11d0L,
- 0xa76500a0c91e6bf6L));
- }
-
- /**
- * @see UUID#randomUUID()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "randomUUID",
- args = {}
- )
- public void test_randomUUID() {
- UUID uuid = UUID.randomUUID();
- assertEquals(2, uuid.variant());
- assertEquals(4, uuid.version());
- }
-
- /**
- * @see UUID#nameUUIDFromBytes(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nameUUIDFromBytes",
- args = {byte[].class}
- )
- public void test_nameUUIDFromBytes() throws Exception {
- byte[] name = { (byte) 0x6b, (byte) 0xa7, (byte) 0xb8, (byte) 0x11,
- (byte) 0x9d, (byte) 0xad, (byte) 0x11, (byte) 0xd1,
- (byte) 0x80, (byte) 0xb4, (byte) 0x00, (byte) 0xc0,
- (byte) 0x4f, (byte) 0xd4, (byte) 0x30, (byte) 0xc8 };
-
- UUID uuid = UUID.nameUUIDFromBytes(name);
-
- assertEquals(2, uuid.variant());
- assertEquals(3, uuid.version());
-
- assertEquals(0xaff565bc2f771745L, uuid.getLeastSignificantBits());
- assertEquals(0x14cdb9b4de013faaL, uuid.getMostSignificantBits());
-
- uuid = UUID.nameUUIDFromBytes(new byte[0]);
- assertEquals(2, uuid.variant());
- assertEquals(3, uuid.version());
-
- assertEquals(0xa9800998ecf8427eL, uuid.getLeastSignificantBits());
- assertEquals(0xd41d8cd98f003204L, uuid.getMostSignificantBits());
-
- try {
- UUID.nameUUIDFromBytes(null);
- fail("No NPE");
- } catch (NullPointerException e) {}
- }
-
- /**
- * @see UUID#fromString(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fromString",
- args = {java.lang.String.class}
- )
- public void test_fromString() {
- UUID actual = UUID.fromString("f81d4fae-7dec-11d0-a765-00a0c91e6bf6");
- UUID expected = new UUID(0xf81d4fae7dec11d0L, 0xa76500a0c91e6bf6L);
- assertEquals(expected, actual);
-
- assertEquals(2, actual.variant());
- assertEquals(1, actual.version());
- assertEquals(130742845922168750L, actual.timestamp());
- assertEquals(10085, actual.clockSequence());
- assertEquals(690568981494L, actual.node());
-
- actual = UUID.fromString("00000000-0000-1000-8000-000000000000");
- expected = new UUID(0x0000000000001000L, 0x8000000000000000L);
- assertEquals(expected, actual);
-
- assertEquals(2, actual.variant());
- assertEquals(1, actual.version());
- assertEquals(0L, actual.timestamp());
- assertEquals(0, actual.clockSequence());
- assertEquals(0L, actual.node());
-
- try {
- UUID.fromString(null);
- fail("No NPE");
- } catch (NullPointerException e) {}
-
- try {
- UUID.fromString("");
- fail("No IAE");
- } catch (IllegalArgumentException e) {}
-
- try {
- UUID.fromString("f81d4fae_7dec-11d0-a765-00a0c91e6bf6");
- fail("No IAE");
- } catch (IllegalArgumentException e) {}
-
- try {
- UUID.fromString("f81d4fae-7dec_11d0-a765-00a0c91e6bf6");
- fail("No IAE");
- } catch (IllegalArgumentException e) {}
-
- try {
- UUID.fromString("f81d4fae-7dec-11d0_a765-00a0c91e6bf6");
- fail("No IAE");
- } catch (IllegalArgumentException e) {}
-
- try {
- UUID.fromString("f81d4fae-7dec-11d0-a765_00a0c91e6bf6");
- fail("No IAE");
- } catch (IllegalArgumentException e) {}
- }
-
- /**
- * @tests java.util.UUID#fromString(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fromString",
- args = {java.lang.String.class}
- )
- public void test_fromString_LString_Exception() {
-
- UUID uuid = UUID.fromString("0-0-0-0-0");
-
- try {
- uuid = UUID.fromString("0-0-0-0-");
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- try {
- uuid = UUID.fromString("-0-0-0-0-0");
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- try {
- uuid = UUID.fromString("-0-0-0-0");
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- try {
- uuid = UUID.fromString("-0-0-0-");
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- try {
- uuid = UUID.fromString("0--0-0-0");
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- try {
- uuid = UUID.fromString("0-0-0-0-");
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- try {
- uuid = UUID.fromString("-1-0-0-0-0");
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- uuid = UUID.fromString("123456789-0-0-0-0");
- assertEquals(0x2345678900000000L, uuid.getMostSignificantBits());
- assertEquals(0x0L, uuid.getLeastSignificantBits());
-
- uuid = UUID.fromString("111123456789-0-0-0-0");
- assertEquals(0x2345678900000000L, uuid.getMostSignificantBits());
- assertEquals(0x0L, uuid.getLeastSignificantBits());
-
- uuid = UUID.fromString("7fffffffffffffff-0-0-0-0");
- assertEquals(0xffffffff00000000L, uuid.getMostSignificantBits());
- assertEquals(0x0L, uuid.getLeastSignificantBits());
-
- try {
- uuid = UUID.fromString("8000000000000000-0-0-0-0");
- fail("should throw NumberFormatException");
- } catch (NumberFormatException e) {
- // expected
- }
-
- uuid = UUID
- .fromString("7fffffffffffffff-7fffffffffffffff-7fffffffffffffff-0-0");
- assertEquals(0xffffffffffffffffL, uuid.getMostSignificantBits());
- assertEquals(0x0L, uuid.getLeastSignificantBits());
-
- uuid = UUID.fromString("0-0-0-7fffffffffffffff-7fffffffffffffff");
- assertEquals(0x0L, uuid.getMostSignificantBits());
- assertEquals(0xffffffffffffffffL, uuid.getLeastSignificantBits());
-
- try {
- uuid = UUID.fromString("0-0-0-8000000000000000-0");
- fail("should throw NumberFormatException");
- } catch (NumberFormatException e) {
- // expected
- }
-
- try {
- uuid = UUID.fromString("0-0-0-0-8000000000000000");
- fail("should throw NumberFormatException");
- } catch (NumberFormatException e) {
- // expected
- }
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UnknownFormatConversionExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UnknownFormatConversionExceptionTest.java
deleted file mode 100644
index 14ed171..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UnknownFormatConversionExceptionTest.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/* 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.Serializable;
-import java.util.UnknownFormatConversionException;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(UnknownFormatConversionException.class)
-public class UnknownFormatConversionExceptionTest extends TestCase {
-
- /**
- * @tests java.util.UnknownFormatConversionException#UnknownFormatConversionException(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnknownFormatConversionException",
- args = {java.lang.String.class}
- )
- public void test_unknownFormatConversionException() {
-
- // RI 5.0 will not throw NullPointerException, it is the bug according
- // to spec.
- try {
- new UnknownFormatConversionException(null);
- } catch (NullPointerException e) {
- fail("should not throw NullPointerExcepiton");
- }
- }
-
- /**
- * @tests java.util.UnknownFormatConversionException#getConversion()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getConversion",
- args = {}
- )
- public void test_getConversion() {
- String s = "MYTESTSTRING";
- UnknownFormatConversionException UnknownFormatConversionException = new UnknownFormatConversionException(
- s);
- assertEquals(s, UnknownFormatConversionException.getConversion());
- }
-
- /**
- * @tests java.util.UnknownFormatConversionException#getMessage()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
- public void test_getMessage() {
- String s = "MYTESTSTRING";
- UnknownFormatConversionException UnknownFormatConversionException = new UnknownFormatConversionException(
- s);
- assertTrue(null != UnknownFormatConversionException.getMessage());
- }
-
- // comparator for comparing UnknownFormatConversionException objects
- private static final SerializableAssert exComparator = new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
-
- SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
- deserialized);
-
- UnknownFormatConversionException initEx = (UnknownFormatConversionException) initial;
- UnknownFormatConversionException desrEx = (UnknownFormatConversionException) deserialized;
-
- assertEquals("Conversion", initEx.getConversion(), desrEx
- .getConversion());
- }
- };
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new UnknownFormatConversionException(
- "MYTESTSTRING"), exComparator);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this,
- new UnknownFormatConversionException("MYTESTSTRING"),
- exComparator);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UnknownFormatFlagsExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UnknownFormatFlagsExceptionTest.java
deleted file mode 100644
index c14cdee..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/UnknownFormatFlagsExceptionTest.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/* 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.Serializable;
-import java.util.UnknownFormatFlagsException;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(UnknownFormatFlagsException.class)
-public class UnknownFormatFlagsExceptionTest extends TestCase {
-
- /**
- * @tests java.util.UnknownFormatFlagsException#UnknownFormatFlagsException(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnknownFormatFlagsException",
- args = {java.lang.String.class}
- )
- public void test_unknownFormatFlagsException() {
-
- try {
- new UnknownFormatFlagsException(null);
- fail("should throw NullPointerExcepiton");
- } catch (NullPointerException e) {
- // expected
- }
- assertNotNull(new UnknownFormatFlagsException("String"));
- }
-
- /**
- * @tests java.util.UnknownFormatFlagsException#getFlags()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFlags",
- args = {}
- )
- public void test_getFlags() {
- String s = "MYTESTSTRING";
- UnknownFormatFlagsException UnknownFormatFlagsException = new UnknownFormatFlagsException(
- s);
- assertEquals(s, UnknownFormatFlagsException.getFlags());
- }
-
- /**
- * @tests java.util.UnknownFormatFlagsException#getMessage()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
- public void test_getMessage() {
- String s = "MYTESTSTRING";
- UnknownFormatFlagsException UnknownFormatFlagsException = new UnknownFormatFlagsException(
- s);
- assertNotNull(UnknownFormatFlagsException.getMessage());
- }
-
- // comparator for comparing UnknownFormatFlagsException objects
- private static final SerializableAssert exComparator = new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
-
- SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
- deserialized);
-
- UnknownFormatFlagsException initEx = (UnknownFormatFlagsException) initial;
- UnknownFormatFlagsException desrEx = (UnknownFormatFlagsException) deserialized;
-
- assertEquals("Flags", initEx.getFlags(), desrEx.getFlags());
- }
- };
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
-
- SerializationTest.verifySelf(new UnknownFormatFlagsException(
- "MYTESTSTRING"), exComparator);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
- public void testSerializationCompatibility() throws Exception {
-
- SerializationTest.verifyGolden(this, new UnknownFormatFlagsException(
- "MYTESTSTRING"), exComparator);
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/VectorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/VectorTest.java
deleted file mode 100644
index 18cb550..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/VectorTest.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/* 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.Vector;
-
-@TestTargetClass(Vector.class)
-public class VectorTest extends TestCase {
-
- /**
- * @tests java.util.Vector#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Ensure toString works with self-referencing elements.
- Vector<Object> vec = new Vector<Object>(3);
- vec.add(null);
- vec.add(new Object());
- vec.add(vec);
- assertNotNull(vec.toString());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/WeakHashMapTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/WeakHashMapTest.java
deleted file mode 100644
index 9521641..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/java/util/WeakHashMapTest.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/* 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.harmony.luni.tests.java.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.WeakHashMap;
-
-@TestTargetClass(WeakHashMap.class)
-public class WeakHashMapTest extends TestCase {
-
- Object[] KEY_ARRAY;
-
- Object[] VALUE_ARRAY;
-
- /**
- * @tests java.util.WeakHashMap#entrySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "entrySet",
- args = {}
- )
- public void test_entrySet() {
- WeakHashMap<Object, Object> weakMap = new WeakHashMap<Object, Object>();
- KEY_ARRAY = new Object[100];
- VALUE_ARRAY = new Object[100];
- for (int i = 0; i < 100; i++) {
- KEY_ARRAY[i] = new Integer(i);
- VALUE_ARRAY[i] = new Long(i);
- weakMap.put(KEY_ARRAY[i], VALUE_ARRAY[i]);
- }
-
- List<Object> keys = Arrays.asList(KEY_ARRAY);
- List<Object> values = Arrays.asList(VALUE_ARRAY);
-
- // Check the entry set has correct size & content
- Set<Map.Entry<Object, Object>> entrySet = weakMap.entrySet();
- assertEquals("Assert 0: Incorrect number of entries returned", 100,
- entrySet.size());
- Iterator<Map.Entry<Object, Object>> it = entrySet.iterator();
- while (it.hasNext()) {
- Map.Entry<Object, Object> entry = it.next();
- assertTrue("Assert 1: Invalid map entry key returned", keys
- .contains(entry.getKey()));
- assertTrue("Assert 2: Invalid map entry value returned", values
- .contains(entry.getValue()));
- assertTrue("Assert 3: Entry not in entry set", entrySet
- .contains(entry));
- }
-
- // Dereference list of key/value objects
- keys = values = null;
-
- // Dereference a single key, then try to
- // force a collection of the weak ref'd obj
- KEY_ARRAY[50] = null;
- int count = 0;
- do {
- System.gc();
- System.gc();
- Runtime.getRuntime().runFinalization();
- count++;
- } while (count <= 5 && entrySet.size() == 100);
-
- if ((count == 5) && (entrySet.size() == 100)) {
- // We failed (or entrySet broken), so further tests not valid.
- return;
- }
-
- assertEquals("Assert 4: Incorrect number of entries after gc", 99,
- entrySet.size());
- assertSame("Assert 5: Entries not identical", entrySet.iterator()
- .next(), entrySet.iterator().next());
-
- // remove alternate entries using the iterator, and ensure the
- // iteration count is consistent
- int size = entrySet.size();
- it = entrySet.iterator();
- while (it.hasNext()) {
- it.next();
- it.remove();
- size--;
- if (it.hasNext()) {
- it.next();
- }
-
- }
- assertEquals("Assert 6: entry set count mismatch", size, entrySet
- .size());
-
- int entries = 0;
- it = entrySet.iterator();
- while (it.hasNext()) {
- it.next();
- entries++;
- }
- assertEquals("Assert 6: count mismatch", size, entries);
-
- it = entrySet.iterator();
- while (it.hasNext()) {
- it.next();
- it.remove();
- }
- assertEquals("Assert 7: entry set not empty", 0, entrySet.size());
- assertTrue("Assert 8: iterator not empty", !entrySet.iterator()
- .hasNext());
- }
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/pkg1/TestClass.java b/luni/src/test/java/org/apache/harmony/luni/tests/pkg1/TestClass.java
deleted file mode 100644
index 5bef9b9..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/pkg1/TestClass.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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.harmony.luni.tests.pkg1;
-
-import java.io.Serializable;
-
-/**
- * Used for a serialization test, must have different package and same base name
- * as the TestClass in o.a.h.l.tests.pkg2
- */
-public class TestClass implements Serializable {
- private static final long serialVersionUID = 11111L;
-
- public int i = 0;
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/pkg2/TestClass.java b/luni/src/test/java/org/apache/harmony/luni/tests/pkg2/TestClass.java
deleted file mode 100644
index c1a9a4e..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/pkg2/TestClass.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * 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.harmony.luni.tests.pkg2;
-
-import java.io.Serializable;
-
-/**
- * Used for a serialization test, must have different package and same base name
- * as the TestClass in o.a.h.l.tests.pkg1
- */
-public class TestClass implements Serializable {
- private static final long serialVersionUID = 11111L;
- public int i = 0;
-}
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/util/Base64Test.java b/luni/src/test/java/org/apache/harmony/luni/tests/util/Base64Test.java
deleted file mode 100644
index 1795745..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/util/Base64Test.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.harmony.luni.tests.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import org.apache.harmony.luni.util.Base64;
-
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
-
-/**
- * Base64 encoder/decoder test.
- */
-@TestTargetClass(Base64.class)
-public class Base64Test extends TestCase {
-
- /**
- * Checks the result on empty parameter.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "decode",
- args = {byte[].class}
- )
- public static void testDecodeEmpty() throws Exception {
- // Regression for HARMONY-1513
- byte[] result = Base64.decode(new byte[0]);
- assertEquals("The length of the result differs from expected",
- 0, result.length);
- }
-
- public static Test suite() {
- return new TestSuite(Base64Test.class);
- }
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
-}
-
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/util/MsgHelpTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/util/MsgHelpTest.java
deleted file mode 100644
index 2ad20ef..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/util/MsgHelpTest.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/* 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.harmony.luni.tests.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import org.apache.harmony.luni.util.MsgHelp;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(MsgHelp.class)
-public class MsgHelpTest extends TestCase {
-
- public MsgHelpTest(String name) {
- super(name);
- }
-
- /*
- * Test method for 'org.apache.harmony.luni.util.MsgHelp.format(String,
- * Object[])'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void testFormatLjava_lang_String$Ljava_lang_Object() {
- assertEquals("empty", MsgHelp.format("empty", new Object[0]));
-
- assertEquals("<null>", MsgHelp.format("{0}", new Object[1]));
- assertEquals("<missing argument>", MsgHelp.format("{0}", new Object[0]));
- assertEquals("fixture {} fixture", MsgHelp.format("{0} \\{} {0}",
- new Object[] { "fixture" }));
-
- assertEquals("<null> fixture", MsgHelp.format("{0} {1}", new Object[] {
- null, "fixture" }));
- assertEquals("<null> fixture <missing argument>", MsgHelp.format(
- "{0} {1} {2}", new Object[] { null, "fixture" }));
- assertEquals("<null> fixture", MsgHelp.format("{0} {1}", new Object[] {
- null, "fixture", "extra" }));
-
- assertEquals("0 1 2 3 4 5 6 7 8 9", MsgHelp.format(
- "{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}", new Object[] { "0",
- "1", "2", "3", "4", "5", "6", "7", "8", "9" }));
- assertEquals("9 8 7 6 5 4 3 2 1 0", MsgHelp.format(
- "{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}", new Object[] { "9",
- "8", "7", "6", "5", "4", "3", "2", "1", "0" }));
-
- assertEquals("0 1 2 3 4 5 6 7 8 9 {10}", MsgHelp.format(
- "{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10}",
- new Object[] { "0", "1", "2", "3", "4", "5", "6", "7", "8",
- "9", "10" }));
-
- try {
- MsgHelp.format(null, new Object[0]);
- fail("No NPE");
- } catch (NullPointerException e) {
- }
-
- try {
- MsgHelp.format("fixture", null);
- fail("No NPE");
- } catch (NullPointerException e) {
- }
- }
-
-} \ No newline at end of file
diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/util/NYITest.java b/luni/src/test/java/org/apache/harmony/luni/tests/util/NYITest.java
deleted file mode 100644
index b30501e..0000000
--- a/luni/src/test/java/org/apache/harmony/luni/tests/util/NYITest.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * 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.harmony.luni.tests.util;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.ByteArrayOutputStream;
-import java.io.PrintStream;
-import java.io.UnsupportedEncodingException;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.luni.util.NotImplementedException;
-
-/**
- * Testing the NYI framework code.
- */
-// well this should be the past now.
-@TestTargetClass(NotImplementedException.class)
-public class NYITest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NotImplementedException",
- args = {java.io.PrintStream.class}
- )
- public void testNYI() throws UnsupportedEncodingException {
- ByteArrayOutputStream bos = new ByteArrayOutputStream(400);
- PrintStream stream = new PrintStream(bos, true, "UTF-8");
- new NotImplementedException(stream);
- String message = new String(bos.toByteArray(), "UTF-8");
- assertFalse(message.indexOf("NYITest") == -1);
- }
-}
diff --git a/luni/src/test/java/tests/AllTests.java b/luni/src/test/java/tests/AllTests.java
deleted file mode 100644
index 2adfd2d..0000000
--- a/luni/src/test/java/tests/AllTests.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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 tests;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-import junit.textui.TestRunner;
-
-/**
- * Listing of all the tests that are to be run.
- */
-public class AllTests
-{
- public static void run() {
- TestRunner.main(new String[] { AllTests.class.getName() });
- }
-
- public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite();
-
- suite.addTest(tests.annotation.AllTests.suite());
- suite.addTest(tests.archive.AllTests.suite());
- suite.addTest(tests.concurrent.AllTests.suite());
- suite.addTest(tests.crypto.AllTests.suite());
- suite.addTest(tests.logging.AllTests.suite());
- suite.addTest(tests.luni.AllTests.suite());
- suite.addTest(tests.luni.AllTestsIo.suite());
- suite.addTest(tests.luni.AllTestsLang.suite());
- suite.addTest(tests.luni.AllTestsNet.suite());
- suite.addTest(tests.luni.AllTestsUtil.suite());
- suite.addTest(tests.math.AllTests.suite());
- suite.addTest(tests.nio.AllTests.suite());
- suite.addTest(tests.nio_char.AllTests.suite());
- suite.addTest(tests.prefs.AllTests.suite());
- suite.addTest(tests.regex.AllTests.suite());
- suite.addTest(tests.sql.AllTests.suite());
- suite.addTest(tests.text.AllTests.suite());
- suite.addTest(tests.xml.AllTests.suite());
- suite.addTest(tests.xnet.AllTests.suite());
- suite.addTest(tests.dom.AllTests.suite());
-
- suite.addTest(tests.security.AllTests.suite());
-
- return suite;
- }
-}
diff --git a/luni/src/test/java/tests/TestSuiteFactory.java b/luni/src/test/java/tests/TestSuiteFactory.java
deleted file mode 100644
index 4f4a479..0000000
--- a/luni/src/test/java/tests/TestSuiteFactory.java
+++ /dev/null
@@ -1,355 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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 tests;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.KnownFailure;
-
-import junit.extensions.TestSetup;
-import junit.framework.AssertionFailedError;
-import junit.framework.Protectable;
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestResult;
-import junit.framework.TestSuite;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.Vector;
-
-/**
- * an enhanced TestSuite e.g. for running RI tests.
- *
- * a sample command line:
- *
- * /usr/lib/jvm/java-1.5.0-sun/bin/java -Xmx1024m -Dcts.listOnlyFailingTests=true
- * -Dcts.includeKnownFailure=false -Dcts.runOnDalvikVM=false
- * -Dcts.allowUnderscoreTests=false -Dcts.useEnhancedJunit=true
- * -Dcts.collectOnly=false
- * -cp
- * /tmp/cts_outjavac:
- * out/debug/host/linux-x86/product/sim/data/app/CtsCoreTests.apk:
- * out/debug/target/common/obj/APPS/CtsCoreTests_intermediates/classes.jar:
- * tools/cts/vm-tests/lib/junit.jar
- *
- * junit.textui.TestRunner tests.AllTests
- *
- */
-public class TestSuiteFactory {
-
-
-
- static boolean _collectOnly = false;
- static boolean _useEnhancedJunit = false;
- static boolean _allowUnderscoreTests = false;
- static boolean _runOnDalvikVM = true;
- static boolean _includeKnowFailure = false;
- static boolean _listOnlyFailingTests = false;
- static boolean _useSuppliedTestResult = false;
- static int _maxRunningTimePerTest = 15000; // 15 seconds
-
- static {
- _useEnhancedJunit = System.getProperty("cts.useEnhancedJunit", "false").equals("true");
- // next only applicable if _useEnhancedJunit
- _collectOnly = System.getProperty("cts.collectOnly", "false").equals("true");
- _allowUnderscoreTests= System.getProperty("cts.allowUnderscoreTests", "false").equals("true");
- _runOnDalvikVM = System.getProperty("cts.runOnDalvikVM", "true").equals("true");
- _includeKnowFailure = System.getProperty("cts.includeKnownFailure", "false").equals("true");
- _maxRunningTimePerTest = Integer.parseInt(System.getProperty("cts.maxRunningTimePerTest", "15000"));
- _listOnlyFailingTests = System.getProperty("cts.listOnlyFailingTests", "false").equals("true");
- _useSuppliedTestResult = System.getProperty("cts.useSuppliedTestResult", "false").equals("true");
-
- System.out.println("TestSuiteFactory: v0.97");
- System.out.println("TestSuiteFactory: using cts.useEnhancedJunit: "+_useEnhancedJunit);
- System.out.println("TestSuiteFactory: using cts.collectOnly: "+_collectOnly);
- System.out.println("TestSuiteFactory: max allowed running time per test (using Thread.stop()) (cts.maxRunningTimePerTest): "+_maxRunningTimePerTest);
- System.out.println("TestSuiteFactory: run tests on a dalvik vm (cts.runOnDalvikVM): "+_runOnDalvikVM);
- System.out.println("TestSuiteFactory: include @KnowFailure when running on dalvik vm (cts.includeKnownFailure): "+_includeKnowFailure);
- System.out.println("TestSuiteFactory: include '_test...' methods in test run (cts.allowUnderscoreTests): "+_allowUnderscoreTests);
- System.out.println("TestSuiteFactory: list only failing tests (cts.listOnlyFailingTests): "+_listOnlyFailingTests);
- System.out.println();
- }
-
- public static TestSuite createTestSuite(String name) {
- return _useEnhancedJunit? new MyTestSuite(name): new TestSuite(name);
- }
-
- public static TestSuite createTestSuite() {
- return _useEnhancedJunit? new MyTestSuite(): new TestSuite();
- }
-
-}
-
-
-class MyTestSuite extends TestSuite {
- private boolean allow_underscoretests = true;
-
- public MyTestSuite() {
- }
-
- public MyTestSuite(String name) {
- super(name);
- }
-
- public MyTestSuite(final Class theClass) {
- String fName = theClass.getName();
- try {
- TestSuite.getTestConstructor(theClass); // Avoid generating multiple error
- // messages
- } catch (NoSuchMethodException e) {
- addTest(warning("Class "
- + theClass.getName()
- + " has no public constructor TestCase(String name) or TestCase()"));
- return;
- }
-
- if (!Modifier.isPublic(theClass.getModifiers())) {
- addTest(warning("Class " + theClass.getName() + " is not public"));
- return;
- }
-
- Class superClass = theClass;
- Vector names = new Vector();
- while (Test.class.isAssignableFrom(superClass)) {
- Method[] methods = superClass.getDeclaredMethods();
- for (int i = 0; i < methods.length; i++) {
- addTestMethod(methods[i], names, theClass);
- }
- superClass = superClass.getSuperclass();
- }
- if (testCount() == 0)
- addTest(warning("No tests found in " + theClass.getName()));
- }
-
- private void addTestMethod(Method m, Vector names, Class theClass) {
- String name = m.getName();
- if (names.contains(name)) return;
- if (!isPublicTestMethod(m)) {
- if (isTestMethod(m))
- addTest(warning("Test method isn't public: " + m.getName()));
- return;
- }
- names.addElement(name);
- addTest(TestSuite.createTest(theClass, name));
- }
-
- private boolean isPublicTestMethod(Method m) {
- return isTestMethod(m) && Modifier.isPublic(m.getModifiers());
- }
-
- private boolean isTestMethod(Method m) {
- String name = m.getName();
- Class[] parameters = m.getParameterTypes();
- Class returnType = m.getReturnType();
- return parameters.length == 0 &&
- (name.startsWith("test") || (TestSuiteFactory._allowUnderscoreTests && name.startsWith("_test")))
- && returnType.equals(Void.TYPE);
- }
-
- public void addTestSuite(Class testClass) {
- try {
- addTest(new MyTestSuite(testClass));
- } catch (Throwable e) {
- System.err.println("---------------- error ----------------------");
- System.err.println("error: could not add test suite: "
- + testClass.getName());
- e.printStackTrace();
- System.err.println("---------------- ----------------------------");
- }
- }
-
- private static int testCnt = 0;
-
- public void runTest(Test test, final TestResult dummy_result) {
-
- if (TestSuiteFactory._useSuppliedTestResult) {
- if (test instanceof TestSetup) {
- test = ((TestSetup)test).getTest();
- }
- test.run(dummy_result);
- return;
- }
-
- TestResult eresult = new TestResult() {
- private String msg;
- private boolean error = false;
-
- protected void run(final TestCase testcase) {
- msg = "";
- String testName = testcase.getClass().getName() + ":" + testcase.getName()+" (nr:"+(++testCnt)+")";
- try {
- if (!TestSuiteFactory._listOnlyFailingTests) {
- System.out.print(testName+" ");
- }
- Annotation aKnownFailure = null;
- Annotation aAndroidOnly = null;
- if (true) { // handle annotations, allow them on both class (valid for all methods then) and method level
- // @KnownFailure("Fails because of a defect in ...") if the test is correct but there is a bug in the core libraries implementation.
- // @BrokenTest("This test is not implemented correctly because...") if there is a defect in the test method itself.
- // @AndroidOnly("Because...") if the test is Android-specific, succeeds on Android but fails on the JDK.
- try {
- Annotation[] annosClass = testcase.getClass().getDeclaredAnnotations();
- Method runMethod= testcase.getClass().getMethod(testcase.getName());
- Annotation[] annosMethod = runMethod.getDeclaredAnnotations();
- Annotation[] annos = null;
- for (int i = 0; i < 2; i++) {
- annos = (i==0? annosClass : annosMethod);
- if (annos != null && annos.length > 0) {
- for (Annotation anno : annos) {
- Class<? extends Annotation> acla = anno.annotationType();
- if (acla.getName().equals("dalvik.annotation.AndroidOnly")) {
- aAndroidOnly = anno;
- } else if (acla.getName().equals("dalvik.annotation.KnownFailure")) {
- aKnownFailure = anno;
- }
- }
- }
- }
- } catch (NoSuchMethodException e) {
- error = true;
- msg +="::warning::unable to get test method to read annotations: testcase name="+testcase.getName();
- }
- }
- boolean androidOnly = aAndroidOnly != null;
- boolean knownFailure = aKnownFailure != null;
-
- if (
- !TestSuiteFactory._collectOnly
- && (
- (TestSuiteFactory._runOnDalvikVM &&
- (TestSuiteFactory._includeKnowFailure || !knownFailure)
- )
- ||
- (!TestSuiteFactory._runOnDalvikVM && !androidOnly)
- )
- ) {
-
- msg += "[";
- long start = System.currentTimeMillis();
- // -----start the test ----
- startTest(testcase);
- final Protectable p= new Protectable() {
- public void protect() throws Throwable {
- testcase.runBare();
- }
- };
- boolean threadStopForced = false;
- if (!TestSuiteFactory._runOnDalvikVM) {
- // for jvm, start in a new thread, since we can stop() it for too-long running processes.
- Thread t = new Thread(new Runnable(){
- public void run() {
- try {
- p.protect();
- }
- catch (AssertionFailedError e) {
- addFailure(testcase, e);
- }
- catch (ThreadDeath e) { // don't catch ThreadDeath by accident
- throw e;
- }
- catch (Throwable e) {
- addError(testcase, e);
- }
- }});
- t.start();
-
- try {
- //System.out.println("joining...");
- t.join(TestSuiteFactory._maxRunningTimePerTest);
- //System.out.println("joining done...");
- } catch (InterruptedException e) {
- // ignore
- }
- if (t.isAlive()) {
- threadStopForced = true;
- }
- t.stop();
-
- // for RI vm : run in new thread and stop thread after a timeout
- } else {
- runProtected(testcase, p);
- }
-
- endTest(testcase);
- // ------------------------
-
- msg += "]";
- long stop = System.currentTimeMillis();
- if (threadStopForced) {
- error = true;
- msg += "::warning::slow test forced to stop since it took longer than "+ TestSuiteFactory._maxRunningTimePerTest;
- } else if (stop - start > TestSuiteFactory._maxRunningTimePerTest) {
- error = true;
- msg += "::warning::slow test took longer than "+ TestSuiteFactory._maxRunningTimePerTest+" milis: "+(stop-start)+" milis. ";
- }
-
- }
- if (!TestSuiteFactory._runOnDalvikVM && androidOnly) {
- msg+= "ignoring on RI since @AndroidOnly: "+((AndroidOnly)aAndroidOnly).value();
- }
- if (TestSuiteFactory._runOnDalvikVM && knownFailure && !TestSuiteFactory._includeKnowFailure) {
- msg += "ignoring on dalvik since @KnownFailure: "+((KnownFailure)aKnownFailure).value();
- }
- }
- finally {
- if (TestSuiteFactory._listOnlyFailingTests) {
- if (error) {
- // we have error / warnings
- msg = testName + msg;
- System.out.println(msg);
- } // else do not output anything
- } else {
- System.out.println(msg+(error? "": " cts-test-passed"));
- }
- }
- }
-
- public synchronized void addError(Test test, Throwable t) {
- error = true;
- msg+= " ::error::err:"+exceptionToString(t);
- super.addError(test, t);
- }
-
- public synchronized void addFailure(Test test,
- AssertionFailedError t) {
- error = true;
- msg+= " ::error::failure:"+exceptionToString(t);
- super.addFailure(test, t);
- }
- };
- test.run(eresult);
- }
-
- private static Test warning(final String message) {
- return new TestCase("warning") {
- protected void runTest() {
- fail(message);
- }
- };
- }
-
- private static String exceptionToString(Throwable t) {
- StringWriter stringWriter = new StringWriter();
- PrintWriter writer = new PrintWriter(stringWriter);
- t.printStackTrace(writer);
- return stringWriter.toString();
-
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/AllTests.java b/luni/src/test/java/tests/api/java/io/AllTests.java
deleted file mode 100644
index 295d4d8..0000000
--- a/luni/src/test/java/tests/api/java/io/AllTests.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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 tests.api.java.io;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-/**
- * This is autogenerated source file. Includes tests for package tests.api.java.io;
- */
-
-public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(AllTests.suite());
- }
-
- public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package tests.api.java.io;");
- // $JUnit-BEGIN$
-
- suite.addTestSuite(BufferedInputStreamTest.class);
- suite.addTestSuite(BufferedOutputStreamTest.class);
- suite.addTestSuite(BufferedReaderTest.class);
- suite.addTestSuite(BufferedWriterTest.class);
- suite.addTestSuite(ByteArrayInputStreamTest.class);
- suite.addTestSuite(ByteArrayOutputStreamTest.class);
- suite.addTestSuite(CharArrayReaderTest.class);
- suite.addTestSuite(CharArrayWriterTest.class);
- suite.addTestSuite(CharConversionExceptionTest.class);
- suite.addTestSuite(ComputeSerialVersionUIDTest.class);
- suite.addTestSuite(DataInputStreamTest.class);
- suite.addTestSuite(DataInputOutputStreamTest.class);
- suite.addTestSuite(DataOutputStreamTest.class);
- suite.addTestSuite(EOFExceptionTest.class);
- suite.addTestSuite(FileDescriptorTest.class);
- suite.addTestSuite(FileInputStreamTest.class);
- suite.addTestSuite(FileNotFoundExceptionTest.class);
- suite.addTestSuite(FileOutputStreamTest.class);
- suite.addTestSuite(FilePermissionTest.class);
- suite.addTestSuite(FileReaderTest.class);
- suite.addTestSuite(FileTest.class);
- suite.addTestSuite(FileWriterTest.class);
- suite.addTestSuite(FilterInputStreamTest.class);
- suite.addTestSuite(FilterOutputStreamTest.class);
- suite.addTestSuite(FilterReaderTest.class);
- suite.addTestSuite(FilterWriterTest.class);
- suite.addTestSuite(IOExceptionTest.class);
- suite.addTestSuite(InputStreamReaderTest.class);
- suite.addTestSuite(InterruptedIOExceptionTest.class);
- suite.addTestSuite(InvalidClassExceptionTest.class);
- suite.addTestSuite(InvalidObjectExceptionTest.class);
- suite.addTestSuite(LineNumberInputStreamTest.class);
- suite.addTestSuite(LineNumberReaderTest.class);
- suite.addTestSuite(NotActiveExceptionTest.class);
- suite.addTestSuite(NotSerializableExceptionTest.class);
- suite.addTestSuite(ObjectInputStreamTest.class);
- suite.addTestSuite(ObjectInputStreamGetFieldTest.class);
- suite.addTestSuite(ObjectInputOutputStreamTest.class);
- suite.addTestSuite(ObjectOutputStreamTest.class);
- suite.addTestSuite(ObjectOutputStreamPutFieldTest.class);
- suite.addTestSuite(ObjectStreamClassTest.class);
- suite.addTestSuite(ObjectStreamExceptionTest.class);
- suite.addTestSuite(ObjectStreamFieldTest.class);
- suite.addTestSuite(OpenRandomFileTest.class);
- suite.addTestSuite(OutputStreamTest.class);
- suite.addTestSuite(OutputStreamWriterTest.class);
- suite.addTestSuite(PipedInputStreamTest.class);
- suite.addTestSuite(PipedOutputStreamTest.class);
- suite.addTestSuite(PipedReaderTest.class);
- suite.addTestSuite(PipedWriterTest.class);
- suite.addTestSuite(PrintStreamTest.class);
- suite.addTestSuite(PrintWriterTest.class);
- suite.addTestSuite(PushbackInputStreamTest.class);
- suite.addTestSuite(PushbackReaderTest.class);
- suite.addTestSuite(RandomAccessFileTest.class);
- suite.addTestSuite(SequenceInputStreamTest.class);
- suite.addTestSuite(SerializablePermissionTest.class);
- suite.addTestSuite(SerializationStressTest.class);
- suite.addTestSuite(SerializationStressTest1.class);
- suite.addTestSuite(SerializationStressTest2.class);
- suite.addTestSuite(SerializationStressTest3.class);
- suite.addTestSuite(SerializationStressTest4.class);
- suite.addTestSuite(SerializationStressTest4.class);
- suite.addTestSuite(SerializationStressTest5.class);
- suite.addTestSuite(StreamCorruptedExceptionTest.class);
- suite.addTestSuite(StreamTokenizerTest.class);
- suite.addTestSuite(StringBufferInputStreamTest.class);
- suite.addTestSuite(StringReaderTest.class);
- suite.addTestSuite(StringWriterTest.class);
- suite.addTestSuite(SyncFailedExceptionTest.class);
- suite.addTestSuite(UTFDataFormatExceptionTest.class);
- suite.addTestSuite(UnsupportedEncodingExceptionTest.class);
- suite.addTestSuite(WriteAbortedExceptionTest.class);
- suite.addTestSuite(WriterTest.class);
-
- // $JUnit-END$
- return suite;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/BufferedInputStreamTest.java b/luni/src/test/java/tests/api/java/io/BufferedInputStreamTest.java
deleted file mode 100644
index d5ab18e..0000000
--- a/luni/src/test/java/tests/api/java/io/BufferedInputStreamTest.java
+++ /dev/null
@@ -1,578 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-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 junit.framework.TestCase;
-import tests.support.Support_ASimpleInputStream;
-import tests.support.Support_PlatformFile;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-@TestTargetClass(BufferedInputStream.class)
-public class BufferedInputStreamTest extends TestCase {
-
- public String fileName;
-
- private BufferedInputStream is;
-
- private FileInputStream isFile;
-
- byte[] ibuf = new byte[4096];
-
- public String fileString = "Test_All_Tests\nTest_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_java_io_File\nTest_java_io_FileDescriptor\nTest_java_io_FileInputStream\nTest_java_io_FileNotFoundException\nTest_java_io_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
-
- /**
- * @throws IOException
- * @tests java.io.BufferedInputStream#BufferedInputStream(java.io.InputStream,
- * int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "BufferedInputStream",
- args = {java.io.InputStream.class}
- )
- public void test_ConstructorLjava_io_InputStream() {
- is = new BufferedInputStream(isFile);
-
- try {
- is.read();
- } catch (Exception e) {
- fail("Test 1: Read failed on a freshly constructed buffer.");
- }
- }
-
- /**
- * @throws IOException
- * @tests java.io.BufferedInputStream#BufferedInputStream(java.io.InputStream,
- * int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "BufferedInputStream",
- args = {java.io.InputStream.class, int.class}
- )
- public void test_ConstructorLjava_io_InputStreamI() throws IOException {
- // Test for method java.io.BufferedInputStream(java.io.InputStream, int)
- boolean exceptionFired = false;
-
- try {
- is = new BufferedInputStream(isFile, -1);
- fail("IllegalArgumentException expected.");
- } catch (IllegalArgumentException e) {
- // Expected.
- }
-
- try {
- // Create buffer with exact size of file
- is = new BufferedInputStream(isFile, this.fileString
- .length());
- // Ensure buffer gets filled by evaluating one read
- is.read();
- // Close underlying FileInputStream, all but 1 buffered bytes should
- // still be available.
- isFile.close();
- // Read the remaining buffered characters, no IOException should
- // occur.
- is.skip(this.fileString.length() - 2);
- is.read();
- try {
- // is.read should now throw an exception because it will have to
- // be filled.
- is.read();
- } catch (IOException e) {
- exceptionFired = true;
- }
- assertTrue("Exception should have been triggered by read()",
- exceptionFired);
- } catch (IOException e) {
- fail("Exception during test_1_Constructor");
- }
-
- // regression test for harmony-2407
- new testBufferedInputStream(null);
- assertNotNull(testBufferedInputStream.buf);
- testBufferedInputStream.buf = null;
- new testBufferedInputStream(null, 100);
- assertNotNull(testBufferedInputStream.buf);
- }
-
- static class testBufferedInputStream extends BufferedInputStream {
- static byte[] buf;
- testBufferedInputStream(InputStream is) throws IOException {
- super(is);
- buf = super.buf;
- }
-
- testBufferedInputStream(InputStream is, int size) throws IOException {
- super(is, size);
- buf = super.buf;
- }
- }
-
- /**
- * @tests java.io.BufferedInputStream#available()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies the available() method.",
- method = "available",
- args = {}
- )
- public void test_available() {
- // Test for method int java.io.BufferedInputStream.available()
- try {
- assertTrue("Returned incorrect number of available bytes", is
- .available() == fileString.length());
- } catch (IOException e) {
- fail("Exception during available test");
- }
-
- // Test that a closed stream throws an IOE for available()
- BufferedInputStream bis = new BufferedInputStream(
- new ByteArrayInputStream(new byte[] { 'h', 'e', 'l', 'l', 'o',
- ' ', 't', 'i', 'm' }));
- int available = 0;
- try {
- available = bis.available();
- bis.close();
- } catch (IOException ex) {
- fail();
- }
- assertTrue(available != 0);
-
- try {
- bis.available();
- fail("Expected test to throw IOE.");
- } catch (IOException ex) {
- // expected
- } catch (Throwable ex) {
- fail("Expected test to throw IOE not "
- + ex.getClass().getName());
- }
- }
-
- /**
- * @throws IOException
- * @tests java.io.BufferedInputStream#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "close",
- args = {}
- )
- public void test_close() throws IOException {
- is.close();
-
- try {
- is.read();
- fail("Test 1: IOException expected when reading after closing " +
- "the stream.");
- } catch (IOException e) {
- // Expected.
- }
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(true);
- is = new BufferedInputStream(sis);
- try {
- is.close();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- }
-
- /**
- * @tests java.io.BufferedInputStream#mark(int)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "mark",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "reset",
- args = {}
- ) /* ,
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks that a marked position is invalidated.",
- method = "read",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks that a marked position is invalidated.",
- method = "read",
- args = {byte[].class, int.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks that a marked position is invalidated.",
- method = "skip",
- args = {long.class}
- ) */
- })
- public void test_markI_reset() throws IOException {
- byte[] buf1 = new byte[100];
- byte[] buf2 = new byte[100];
-
- // Test 1: Check that reset fails if no mark has been set.
- try {
- is.reset();
- fail("Test 1: IOException expected if no mark has been set.");
- } catch (IOException e) {
- // Expected.
- }
-
- // Test 2: Check that mark / reset works when the mark is not invalidated.
- is.skip(10);
- is.mark(100);
- is.read(buf1, 0, buf1.length);
- is.reset();
- is.read(buf2, 0, buf2.length);
- is.reset();
- assertTrue("Test 2: Failed to mark correct position or reset failed.",
- new String(buf1, 0, buf1.length).equals(new String(buf2, 0, buf2.length)));
-
- // Tests 3 and 4: Check that skipping less than readlimit bytes does
- // not invalidate the mark.
- is.skip(10);
- try {
- is.reset();
- } catch (IOException e) {
- fail("Test 3: Unexpected IOException " + e.getMessage());
- }
- is.read(buf2, 0, buf2.length);
- is.reset();
- assertTrue("Test 4: Failed to mark correct position, or reset failed.",
- new String(buf1, 0, buf1.length).equals(new String(buf2, 0, buf2.length)));
-
-/* Tests disabled because they fail. The specification is ambiguous
- * regarding the invalidation of a set mark by read and skip operations.
-
- // Test 5: Check that the mark is invalidated by a sequence of reads.
- is.skip(200);
- is.mark(10);
- for (int i = 0; i < 11; i++) {
- is.read();
- }
- try {
- is.reset();
- fail("Test 5: IOException expected because the mark should be invalid.");
- } catch (IOException e) {
- // Expected.
- }
-
- // Test 6: Check that the mark is invalidated by a buffer read.
- is.skip(200);
- is.mark(10);
- is.read(buf1, 0, buf1.length);
- try {
- is.reset();
- fail("Test 6: IOException expected because the mark should be invalid.");
- } catch (IOException e) {
- // Expected.
- }
-
- // Test 7: Check that the mark is invalidated by a skip.
- is.mark(10);
- is.skip(11);
- try {
- is.reset();
- fail("Test 7: IOException expected because the mark should be invalid.");
- } catch (IOException e) {
- // Expected.
- }
-*/
-
- // Test 8: Check that reset fails for a closed input stream.
- is.close();
- try {
- is.reset();
- fail("Test 8: IOException expected because the input stream is closed.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.BufferedInputStream#markSupported()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies markSupported() method.",
- method = "markSupported",
- args = {}
- )
- public void test_markSupported() {
- // Test for method boolean java.io.BufferedInputStream.markSupported()
- assertTrue("markSupported returned incorrect value", is.markSupported());
- }
-
- /**
- * @tests java.io.BufferedInputStream#read()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "A partial read test in test_markI_reset() is disabled at " +
- "the moment because it fails. If this test is ever " +
- "enabled, then the level here must be changed to " +
- "PARTIAL_COMPLETE.",
- method = "read",
- args = {}
- )
- public void test_read() throws IOException {
- int c = is.read();
- assertTrue("Test 1: Incorrect character read.",
- c == fileString.charAt(0));
-
- byte[] bytes = new byte[256];
- for (int i = 0; i < 256; i++) {
- bytes[i] = (byte) i;
- }
-
- BufferedInputStream in = new BufferedInputStream(
- new ByteArrayInputStream(bytes), 5);
-
- // Read more bytes than are buffered.
- for (int i = 0; i < 10; i++) {
- assertEquals("Test 2: Incorrect byte read;", bytes[i], in.read());
- }
-
- in.close();
- try {
- in.read();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.BufferedInputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks exceptions only.",
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII_Exception() throws IOException {
- BufferedInputStream bis = new BufferedInputStream(null);
-
- try {
- bis.read(null, -1, -1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- //expected
- }
-
- try {
- bis.read(new byte[0], -1, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- bis.read(new byte[0], 1, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- bis.read(new byte[0], 1, 1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- bis.close();
-
- try {
- bis.read(null, -1, -1);
- fail("should throw IOException");
- } catch (IOException e) {
- //expected
- }
- }
-
- /**
- * @tests java.io.BufferedInputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Functional test.",
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII() {
- // Test for method int java.io.BufferedInputStream.read(byte [], int,
- // int)
- byte[] buf1 = new byte[100];
- try {
- is.skip(3000);
- is.mark(1000);
- is.read(buf1, 0, buf1.length);
- assertTrue("Failed to read correct data", new String(buf1, 0,
- buf1.length).equals(fileString.substring(3000, 3100)));
-
- } catch (IOException e) {
- fail("Exception during read test");
- }
-
- BufferedInputStream bufin = new BufferedInputStream(new InputStream() {
- int size = 2, pos = 0;
-
- byte[] contents = new byte[size];
-
- @Override
- public int read() throws IOException {
- if (pos >= size) {
- throw new IOException("Read past end of data");
- }
- return contents[pos++];
- }
-
- @Override
- public int read(byte[] buf, int off, int len) throws IOException {
- if (pos >= size) {
- throw new IOException("Read past end of data");
- }
- int toRead = len;
- if (toRead > available()) {
- toRead = available();
- }
- System.arraycopy(contents, pos, buf, off, toRead);
- pos += toRead;
- return toRead;
- }
-
- @Override
- public int available() {
- return size - pos;
- }
- });
- try {
- bufin.read();
- int result = bufin.read(new byte[2], 0, 2);
- assertTrue("Incorrect result: " + result, result == 1);
- } catch (IOException e) {
- fail("Unexpected: " + e);
- }
- }
-
- /**
- * @tests java.io.BufferedInputStream#skip(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies skip(long n) method.",
- method = "skip",
- args = {long.class}
- )
- public void test_skipJ() {
- // Test for method long java.io.BufferedInputStream.skip(long)
- byte[] buf1 = new byte[10];
- try {
- is.mark(2000);
- is.skip(1000);
- is.read(buf1, 0, buf1.length);
- is.reset();
- assertTrue("Failed to skip to correct position", new String(buf1,
- 0, buf1.length).equals(fileString.substring(1000, 1010)));
- } catch (IOException e) {
- fail("Exception during skip test");
- }
-
- //regression for HARMONY-667
- BufferedInputStream buf = new BufferedInputStream(null, 5);
- try {
- buf.skip(10);
- fail("Should throw IOException");
- } catch (IOException e) {
- //expected
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- @Override
- protected void setUp() {
-
- try {
- fileName = System.getProperty("java.io.tmpdir");
- String separator = System.getProperty("file.separator");
- if (fileName.charAt(fileName.length() - 1) == separator.charAt(0)) {
- fileName = Support_PlatformFile.getNewPlatformFile(fileName,
- "input.tst");
- } else {
- fileName = Support_PlatformFile.getNewPlatformFile(fileName
- + separator, "input.tst");
- }
- OutputStream fos = new FileOutputStream(fileName);
- fos.write(fileString.getBytes());
- fos.close();
- isFile = new FileInputStream(fileName);
- is = new BufferedInputStream(isFile, 1000);
- } catch (IOException e) {
- System.out.println("Exception during setup");
- e.printStackTrace();
- }
-
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- @Override
- protected void tearDown() {
-
- if (is != null) {
- try {
- is.close();
- } catch (Exception e) {
- System.out.println("Exception 1 during BIS tearDown: " + e.getMessage());
- }
- }
- try {
- File f = new File(fileName);
- f.delete();
- } catch (Exception e) {
- System.out.println("Exception 2 during BIS tearDown: " + e.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/BufferedOutputStreamTest.java b/luni/src/test/java/tests/api/java/io/BufferedOutputStreamTest.java
deleted file mode 100644
index 3b727a5..0000000
--- a/luni/src/test/java/tests/api/java/io/BufferedOutputStreamTest.java
+++ /dev/null
@@ -1,253 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.BufferedOutputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-
-import tests.support.Support_OutputStream;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(BufferedOutputStream.class)
-public class BufferedOutputStreamTest extends junit.framework.TestCase {
-
- private java.io.OutputStream os;
-
- java.io.ByteArrayOutputStream baos;
-
- java.io.ByteArrayInputStream bais;
-
- Support_OutputStream sos;
-
- public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_java_io_File\nTest_java_io_FileDescriptor\nTest_java_io_FileInputStream\nTest_java_io_FileNotFoundException\nTest_java_io_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
-
- /**
- * @tests java.io.BufferedOutputStream#BufferedOutputStream(java.io.OutputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "BufferedOutputStream",
- args = {java.io.OutputStream.class}
- )
- public void test_ConstructorLjava_io_OutputStream() {
- try {
- baos = new java.io.ByteArrayOutputStream();
- os = new java.io.BufferedOutputStream(baos);
- os.write(fileString.getBytes(), 0, 500);
- } catch (java.io.IOException e) {
- fail("Constrcutor test failed");
- }
-
- }
-
- /**
- * @tests java.io.BufferedOutputStream#BufferedOutputStream(java.io.OutputStream,
- * int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "IllegalArgumentException checking missed.",
- method = "BufferedOutputStream",
- args = {java.io.OutputStream.class, int.class}
- )
- public void test_ConstructorLjava_io_OutputStreamI() {
- baos = new java.io.ByteArrayOutputStream();
-
- try {
- os = new java.io.BufferedOutputStream(baos, -1);
- fail("Test 1: IllegalArgumentException expected.");
- } catch (IllegalArgumentException e) {
- // Expected.
- }
- try {
- os = new java.io.BufferedOutputStream(baos, 1024);
- os.write(fileString.getBytes(), 0, 500);
- } catch (java.io.IOException e) {
- fail("Test 2: Unexpected IOException.");
- }
- }
-
- /**
- * @tests java.io.BufferedOutputStream#flush()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "flush",
- args = {}
- )
- public void test_flush() throws IOException {
- baos = new ByteArrayOutputStream();
- os = new java.io.BufferedOutputStream(baos, 600);
- os.write(fileString.getBytes(), 0, 500);
- os.flush();
- assertEquals("Test 1: Bytes not written after flush;",
- 500, ((ByteArrayOutputStream) baos).size());
- os.close();
-
- sos = new Support_OutputStream(true);
- os = new BufferedOutputStream(sos, 10);
- try {
- os.flush();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- // To avoid exception during tearDown().
- sos.setThrowsException(false);
- }
-
- /**
- * @tests java.io.BufferedOutputStream#write(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "write",
- args = {byte[].class, int.class, int.class}
- )
- public void test_write$BII() throws IOException {
- os = new java.io.BufferedOutputStream(
- baos = new java.io.ByteArrayOutputStream(),512);
- os.write(fileString.getBytes(), 0, 500);
- bais = new java.io.ByteArrayInputStream(baos.toByteArray());
- assertEquals("Test 1: Bytes written, not buffered;",
- 0, bais.available());
- os.flush();
- bais = new java.io.ByteArrayInputStream(baos.toByteArray());
- assertEquals("Test 2: Bytes not written after flush;",
- 500, bais.available());
- os.write(fileString.getBytes(), 500, 513);
- bais = new java.io.ByteArrayInputStream(baos.toByteArray());
- assertTrue("Test 3: Bytes not written when buffer full.",
- bais.available() >= 1000);
- byte[] wbytes = new byte[1013];
- bais.read(wbytes, 0, 1013);
- assertTrue("Test 4: Incorrect bytes written or read.",
- fileString.substring(0, 1013).equals(
- new String(wbytes, 0, wbytes.length)));
- os.close();
-
- sos = new Support_OutputStream(true);
- os = new BufferedOutputStream(sos, 10);
- try {
- os.write(fileString.getBytes(), 0, 500);
- fail("Test 5: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- // To avoid exception during tearDown().
- sos.setThrowsException(false);
- }
-
- /**
- * @tests java.io.BufferedOutputStream#write(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "write",
- args = {byte[].class, int.class, int.class}
- )
- public void test_write$BII_Exception() throws IOException {
- OutputStream bos = new BufferedOutputStream(new ByteArrayOutputStream());
- byte[] nullByteArray = null;
- byte[] byteArray = new byte[10];
-
- try {
- bos.write(nullByteArray, 0, 1);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
-
- try {
- bos.write(byteArray, -1, 1);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- bos.write(byteArray, 0, -1);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- bos.write(byteArray, 1, 10);
- fail("Test 4: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.io.BufferedOutputStream#write(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "write",
- args = {int.class}
- )
- public void test_writeI() throws IOException {
- baos = new java.io.ByteArrayOutputStream();
- os = new java.io.BufferedOutputStream(baos);
- os.write('t');
- bais = new java.io.ByteArrayInputStream(baos.toByteArray());
- assertEquals("Test 1: Byte written, not buffered;",
- 0, bais.available());
- os.flush();
- bais = new java.io.ByteArrayInputStream(baos.toByteArray());
- assertEquals("Test 2: Byte not written after flush;",
- 1, bais.available());
- byte[] wbytes = new byte[1];
- bais.read(wbytes, 0, 1);
- assertEquals("Test 3: Incorrect byte written or read;",
- 't', wbytes[0]);
- os.close();
-
- sos = new Support_OutputStream(true);
- os = new BufferedOutputStream(sos, 1);
- os.write('t');
- try {
- // Exception is only thrown when the buffer is flushed.
- os.write('e');
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- // To avoid exception during tearDown().
- sos.setThrowsException(false);
- }
-
- protected void tearDown() {
- try {
- if (bais != null)
- bais.close();
- if (os != null)
- os.close();
- if (baos != null)
- baos.close();
- } catch (Exception e) {
- System.out.println("Exception during tearDown" + e.toString());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/BufferedReaderTest.java b/luni/src/test/java/tests/api/java/io/BufferedReaderTest.java
deleted file mode 100644
index b1a5755..0000000
--- a/luni/src/test/java/tests/api/java/io/BufferedReaderTest.java
+++ /dev/null
@@ -1,515 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.CharArrayReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.PipedReader;
-import java.io.Reader;
-
-import tests.support.Support_ASimpleReader;
-import tests.support.Support_StringReader;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(BufferedReader.class)
-public class BufferedReaderTest extends junit.framework.TestCase {
-
- BufferedReader br;
-
- String testString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_java_io_File\nTest_java_io_FileDescriptor\nTest_java_io_FileInputStream\nTest_java_io_FileNotFoundException\nTest_java_io_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
-
- /**
- * @tests java.io.BufferedReader#BufferedReader(java.io.Reader)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "BufferedReader",
- args = {java.io.Reader.class}
- )
- public void test_ConstructorLjava_io_Reader() {
- // Test for method java.io.BufferedReader(java.io.Reader)
- br = new BufferedReader(new Support_StringReader(testString));
- assertNotNull(br);
- }
-
- /**
- * @tests java.io.BufferedReader#BufferedReader(java.io.Reader, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "BufferedReader",
- args = {java.io.Reader.class, int.class}
- )
- public void test_ConstructorLjava_io_ReaderI() {
- // Illegal negative size argument test.
- try {
- br = new BufferedReader(new Support_StringReader(testString), 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException expected) {
- }
- br = new BufferedReader(new Support_StringReader(testString), 1024);
- assertNotNull(br);
- }
-
- /**
- * @tests java.io.BufferedReader#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "close",
- args = {}
- )
- public void test_close() {
- Support_ASimpleReader ssr = new Support_ASimpleReader(true);
- try {
- br = new BufferedReader(new Support_StringReader(testString));
- br.close();
- br.read();
- fail("Test 1: Read on closed stream.");
- } catch (IOException x) {
- // Expected.
- } catch (Exception e) {
- fail("Exception during close test " + e.toString());
- }
-
- br = new BufferedReader(ssr);
- try {
- br.close();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- // Avoid IOException in tearDown().
- ssr.throwExceptionOnNextUse = false;
- }
-
- /**
- * @tests java.io.BufferedReader#mark(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "mark",
- args = {int.class}
- )
- public void test_markI() {
- // Test for method void java.io.BufferedReader.mark(int)
- char[] buf = null;
- try {
- br = new BufferedReader(new Support_StringReader(testString));
- br.skip(500);
- br.mark(1000);
- br.skip(250);
- br.reset();
- buf = new char[testString.length()];
- br.read(buf, 0, 500);
- assertTrue("Failed to set mark properly", testString.substring(500,
- 1000).equals(new String(buf, 0, 500)));
- } catch (java.io.IOException e) {
- fail("Exception during mark test");
- }
- try {
- br = new BufferedReader(new Support_StringReader(testString), 800);
- br.skip(500);
- br.mark(250);
- br.read(buf, 0, 1000);
- br.reset();
- fail("Failed to invalidate mark properly");
- } catch (IOException x) {
- }
-
- char[] chars = new char[256];
- for (int i = 0; i < 256; i++)
- chars[i] = (char) i;
- Reader in = new BufferedReader(new Support_StringReader(new String(
- chars)), 12);
- try {
- in.skip(6);
- in.mark(14);
- in.read(new char[14], 0, 14);
- in.reset();
- assertTrue("Wrong chars", in.read() == (char) 6
- && in.read() == (char) 7);
- } catch (IOException e) {
- fail("Exception during mark test 2:" + e);
- }
-
- in = new BufferedReader(new Support_StringReader(new String(chars)), 12);
- try {
- in.skip(6);
- in.mark(8);
- in.skip(7);
- in.reset();
- assertTrue("Wrong chars 2", in.read() == (char) 6
- && in.read() == (char) 7);
- } catch (IOException e) {
- fail("Exception during mark test 3:" + e);
- }
- }
-
- /**
- * @tests java.io.BufferedReader#markSupported()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "markSupported",
- args = {}
- )
- public void test_markSupported() {
- // Test for method boolean java.io.BufferedReader.markSupported()
- br = new BufferedReader(new Support_StringReader(testString));
- assertTrue("markSupported returned false.", br.markSupported());
- }
-
- /**
- * @tests java.io.BufferedReader#read()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "read",
- args = {}
- )
- public void test_read() throws IOException {
- Support_ASimpleReader ssr = new Support_ASimpleReader(true);
- try {
- br = new BufferedReader(new Support_StringReader(testString));
- int r = br.read();
- assertTrue("Char read improperly", testString.charAt(0) == r);
- br = new BufferedReader(new Support_StringReader(new String(
- new char[] { '\u8765' })));
- assertTrue("Wrong double byte character", br.read() == '\u8765');
- } catch (java.io.IOException e) {
- fail("Exception during read test");
- }
-
- char[] chars = new char[256];
- for (int i = 0; i < 256; i++)
- chars[i] = (char) i;
- Reader in = new BufferedReader(new Support_StringReader(new String(
- chars)), 12);
- try {
- assertEquals("Wrong initial char", 0, in.read()); // Fill the
- // buffer
- char[] buf = new char[14];
- in.read(buf, 0, 14); // Read greater than the buffer
- assertTrue("Wrong block read data", new String(buf)
- .equals(new String(chars, 1, 14)));
- assertEquals("Wrong chars", 15, in.read()); // Check next byte
- } catch (IOException e) {
- fail("Exception during read test 2:" + e);
- }
-
- // regression test for HARMONY-841
- assertTrue(new BufferedReader(new CharArrayReader(new char[5], 1, 0), 2).read() == -1);
-
- br.close();
- br = new BufferedReader(ssr);
- try {
- br.read();
- fail("IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- // Avoid IOException in tearDown().
- ssr.throwExceptionOnNextUse = false;
- }
-
- /**
- * @tests java.io.BufferedReader#read(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "The test verifies read(char[] cbuf, int off, int len) method.",
- method = "read",
- args = {char[].class, int.class, int.class}
- )
- public void test_read$CII() throws Exception {
- char[] ca = new char[2];
- BufferedReader toRet = new BufferedReader(new InputStreamReader(
- new ByteArrayInputStream(new byte[0])));
- try {
- toRet.close();
- } catch (IOException e) {
- fail("unexpected 1: " + e);
- }
-
- /* Closed reader should throw IOException reading zero bytes */
- try {
- toRet.read(ca, 0, 0);
- fail("Reading zero bytes on a closed reader should not work");
- } catch (IOException e) {
- // expected
- }
-
- // Test to ensure that a drained stream returns 0 at EOF
- toRet = new BufferedReader(new InputStreamReader(
- new ByteArrayInputStream(new byte[2])));
- try {
- assertEquals("Emptying the reader should return two bytes", 2,
- toRet.read(ca, 0, 2));
- assertEquals("EOF on a reader should be -1", -1, toRet.read(ca, 0,
- 2));
- assertEquals("Reading zero bytes at EOF should work", 0, toRet
- .read(ca, 0, 0));
- } catch (IOException ex) {
- fail("Unexpected IOException : " + ex.getLocalizedMessage());
- }
-
- // Test for method int java.io.BufferedReader.read(char [], int, int)
- try {
- char[] buf = new char[testString.length()];
- br = new BufferedReader(new Support_StringReader(testString));
- br.read(buf, 50, 500);
- assertTrue("Chars read improperly", new String(buf, 50, 500)
- .equals(testString.substring(0, 500)));
-
- br = new BufferedReader(new Support_StringReader(testString));
- assertEquals(0, br.read(buf, 0, 0));
- assertEquals(buf.length, br.read(buf, 0, buf.length));
- assertEquals(0, br.read(buf, buf.length, 0));
- } catch (java.io.IOException e) {
- fail("Exception during read test");
- }
-
- BufferedReader bufin = new BufferedReader(new Reader() {
- int size = 2, pos = 0;
-
- char[] contents = new char[size];
-
- public int read() throws IOException {
- if (pos >= size)
- throw new IOException("Read past end of data");
- return contents[pos++];
- }
-
- public int read(char[] buf, int off, int len) throws IOException {
- if (pos >= size)
- throw new IOException("Read past end of data");
- int toRead = len;
- if (toRead > (size - pos))
- toRead = size - pos;
- System.arraycopy(contents, pos, buf, off, toRead);
- pos += toRead;
- return toRead;
- }
-
- public boolean ready() throws IOException {
- return size - pos > 0;
- }
-
- public void close() throws IOException {
- }
- });
- try {
- bufin.read();
- int result = bufin.read(new char[2], 0, 2);
- assertTrue("Incorrect result: " + result, result == 1);
- } catch (IOException e) {
- fail("Unexpected: " + e);
- }
- }
-
- /**
- * @tests java.io.BufferedReader#read(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "The test verifies read(char[] cbuf, int off, int len) method.",
- method = "read",
- args = {char[].class, int.class, int.class}
- )
- public void test_read$CII_Exception() throws Exception {
- br = new BufferedReader(new Support_StringReader(testString));
- try{
- br.read(new char[10], -1, 1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try{
- br.read(new char[10], 0, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try{
- br.read(new char[10], 10, 1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- //regression for HARMONY-831
- try{
- new BufferedReader(new PipedReader(), 9).read(new char[] {}, 7, 0);
- fail("should throw IndexOutOfBoundsException");
- }catch(IndexOutOfBoundsException e){
- }
- }
-
- /**
- * @tests java.io.BufferedReader#readLine()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "readLine",
- args = {}
- )
- public void test_readLine() throws IOException {
- String line;
- br = new BufferedReader(new Support_StringReader("Lorem\nipsum\rdolor sit amet..."));
-
- line = br.readLine();
- assertTrue("Test 1: Incorrect line written or read: " + line,
- line.equals("Lorem"));
- line = br.readLine();
- assertTrue("Test 2: Incorrect line written or read: " + line,
- line.equals("ipsum"));
- line = br.readLine();
- assertTrue("Test 3: Incorrect line written or read: " + line,
- line.equals("dolor sit amet..."));
-
- br.close();
- try {
- br.readLine();
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.BufferedReader#ready()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "ready",
- args = {}
- )
- public void test_ready() throws IOException {
- Support_ASimpleReader ssr = new Support_ASimpleReader(true);
- try {
- br = new BufferedReader(new Support_StringReader(testString));
- assertTrue("Test 1: ready() returned false", br.ready());
- } catch (java.io.IOException e) {
- fail("Exception during ready test" + e.toString());
- }
-
- br.close();
- br = new BufferedReader(ssr);
- try {
- br.close();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- // Avoid IOException in tearDown().
- ssr.throwExceptionOnNextUse = false;
- }
-
- /**
- * @tests java.io.BufferedReader#reset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "The test verifies reset() method.",
- method = "reset",
- args = {}
- )
- public void test_reset() {
- // Test for method void java.io.BufferedReader.reset()
- try {
- br = new BufferedReader(new Support_StringReader(testString));
- br.skip(500);
- br.mark(900);
- br.skip(500);
- br.reset();
- char[] buf = new char[testString.length()];
- br.read(buf, 0, 500);
- assertTrue("Failed to reset properly", testString.substring(500,
- 1000).equals(new String(buf, 0, 500)));
- } catch (java.io.IOException e) {
- fail("Exception during reset test");
- }
- try {
- br = new BufferedReader(new Support_StringReader(testString));
- br.skip(500);
- br.reset();
- fail("Reset succeeded on unmarked stream");
- } catch (IOException x) {
- return;
-
- }
-
- }
-
- /**
- * @tests java.io.BufferedReader#skip(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "skip",
- args = {long.class}
- )
- public void test_skipJ() throws IOException {
- Support_ASimpleReader ssr = new Support_ASimpleReader(true);
- br = new BufferedReader(new Support_StringReader(testString));
-
- try {
- br.skip(-1);
- fail("Test 1: IllegalArgumentException expected.");
- } catch (IllegalArgumentException e) {
- // Expected.
- }
-
- br.skip(500);
- char[] buf = new char[testString.length()];
- br.read(buf, 0, 500);
- assertTrue("Test 2: Failed to set skip properly.",
- testString.substring(500, 1000).equals(
- new String(buf, 0, 500)));
-
- br.close();
- br = new BufferedReader(ssr);
- try {
- br.skip(1);
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- // Avoid IOException in tearDown().
- ssr.throwExceptionOnNextUse = false;
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- try {
- br.close();
- } catch (Exception e) {
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/BufferedWriterTest.java b/luni/src/test/java/tests/api/java/io/BufferedWriterTest.java
deleted file mode 100644
index d8ea5a8..0000000
--- a/luni/src/test/java/tests/api/java/io/BufferedWriterTest.java
+++ /dev/null
@@ -1,412 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.BufferedWriter;
-import java.io.IOException;
-
-import tests.support.Support_ASimpleWriter;
-import tests.support.Support_StringWriter;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(BufferedWriter.class)
-public class BufferedWriterTest extends junit.framework.TestCase {
-
- BufferedWriter bw;
-
- Support_StringWriter sw;
-
- Support_ASimpleWriter ssw;
-
- public String testString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_java_io_File\nTest_java_io_FileDescriptor\nTest_java_io_FileInputStream\nTest_java_io_FileNotFoundException\nTest_java_io_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
-
- /**
- * @tests java.io.BufferedWriter#BufferedWriter(java.io.Writer)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "BufferedWriter",
- args = {java.io.Writer.class}
- )
- public void test_ConstructorLjava_io_Writer() {
- bw = new BufferedWriter(sw);
- try {
- bw.write("Hi", 0, 2);
- assertTrue("Test 1: Buffering failed.", sw.toString().equals(""));
- bw.flush();
- assertEquals("Test 2: Incorrect value;", "Hi", sw.toString());
- } catch (IOException e) {
- fail("Test 3: Unexpected IOException.");
- }
- }
-
- /**
- * @tests java.io.BufferedWriter#BufferedWriter(java.io.Writer, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "BufferedWriter",
- args = {java.io.Writer.class, int.class}
- )
- public void test_ConstructorLjava_io_WriterI() {
- try {
- bw = new BufferedWriter(sw, 0);
- fail("Test 1: IllegalArgumentException expected.");
- } catch (IllegalArgumentException expected) {
- // Expected.
- }
-
- bw = new BufferedWriter(sw, 10);
- try {
- bw.write("Hi", 0, 2);
- assertTrue("Test 2: Buffering failed.", sw.toString().equals(""));
- bw.flush();
- assertEquals("Test 3: Incorrect value;", "Hi", sw.toString());
- } catch (IOException e) {
- fail("Test 4: Unexpected IOException.");
- }
- }
-
- /**
- * @tests java.io.BufferedWriter#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "close",
- args = {}
- )
- public void test_close() {
- // Test for method void java.io.BufferedWriter.close()
- try {
- bw.close();
- bw.write(testString);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- assertFalse("Test 2: Write after close.", sw.toString().equals(testString));
-
- bw = new BufferedWriter(ssw);
- try {
- bw.close();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.BufferedWriter#flush()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "flush",
- args = {}
- )
- public void test_flush() throws IOException {
- bw.write("This should not cause a flush");
- assertTrue("Test 1: Bytes written without flush.",
- sw.toString().equals(""));
- bw.flush();
- assertEquals("Test 2: Bytes not flushed.",
- "This should not cause a flush", sw.toString());
-
- bw.close();
- bw = new BufferedWriter(ssw);
- try {
- bw.flush();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.BufferedWriter#newLine()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "newLine",
- args = {}
- )
- public void test_newLine() throws IOException {
- String separator = System.getProperty("line.separator");
- bw.write("Hello");
- bw.newLine();
- bw.write("World");
- bw.flush();
- assertTrue("Test 1: Incorrect string written: " + sw.toString(),
- sw.toString().equals("Hello" + separator + "World"));
-
- bw.close();
- bw = new BufferedWriter(ssw, 1);
- try {
- bw.newLine();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.BufferedWriter#write(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "write",
- args = {char[].class, int.class, int.class}
- )
- public void test_write$CII() {
- // Test for method void java.io.BufferedWriter.write(char [], int, int)
- try {
- char[] testCharArray = testString.toCharArray();
- bw.write(testCharArray, 500, 1000);
- bw.flush();
- assertTrue("Incorrect string written", sw.toString().equals(
- testString.substring(500, 1500)));
-
- int idx = sw.toString().length();
- bw.write(testCharArray, 0, testCharArray.length);
- assertEquals(idx + testCharArray.length, sw.toString().length());
- bw.write(testCharArray, 0, 0);
- assertEquals(idx + testCharArray.length, sw.toString().length());
- bw.write(testCharArray, testCharArray.length, 0);
- assertEquals(idx + testCharArray.length, sw.toString().length());
- } catch (Exception e) {
- fail("Exception during write test");
- }
-
- }
-
- /**
- * @tests java.io.BufferedWriter#write(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Illegal argument tests.",
- method = "write",
- args = {char[].class, int.class, int.class}
- )
- public void test_write$CII_Exception() throws IOException {
- char[] nullCharArray = null;
- char[] charArray = testString.toCharArray();
-
- try {
- bw.write(nullCharArray, 0, 1);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
-
- try {
- bw.write(charArray, -1, 0);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- bw.write(charArray, 0, -1);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- bw.write(charArray, charArray.length + 1, 0);
- fail("Test 4: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- bw.write(charArray, charArray.length, 1);
- fail("Test 5: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- bw.write(charArray, 0, charArray.length + 1);
- fail("Test 6: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- bw.write(charArray, 1, charArray.length);
- fail("Test 7: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- bw.close();
-
- try {
- bw.write(charArray, 0, 1);
- fail("Test 7: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- bw = new BufferedWriter(ssw, charArray.length / 2);
- try {
- bw.write(charArray, 0, charArray.length);
- fail("Test 8: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.BufferedWriter#write(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "write",
- args = {int.class}
- )
- public void test_writeI() throws IOException {
- bw.write('T');
- assertTrue("Test 1: Char written without flush.",
- sw.toString().equals(""));
- bw.flush();
- assertEquals("Test 2: Incorrect char written;",
- "T", sw.toString());
-
- bw.close();
- try {
- bw.write('E');
- fail("Test 3: IOException expected since the target writer is closed.");
- } catch (IOException e) {
- // Expected.
- }
-
- // IOException should be thrown when the buffer is full and data is
- // written out to the target writer.
- bw = new BufferedWriter(ssw, 1);
- bw.write('S');
- try {
- bw.write('T');
- fail("Test 4: IOException expected since the target writer throws it.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.BufferedWriter#write(java.lang.String, int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "write",
- args = {java.lang.String.class, int.class, int.class}
- )
- public void test_writeLjava_lang_StringII() {
- // Test for method void java.io.BufferedWriter.write(java.lang.String,
- // int, int)
- try {
- bw.write(testString);
- bw.flush();
- assertTrue("Incorrect string written", sw.toString().equals(
- testString));
- } catch (Exception e) {
- fail("Exception during write test");
- }
- }
-
- /**
- * @tests java.io.BufferedWriter#write(java.lang.String, int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Illegal argument checking.",
- method = "write",
- args = {java.lang.String.class, int.class, int.class}
- )
- public void test_writeLjava_lang_StringII_Exception() throws IOException {
-
- bw.write((String) null , -1, -1);
- bw.write((String) null , -1, 0);
- bw.write((String) null , 0 , -1);
- bw.write((String) null , 0 , 0);
-
- try {
- bw.write((String) null, 0, 1);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
-
- try {
- bw.write(testString, -1, 1);
- fail("Test 2: StringIndexOutOfBoundsException expected.");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- bw.write(testString, 1, testString.length());
- fail("Test 3: StringIndexOutOfBoundsException expected.");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected.
- }
-
- bw.close();
-
- try {
- bw.write(testString, 0, 1);
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- bw = new BufferedWriter(ssw, testString.length() / 2);
- try {
- bw.write(testString, 0, testString.length());
- fail("Test 5: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- sw = new Support_StringWriter();
- ssw = new Support_ASimpleWriter(true);
- bw = new BufferedWriter(sw, 500);
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
-
- ssw.throwExceptionOnNextUse = false;
- try {
- bw.close();
- } catch (Exception e) {
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/ByteArrayInputStreamTest.java b/luni/src/test/java/tests/api/java/io/ByteArrayInputStreamTest.java
deleted file mode 100644
index eaf4c48..0000000
--- a/luni/src/test/java/tests/api/java/io/ByteArrayInputStreamTest.java
+++ /dev/null
@@ -1,325 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(ByteArrayInputStream.class)
-public class ByteArrayInputStreamTest extends junit.framework.TestCase {
-
- private ByteArrayInputStream is;
-
- public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\n";
-
- /**
- * @tests java.io.ByteArrayInputStream#ByteArrayInputStream(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "ByteArrayInputStream",
- args = {byte[].class}
- )
- public void test_Constructor$B() {
- // Test for method java.io.ByteArrayInputStream(byte [])
-
- java.io.InputStream bis = new java.io.ByteArrayInputStream(fileString
- .getBytes());
-
- try {
- assertTrue("Unable to create ByteArrayInputStream",
- bis.available() == fileString.length());
- } catch (Exception e) {
- System.out.println("Exception during Constructor test");
- }
- }
-
- /**
- * @throws IOException
- * @tests java.io.ByteArrayInputStream#ByteArrayInputStream(byte[], int,
- * int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "ByteArrayInputStream",
- args = {byte[].class, int.class, int.class}
- )
- public void test_Constructor$BII() throws IOException {
- // Test for method java.io.ByteArrayInputStream(byte [], int, int)
-
- byte[] zz = fileString.getBytes();
- java.io.InputStream bis = new java.io.ByteArrayInputStream(zz, 0, 100);
-
- try {
- assertEquals("Unable to create ByteArrayInputStream",
- 100, bis.available());
- } catch (Exception e) {
- fail("Exception during Constructor test");
- }
-
- // Regression test for Harmony-2405
- new SubByteArrayInputStream(new byte[] { 1, 2 }, 444, 13);
- assertEquals(444, SubByteArrayInputStream.pos);
- assertEquals(444, SubByteArrayInputStream.mark);
- assertEquals(2, SubByteArrayInputStream.count);
- }
-
- static class SubByteArrayInputStream extends ByteArrayInputStream {
- public static byte[] buf;
-
- public static int mark, pos, count;
-
- SubByteArrayInputStream(byte[] buf, int offset, int length)
- throws IOException {
- super(buf, offset, length);
- buf = super.buf;
- mark = super.mark;
- pos = super.pos;
- count = super.count;
- }
- }
-
- /**
- * @tests java.io.ByteArrayInputStream#available()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies available() method.",
- method = "available",
- args = {}
- )
- public void test_available() {
- // Test for method int java.io.ByteArrayInputStream.available()
- try {
- assertTrue("Returned incorrect number of available bytes", is
- .available() == fileString.length());
- } catch (Exception e) {
- fail("Exception during available test");
- }
- }
-
- /**
- * @tests java.io.ByteArrayInputStream#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "close",
- args = {}
- )
- public void test_close() {
- is.read();
- try {
- is.close();
- } catch (java.io.IOException e) {
- fail("Test 1: Failed to close the input stream.");
- }
- try {
- is.read();
- } catch (Exception e) {
- fail("Test 2: Should be able to read from closed stream.");
- }
- }
-
- /**
- * @tests java.io.ByteArrayInputStream#mark(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies mark(int readAheadLimit) method.",
- method = "mark",
- args = {int.class}
- )
- public void test_markI() {
- // Test for method void java.io.ByteArrayInputStream.mark(int)
- byte[] buf1 = new byte[100];
- byte[] buf2 = new byte[100];
- try {
- is.skip(3000);
- is.mark(1000);
- is.read(buf1, 0, buf1.length);
- is.reset();
- is.read(buf2, 0, buf2.length);
- is.reset();
- assertTrue("Failed to mark correct position", new String(buf1, 0,
- buf1.length).equals(new String(buf2, 0, buf2.length)));
-
- } catch (Exception e) {
- fail("Exception during mark test");
- }
-
- }
-
- /**
- * @tests java.io.ByteArrayInputStream#markSupported()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies markSupported() method.",
- method = "markSupported",
- args = {}
- )
- public void test_markSupported() {
- // Test for method boolean java.io.ByteArrayInputStream.markSupported()
- assertTrue("markSupported returned incorrect value", is.markSupported());
- }
-
- /**
- * @tests java.io.ByteArrayInputStream#read()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies read() method.",
- method = "read",
- args = {}
- )
- public void test_read() {
- // Test for method int java.io.ByteArrayInputStream.read()
- try {
-
- int c = is.read();
- is.reset();
- assertTrue("read returned incorrect char", c == fileString
- .charAt(0));
- } catch (Exception e) {
- fail("Exception during read test");
- }
- }
-
- /**
- * @tests java.io.ByteArrayInputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII() throws IOException {
- byte[] buf1 = new byte[20];
- is.skip(50);
- is.mark(100);
- is.read(buf1, 0, buf1.length);
- assertTrue("Test 1: Failed to read correct data.",
- new String(buf1, 0, buf1.length).equals(
- fileString.substring(50, 70)));
-
- // Illegal argument checks.
- try {
- is.read(null, 1, 0);
- fail("Test 2: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
-
- try {
- is.read(buf1 , -1, 1);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- is.read(buf1 , 1, -1);
- fail("Test 4: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- is.read(buf1, 1, buf1.length);
- fail("Test 5: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.io.ByteArrayInputStream#reset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "The test verifies reset() method.",
- method = "reset",
- args = {}
- )
- public void test_reset() {
- // Test for method void java.io.ByteArrayInputStream.reset()
- byte[] buf1 = new byte[10];
- byte[] buf2 = new byte[10];
- try {
- is.mark(200);
- is.read(buf1, 0, 10);
- is.reset();
- is.read(buf2, 0, 10);
- is.reset();
- assertTrue("Reset failed", new String(buf1, 0, buf1.length)
- .equals(new String(buf2, 0, buf2.length)));
- } catch (Exception e) {
- fail("Exception during reset test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.ByteArrayInputStream#skip(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "skip",
- args = {long.class}
- )
- public void test_skipJ() {
- // Test for method long java.io.ByteArrayInputStream.skip(long)
- byte[] buf1 = new byte[10];
- try {
- is.skip(100);
- is.read(buf1, 0, buf1.length);
- assertTrue("Failed to skip to correct position", new String(buf1,
- 0, buf1.length).equals(fileString.substring(100, 110)));
- } catch (Exception e) {
- fail("Exception during skip test : " + e.getMessage());
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
-
- is = new java.io.ByteArrayInputStream(fileString.getBytes());
-
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
-
- try {
- is.close();
-
- } catch (Exception e) {
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/ByteArrayOutputStreamTest.java b/luni/src/test/java/tests/api/java/io/ByteArrayOutputStreamTest.java
deleted file mode 100644
index b2a4e21..0000000
--- a/luni/src/test/java/tests/api/java/io/ByteArrayOutputStreamTest.java
+++ /dev/null
@@ -1,327 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-
-import junit.framework.TestCase;
-import tests.support.Support_OutputStream;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-/**
- * Automated Test Suite for class java.io.ByteArrayOutputStream
- *
- * @see java.io.ByteArrayOutputStream
- */
-@TestTargetClass(ByteArrayOutputStream.class)
-public class ByteArrayOutputStreamTest extends TestCase {
-
- ByteArrayOutputStream bos = null;
-
- public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_ByteArrayOutputStream\nTest_java_io_DataInputStream\n";
-
- /**
- * @tests java.io.ByteArrayOutputStream#ByteArrayOutputStream(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "ByteArrayOutputStream",
- args = {int.class}
- )
- public void test_ConstructorI() {
- bos = new java.io.ByteArrayOutputStream(100);
- assertEquals("Test 1: Failed to create stream;", 0, bos.size());
-
- try {
- bos = new ByteArrayOutputStream(-1);
- fail("Test 2: IllegalArgumentException expected.");
- } catch (IllegalArgumentException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ByteArrayOutputStream#ByteArrayOutputStream()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "ByteArrayOutputStream",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.io.ByteArrayOutputStream()
- bos = new java.io.ByteArrayOutputStream();
- assertEquals("Failed to create stream", 0, bos.size());
- }
-
- /**
- * @tests java.io.ByteArrayOutputStream#close()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "No IOException check since it is never thrown.",
- method = "close",
- args = {}
- )
- public void test_close() {
- // Test for method void java.io.ByteArrayOutputStream.close()
-
- assertTrue(
- "close() does nothing for this implementation of OutputSteam",
- true);
-
- // The spec seems to say that a closed output stream can't be written
- // to. We don't throw an exception if attempt is made to write.
- // Right now our implementation doesn't do anything testable but
- // should we decide to throw an exception if a closed stream is
- // written to, the appropriate test is commented out below.
-
- /***********************************************************************
- * java.io.ByteArrayOutputStream bos = new
- * java.io.ByteArrayOutputStream(); bos.write (fileString.getBytes(), 0,
- * 100); try { bos.close(); } catch (java.io.IOException e) {
- * fail("IOException closing stream"); } try { bos.write
- * (fileString.getBytes(), 0, 100); bos.toByteArray(); fail("Wrote
- * to closed stream"); } catch (Exception e) { }
- **********************************************************************/
- }
-
- /**
- * @tests java.io.ByteArrayOutputStream#reset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "reset",
- args = {}
- )
- public void test_reset() {
- // Test for method void java.io.ByteArrayOutputStream.reset()
- bos = new java.io.ByteArrayOutputStream();
- bos.write(fileString.getBytes(), 0, 100);
- bos.reset();
- assertEquals("Test 1: Reset failed;", 0, bos.size());
- }
-
- /**
- * @tests java.io.ByteArrayOutputStream#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies size() method.",
- method = "size",
- args = {}
- )
- public void test_size() {
- // Test for method int java.io.ByteArrayOutputStream.size()
- bos = new java.io.ByteArrayOutputStream();
- bos.write(fileString.getBytes(), 0, 100);
- assertEquals("size test failed", 100, bos.size());
- bos.reset();
- assertEquals("size test failed", 0, bos.size());
- }
-
- /**
- * @tests java.io.ByteArrayOutputStream#toByteArray()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies toByteArray() method.",
- method = "toByteArray",
- args = {}
- )
- public void test_toByteArray() {
- // Test for method byte [] java.io.ByteArrayOutputStream.toByteArray()
- byte[] bytes;
- byte[] sbytes = fileString.getBytes();
- bos = new java.io.ByteArrayOutputStream();
- bos.write(fileString.getBytes(), 0, fileString.length());
- bytes = bos.toByteArray();
- for (int i = 0; i < fileString.length(); i++) {
- assertTrue("Error in byte array", bytes[i] == sbytes[i]);
- }
- }
-
- /**
- * @tests java.io.ByteArrayOutputStream#toString(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "toString",
- args = {java.lang.String.class}
- )
- public void test_toStringLjava_lang_String() throws Exception {
- bos = new ByteArrayOutputStream();
-
- bos.write(fileString.getBytes(), 0, fileString.length());
- assertTrue("Test 1: Returned incorrect 8859-1 String",
- bos.toString("8859_1").equals(fileString));
- assertTrue("Test 2: Returned incorrect 8859-2 String",
- bos.toString("8859_2").equals(fileString));
-
- try {
- bos.toString("NotAnEcoding");
- fail("Test 3: UnsupportedEncodingException expected.");
- } catch (UnsupportedEncodingException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ByteArrayOutputStream#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies toString() method.",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String
- // java.io.ByteArrayOutputStream.toString()
- java.io.ByteArrayOutputStream bos = null;
- bos = new java.io.ByteArrayOutputStream();
- bos.write(fileString.getBytes(), 0, fileString.length());
- assertTrue("Returned incorrect String", bos.toString().equals(
- fileString));
- }
-
- /**
- * @tests java.io.ByteArrayOutputStream#toString(int)
- */
- @SuppressWarnings("deprecation")
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies toString(int hibyte) method.",
- method = "toString",
- args = {int.class}
- )
- public void test_toStringI() {
- // Test for method java.lang.String
- // java.io.ByteArrayOutputStream.toString(int)
- java.io.ByteArrayOutputStream bos = null;
- bos = new java.io.ByteArrayOutputStream();
- bos.write(fileString.getBytes(), 0, fileString.length());
- assertTrue("Returned incorrect String",
- bos.toString(5).length() == fileString.length());
- }
-
- /**
- * @tests java.io.ByteArrayOutputStream#write(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {int.class}
- )
- public void test_writeI() {
- // Test for method void java.io.ByteArrayOutputStream.write(int)
- bos = new java.io.ByteArrayOutputStream();
- bos.write('t');
- byte[] result = bos.toByteArray();
- assertEquals("Wrote incorrect bytes",
- "t", new String(result, 0, result.length));
- }
-
- /**
- * @tests java.io.ByteArrayOutputStream#write(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "write",
- args = {byte[].class, int.class, int.class}
- )
- public void test_write$BII() {
- // Test for method void java.io.ByteArrayOutputStream.write(byte [],
- // int, int)
- java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
- bos.write(fileString.getBytes(), 0, 100);
- byte[] result = bos.toByteArray();
- assertTrue("Wrote incorrect bytes",
- new String(result, 0, result.length).equals(fileString
- .substring(0, 100)));
- }
-
- /**
- * @tests java.io.ByteArrayOutputStream#write(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Illegal argument checks.",
- method = "write",
- args = {byte[].class, int.class, int.class}
- )
- public void test_write$BII_Exception() {
- byte[] target = new byte[10];
- bos = new ByteArrayOutputStream();
- try {
- bos.write(target, -1, 1);
- fail("Test 1: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- bos.write(target, 0, -1);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- bos.write(target, 1, target.length);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- bos.write(null, 1, 1);
- fail("Test 4: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ByteArrayOutputStream#writeTo(java.io.OutputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "writeTo",
- args = {java.io.OutputStream.class}
- )
- public void test_writeToLjava_io_OutputStream() throws Exception {
- Support_OutputStream sos = new Support_OutputStream();
- bos = new java.io.ByteArrayOutputStream();
- bos.write(fileString.getBytes(), 0, 10);
- bos.writeTo(sos);
- assertTrue("Test 1: Incorrect string written.",
- sos.toString().equals(
- fileString.substring(0, 10)));
-
- sos.setThrowsException(true);
- try {
- bos.writeTo(sos);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/CharArrayReaderTest.java b/luni/src/test/java/tests/api/java/io/CharArrayReaderTest.java
deleted file mode 100644
index e94f74b..0000000
--- a/luni/src/test/java/tests/api/java/io/CharArrayReaderTest.java
+++ /dev/null
@@ -1,342 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.CharArrayReader;
-import java.io.IOException;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(CharArrayReader.class)
-public class CharArrayReaderTest extends junit.framework.TestCase {
-
- char[] hw = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
-
- CharArrayReader cr;
-
- /**
- * @tests java.io.CharArrayReader#CharArrayReader(char[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies CharArrayReader(char[] buf) constructor.",
- method = "CharArrayReader",
- args = {char[].class}
- )
- public void test_Constructor$C() {
- // Test for method java.io.CharArrayReader(char [])
-
- try {
- cr = new CharArrayReader(hw);
- assertTrue("Failed to create reader", cr.ready());
- } catch (IOException e) {
- fail("Exception determining ready state : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.CharArrayReader#CharArrayReader(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "CharArrayReader",
- args = {char[].class, int.class, int.class}
- )
- public void test_Constructor$CII() throws IOException {
- try {
- cr = new CharArrayReader(null, 0, 0);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
- try {
- cr = new CharArrayReader(hw, -1, 0);
- fail("Test 2: IllegalArgumentException expected.");
- } catch (IllegalArgumentException e) {
- // Expected.
- }
- try {
- cr = new CharArrayReader(hw, 0, -1);
- fail("Test 3: IllegalArgumentException expected.");
- } catch (IllegalArgumentException e) {
- // Expected.
- }
- try {
- cr = new CharArrayReader(hw, hw.length + 1, 1);
- fail("Test 4: IllegalArgumentException expected.");
- } catch (IllegalArgumentException e) {
- // Expected.
- }
-
- cr = new CharArrayReader(hw, 5, 5);
- assertTrue("Test 5: Failed to create reader", cr.ready());
- assertEquals("Test 6: Incorrect character read;",
- 'W', cr.read());
- }
-
- /**
- * @tests java.io.CharArrayReader#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies close() method.",
- method = "close",
- args = {}
- )
- public void test_close() {
- cr = new CharArrayReader(hw);
- cr.close();
- try {
- cr.read();
- fail("Failed to throw exception on read from closed stream");
- } catch (IOException e) {
- // Expected.
- }
-
- }
-
- /**
- * @tests java.io.CharArrayReader#mark(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "mark",
- args = {int.class}
- )
- public void test_markI() throws IOException {
- // Test for method void java.io.CharArrayReader.mark(int)
- cr = new CharArrayReader(hw);
- cr.skip(5L);
- cr.mark(100);
- cr.read();
- cr.reset();
- assertEquals("Test 1: Failed to mark correct position;",
- 'W', cr.read());
-
- cr.close();
- try {
- cr.mark(100);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.CharArrayReader#markSupported()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies markSupported() method.",
- method = "markSupported",
- args = {}
- )
- public void test_markSupported() {
- // Test for method boolean java.io.CharArrayReader.markSupported()
- cr = new CharArrayReader(hw);
- assertTrue("markSupported returned false", cr.markSupported());
- }
-
- /**
- * @tests java.io.CharArrayReader#read()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "read",
- args = {}
- )
- public void test_read() throws IOException {
- cr = new CharArrayReader(hw);
- assertEquals("Test 1: Read returned incorrect char;",
- 'H', cr.read());
- cr = new CharArrayReader(new char[] { '\u8765' });
- assertTrue("Test 2: Incorrect double byte char;",
- cr.read() == '\u8765');
-
- cr.close();
- try {
- cr.read();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.CharArrayReader#read(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "read",
- args = {char[].class, int.class, int.class}
- )
- @AndroidOnly("The RI throws an IndexOutOfBoundsException instead of an" +
- "ArrayIndexOutOfBoundsException. The RI specification does not" +
- "define the expected behavior.")
- public void test_read$CII() throws IOException {
- // Test for method int java.io.CharArrayReader.read(char [], int, int)
- char[] c = new char[11];
- cr = new CharArrayReader(hw);
- cr.read(c, 1, 10);
- assertTrue("Test 1: Read returned incorrect chars.",
- new String(c, 1, 10).equals(new String(hw, 0, 10)));
-
- // Illegal argument checks.
- try {
- cr.read(null, 1, 0);
- fail("Test 2: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
-
- try {
- cr.read(c , -1, 1);
- fail("Test 3: ArrayIndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- cr.read(c , 1, -1);
- fail("Test 4: ArrayIndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- cr.read(c, 1, c.length);
- fail("Test 5: ArrayIndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- cr.close();
- try {
- cr.read(c, 1, 1);
- fail("Test 6: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.CharArrayReader#ready()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies ready() method.",
- method = "ready",
- args = {}
- )
- public void test_ready() {
- // Test for method boolean java.io.CharArrayReader.ready()
- cr = new CharArrayReader(hw);
- boolean expectException = false;
- try {
- assertTrue("ready returned false", cr.ready());
- cr.skip(1000);
- assertTrue("ready returned true", !cr.ready());
- cr.close();
- expectException = true;
- cr.ready();
- fail("No exception 1");
- } catch (IOException e) {
- if (!expectException)
- fail("Unexpected: " + e);
- }
- try {
- cr = new CharArrayReader(hw);
- cr.close();
- cr.ready();
- fail("No exception 2");
- } catch (IOException e) {
- }
-
- }
-
- /**
- * @tests java.io.CharArrayReader#reset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "reset",
- args = {}
- )
- public void test_reset() throws IOException {
- cr = new CharArrayReader(hw);
- cr.skip(5L);
- cr.mark(100);
- cr.read();
- cr.reset();
- assertEquals("Test 1: Reset failed to return to marker position.",
- 'W', cr.read());
-
- cr.close();
- try {
- cr.reset();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.CharArrayReader#skip(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "skip",
- args = {long.class}
- )
- public void test_skipJ() throws IOException {
- long skipped = 0;
- cr = new CharArrayReader(hw);
- skipped = cr.skip(5L);
- assertEquals("Test 1: Failed to skip correct number of chars;",
- 5L, skipped);
- assertEquals("Test 2: Skip skipped wrong chars;",
- 'W', cr.read());
-
- cr.close();
- try {
- cr.skip(1);
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- if (cr != null)
- cr.close();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/CharArrayWriterTest.java b/luni/src/test/java/tests/api/java/io/CharArrayWriterTest.java
deleted file mode 100644
index 5c7d355..0000000
--- a/luni/src/test/java/tests/api/java/io/CharArrayWriterTest.java
+++ /dev/null
@@ -1,436 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.CharArrayReader;
-import java.io.CharArrayWriter;
-import java.io.IOException;
-import java.io.StringWriter;
-
-import tests.support.Support_ASimpleWriter;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(CharArrayWriter.class)
-public class CharArrayWriterTest extends junit.framework.TestCase {
-
- char[] hw = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
-
- CharArrayWriter cw;
-
- CharArrayReader cr;
-
- /**
- * @tests java.io.CharArrayWriter#CharArrayWriter(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "CharArrayWriter",
- args = {int.class}
- )
- public void test_ConstructorI() {
- // Test for method java.io.CharArrayWriter(int)
- cw = new CharArrayWriter(90);
- assertEquals("Test 1: Incorrect writer created.", 0, cw.size());
-
- try {
- cw = new CharArrayWriter(-1);
- fail("IllegalArgumentException expected.");
- } catch (IllegalArgumentException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.CharArrayWriter#CharArrayWriter()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies CharArrayWriter() method.",
- method = "CharArrayWriter",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.io.CharArrayWriter()
- cw = new CharArrayWriter();
- assertEquals("Created incorrect writer", 0, cw.size());
- }
-
- /**
- * @tests java.io.CharArrayWriter#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies close() method.",
- method = "close",
- args = {}
- )
- public void test_close() {
- // Test for method void java.io.CharArrayWriter.close()
- cw.close();
- }
-
- /**
- * @tests java.io.CharArrayWriter#flush()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies flush() method.",
- method = "flush",
- args = {}
- )
- public void test_flush() {
- // Test for method void java.io.CharArrayWriter.flush()
- cw.flush();
- }
-
- /**
- * @tests java.io.CharArrayWriter#reset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies reset() method.",
- method = "reset",
- args = {}
- )
- public void test_reset() {
- // Test for method void java.io.CharArrayWriter.reset()
- cw.write("HelloWorld", 5, 5);
- cw.reset();
- cw.write("HelloWorld", 0, 5);
- cr = new CharArrayReader(cw.toCharArray());
- try {
- char[] c = new char[100];
- cr.read(c, 0, 5);
- assertEquals("Reset failed to reset buffer",
- "Hello", new String(c, 0, 5));
- } catch (IOException e) {
- fail("Exception during reset test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.CharArrayWriter#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies size() method.",
- method = "size",
- args = {}
- )
- public void test_size() {
- // Test for method int java.io.CharArrayWriter.size()
- assertEquals("Returned incorrect size", 0, cw.size());
- cw.write(hw, 5, 5);
- assertEquals("Returned incorrect size", 5, cw.size());
- }
-
- /**
- * @tests java.io.CharArrayWriter#toCharArray()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies toCharArray() method.",
- method = "toCharArray",
- args = {}
- )
- public void test_toCharArray() {
- // Test for method char [] java.io.CharArrayWriter.toCharArray()
- cw.write("HelloWorld", 0, 10);
- cr = new CharArrayReader(cw.toCharArray());
- try {
- char[] c = new char[100];
- cr.read(c, 0, 10);
- assertEquals("toCharArray failed to return correct array",
- "HelloWorld", new String(c, 0, 10));
- } catch (IOException e) {
- fail("Exception during toCharArray test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.CharArrayWriter#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies toString() method.",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.io.CharArrayWriter.toString()
- cw.write("HelloWorld", 5, 5);
- cr = new CharArrayReader(cw.toCharArray());
- assertEquals("Returned incorrect string",
- "World", cw.toString());
- }
-
- /**
- * @tests java.io.CharArrayWriter#write(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "write",
- args = {char[].class, int.class, int.class}
- )
- public void test_write$CII() {
- // Test for method void java.io.CharArrayWriter.write(char [], int, int)
- cw.write(hw, 5, 5);
- cr = new CharArrayReader(cw.toCharArray());
- try {
- char[] c = new char[100];
- cr.read(c, 0, 5);
- assertEquals("Writer failed to write correct chars",
- "World", new String(c, 0, 5));
- } catch (IOException e) {
- fail("Exception during write test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.CharArrayWriter#write(char[], int, int)
- * Regression for HARMONY-387
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Illegal argument checks.",
- method = "write",
- args = {char[].class, int.class, int.class}
- )
- public void test_write$CII_Exception() {
- char[] target = new char[10];
- cw = new CharArrayWriter();
- try {
- cw.write(target, -1, 1);
- fail("Test 1: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- cw.write(target, 0, -1);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- cw.write(target, 1, target.length);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- cw.write((char[]) null, 1, 1);
- fail("Test 4: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.CharArrayWriter#write(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies write(int) method.",
- method = "write",
- args = {int.class}
- )
- public void test_writeI() {
- // Test for method void java.io.CharArrayWriter.write(int)
- cw.write('T');
- cr = new CharArrayReader(cw.toCharArray());
- try {
- assertEquals("Writer failed to write char", 'T', cr.read());
- } catch (IOException e) {
- fail("Exception during write test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.CharArrayWriter#write(java.lang.String, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies write(java.lang.String, int, int) method. [Need to check different strings?]",
- method = "write",
- args = {java.lang.String.class, int.class, int.class}
- )
- public void test_writeLjava_lang_StringII() {
- // Test for method void java.io.CharArrayWriter.write(java.lang.String,
- // int, int)
- cw.write("HelloWorld", 5, 5);
- cr = new CharArrayReader(cw.toCharArray());
- try {
- char[] c = new char[100];
- cr.read(c, 0, 5);
- assertEquals("Writer failed to write correct chars",
- "World", new String(c, 0, 5));
- } catch (IOException e) {
- fail("Exception during write test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.CharArrayWriter#write(java.lang.String, int, int)
- * Regression for HARMONY-387
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Regression for write(java.lang.String, int, int) method.",
- method = "write",
- args = {java.lang.String.class, int.class, int.class}
- )
- public void test_writeLjava_lang_StringII_2() throws StringIndexOutOfBoundsException {
- CharArrayWriter obj = new CharArrayWriter();
- try {
- obj.write((String) null, -1, 0);
- fail("NullPointerException expected");
- } catch (NullPointerException t) {
- }
- }
-
- /**
- * @tests java.io.CharArrayWriter#writeTo(java.io.Writer)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "writeTo",
- args = {java.io.Writer.class}
- )
- public void test_writeToLjava_io_Writer() {
- Support_ASimpleWriter ssw = new Support_ASimpleWriter(true);
- cw.write("HelloWorld", 0, 10);
- StringWriter sw = new StringWriter();
- try {
- cw.writeTo(sw);
- assertEquals("Test 1: Writer failed to write correct chars;",
- "HelloWorld", sw.toString());
- } catch (IOException e) {
- fail("Exception during writeTo test : " + e.getMessage());
- }
-
- try {
- cw.writeTo(ssw);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- cw = new CharArrayWriter();
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- if (cr != null)
- cr.close();
- cw.close();
- }
-
- /**
- * @tests java.io.CharArrayWriter#append(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies append(char c) method.",
- method = "append",
- args = {char.class}
- )
- public void test_appendChar() throws IOException {
- char testChar = ' ';
- CharArrayWriter writer = new CharArrayWriter(10);
- writer.append(testChar);
- writer.flush();
- assertEquals(String.valueOf(testChar), writer.toString());
- writer.close();
- }
-
- /**
- * @tests java.io.CharArrayWriter#append(CharSequence)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies append(CharSequence csq) method.",
- method = "append",
- args = {java.lang.CharSequence.class}
- )
- public void test_appendCharSequence() {
-
- String testString = "My Test String";
- CharArrayWriter writer = new CharArrayWriter(10);
- writer.append(testString);
- writer.flush();
- assertEquals(testString, writer.toString());
- writer.close();
- }
-
- /**
- * @tests java.io.CharArrayWriter#append(CharSequence, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "append",
- args = {java.lang.CharSequence.class, int.class, int.class}
- )
- public void test_appendLjava_langCharSequenceII() {
- String testString = "My Test String";
- CharArrayWriter writer = new CharArrayWriter(10);
-
- // Illegal argument checks.
- try {
- writer.append(testString, -1, 0);
- fail("Test 1: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
- try {
- writer.append(testString, 0, -1);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
- try {
- writer.append(testString, 1, 0);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
- try {
- writer.append(testString, 1, testString.length() + 1);
- fail("Test 4: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- writer.append(testString, 1, 3);
- writer.flush();
- assertEquals("Test 5: Appending failed;",
- testString.substring(1, 3), writer.toString());
- writer.close();
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/io/CharConversionExceptionTest.java b/luni/src/test/java/tests/api/java/io/CharConversionExceptionTest.java
deleted file mode 100644
index 912951c..0000000
--- a/luni/src/test/java/tests/api/java/io/CharConversionExceptionTest.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.CharConversionException;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(CharConversionException.class)
-public class CharConversionExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.io.CharConversionException#CharConversionException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "CharConversionException",
- args = {}
- )
- public void test_Constructor() {
- try {
- if (true) // To avoid unreachable code compilation error.
- throw new CharConversionException();
- fail("Test 1: CharConversionException expected.");
- } catch (CharConversionException e) {
- assertNull("Test 2: Null expected for exceptions constructed without a message.",
- e.getMessage());
- }
- }
-
- /**
- * @tests java.io.CharConversionException#CharConversionException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "CharConversionException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- try {
- if (true) // To avoid unreachable code compilation error.
- throw new CharConversionException("Something went wrong.");
- fail("Test 1: CharConversionException expected.");
- } catch (CharConversionException e) {
- assertEquals("Test 2: Incorrect message;",
- "Something went wrong.", e.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/ComputeSerialVersionUIDTest.java b/luni/src/test/java/tests/api/java/io/ComputeSerialVersionUIDTest.java
deleted file mode 100644
index 7b783e0..0000000
--- a/luni/src/test/java/tests/api/java/io/ComputeSerialVersionUIDTest.java
+++ /dev/null
@@ -1,183 +0,0 @@
-package tests.api.java.io;
-
-import java.io.ObjectInputStream;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(ObjectInputStream.class)
-public class ComputeSerialVersionUIDTest extends junit.framework.TestCase {
-
-
- private String path = "serialization/tests/api/java/io/";
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void testComputeSUIDClass() throws Exception {
- ObjectInputStream ois = new ObjectInputStream(ClassLoader
- .getSystemResourceAsStream(path + "testComputeSUIDClass.ser"));
- SerializationTestClass.TestClassName1 o1 = (SerializationTestClass.TestClassName1) ois
- .readObject();
- SerializationTestClass.TestClassName2T_T$T o2 = (SerializationTestClass.TestClassName2T_T$T) ois
- .readObject();
- SerializationTestClass.TestClassModifierPublic o6 = (SerializationTestClass.TestClassModifierPublic) ois
- .readObject();
- SerializationTestClass.TestClassModifierAbstract o3 = (SerializationTestClass.TestClassModifierAbstract) ois
- .readObject();
- SerializationTestClass.TestClassModifierFinal o4 = (SerializationTestClass.TestClassModifierFinal) ois
- .readObject();
- SerializationTestClass.TestClassModifierInterface o5 = (SerializationTestClass.TestClassModifierInterface) ois
- .readObject();
- ois.close();
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void testComputeSUIDInterfaces() throws Exception {
- ObjectInputStream ois = new ObjectInputStream(ClassLoader
- .getSystemResourceAsStream(path
- + "testComputeSUIDInterfaces.ser"));
- SerializationTestClass.TestIntefaces o1 = (SerializationTestClass.TestIntefaces) ois
- .readObject();
- SerializationTestClass.TestIntefacesA o2 = (SerializationTestClass.TestIntefacesA) ois
- .readObject();
- SerializationTestClass.TestIntefacesAB o3 = (SerializationTestClass.TestIntefacesAB) ois
- .readObject();
- SerializationTestClass.TestIntefacesBA o4 = (SerializationTestClass.TestIntefacesBA) ois
- .readObject();
- SerializationTestClass.TestIntefacesC o5 = (SerializationTestClass.TestIntefacesC) ois
- .readObject();
- SerializationTestClass.TestIntefacesAC o6 = (SerializationTestClass.TestIntefacesAC) ois
- .readObject();
- SerializationTestClass.TestIntefacesCA o7 = (SerializationTestClass.TestIntefacesCA) ois
- .readObject();
- SerializationTestClass.TestIntefacesABC o8 = (SerializationTestClass.TestIntefacesABC) ois
- .readObject();
- SerializationTestClass.TestIntefacesACB o9 = (SerializationTestClass.TestIntefacesACB) ois
- .readObject();
- SerializationTestClass.TestIntefacesBAC o10 = (SerializationTestClass.TestIntefacesBAC) ois
- .readObject();
- SerializationTestClass.TestIntefacesBCA o11 = (SerializationTestClass.TestIntefacesBCA) ois
- .readObject();
- SerializationTestClass.TestIntefacesCAB o12 = (SerializationTestClass.TestIntefacesCAB) ois
- .readObject();
- SerializationTestClass.TestIntefacesCBA o13 = (SerializationTestClass.TestIntefacesCBA) ois
- .readObject();
- ois.close();
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void testComputeSUIDFields() throws Exception {
- ObjectInputStream ois = new ObjectInputStream(ClassLoader
- .getSystemResourceAsStream(path + "testComputeSUIDFields.ser"));
- SerializationTestClass.TestFieldsNone o1 = (SerializationTestClass.TestFieldsNone) ois
- .readObject();
- SerializationTestClass.TestFieldsOneFinal o2 = (SerializationTestClass.TestFieldsOneFinal) ois
- .readObject();
- SerializationTestClass.TestFieldsTwoFinal o3 = (SerializationTestClass.TestFieldsTwoFinal) ois
- .readObject();
- SerializationTestClass.TestFieldsOnePrivate o4 = (SerializationTestClass.TestFieldsOnePrivate) ois
- .readObject();
- SerializationTestClass.TestFieldsTwoPrivate o5 = (SerializationTestClass.TestFieldsTwoPrivate) ois
- .readObject();
- SerializationTestClass.TestFieldsOneProtected o6 = (SerializationTestClass.TestFieldsOneProtected) ois
- .readObject();
- SerializationTestClass.TestFieldsTwoProtected o7 = (SerializationTestClass.TestFieldsTwoProtected) ois
- .readObject();
- SerializationTestClass.TestFieldsOnePublic o8 = (SerializationTestClass.TestFieldsOnePublic) ois
- .readObject();
- SerializationTestClass.TestFieldsTwoPublic o9 = (SerializationTestClass.TestFieldsTwoPublic) ois
- .readObject();
- SerializationTestClass.TestFieldsOneStatic o10 = (SerializationTestClass.TestFieldsOneStatic) ois
- .readObject();
- SerializationTestClass.TestFieldsTwoStatic o11 = (SerializationTestClass.TestFieldsTwoStatic) ois
- .readObject();
- SerializationTestClass.TestFieldsOneTransient o12 = (SerializationTestClass.TestFieldsOneTransient) ois
- .readObject();
- SerializationTestClass.TestFieldsTwoTransient o13 = (SerializationTestClass.TestFieldsTwoTransient) ois
- .readObject();
- SerializationTestClass.TestFieldsOneVolatile o14 = (SerializationTestClass.TestFieldsOneVolatile) ois
- .readObject();
- SerializationTestClass.TestFieldsTwoVolatile o15 = (SerializationTestClass.TestFieldsTwoVolatile) ois
- .readObject();
- SerializationTestClass.TestFieldSignatures o16 = (SerializationTestClass.TestFieldSignatures) ois
- .readObject();
- ois.close();
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void testComputeSUIDConstructors() throws Exception {
- ObjectInputStream ois = new ObjectInputStream(ClassLoader
- .getSystemResourceAsStream(path
- + "testComputeSUIDConstructors.ser"));
- SerializationTestClass.TestConstructorNone o1 = (SerializationTestClass.TestConstructorNone) ois
- .readObject();
- SerializationTestClass.TestConstructorOne o2 = (SerializationTestClass.TestConstructorOne) ois
- .readObject();
- SerializationTestClass.TestConstructorPrivate o3 = (SerializationTestClass.TestConstructorPrivate) ois
- .readObject();
- SerializationTestClass.TestConstructorProtected o4 = (SerializationTestClass.TestConstructorProtected) ois
- .readObject();
- SerializationTestClass.TestConstructorPublic o5 = (SerializationTestClass.TestConstructorPublic) ois
- .readObject();
- SerializationTestClass.TestConstructorSignature o6 = (SerializationTestClass.TestConstructorSignature) ois
- .readObject();
- SerializationTestClass.TestConstructorTwo o7 = (SerializationTestClass.TestConstructorTwo) ois
- .readObject();
- SerializationTestClass.TestConstructorTwoReverse o8 = (SerializationTestClass.TestConstructorTwoReverse) ois
- .readObject();
- ois.close();
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void testComputeSUIDMethods() throws Exception {
- ObjectInputStream ois = new ObjectInputStream(ClassLoader
- .getSystemResourceAsStream(path + "testComputeSUIDMethods.ser"));
- SerializationTestClass.TestMehodPrivate o1 = (SerializationTestClass.TestMehodPrivate) ois
- .readObject();
- SerializationTestClass.TestMethodAbstract o2 = (SerializationTestClass.TestMethodAbstract) ois
- .readObject();
- SerializationTestClass.TestMethodFinal o3 = (SerializationTestClass.TestMethodFinal) ois
- .readObject();
- SerializationTestClass.TestMethodNative o4 = (SerializationTestClass.TestMethodNative) ois
- .readObject();
- SerializationTestClass.TestMethodProtected o5 = (SerializationTestClass.TestMethodProtected) ois
- .readObject();
- SerializationTestClass.TestMethodPublic o6 = (SerializationTestClass.TestMethodPublic) ois
- .readObject();
- SerializationTestClass.TestMethodStatic o7 = (SerializationTestClass.TestMethodStatic) ois
- .readObject();
- SerializationTestClass.TestMethodSignature o9 = (SerializationTestClass.TestMethodSignature) ois
- .readObject();
- SerializationTestClass.TestMethodReturnSignature o10 = (SerializationTestClass.TestMethodReturnSignature) ois
- .readObject();
- SerializationTestClass.TestMethodSynchronized o8 = (SerializationTestClass.TestMethodSynchronized) ois
- .readObject();
- ois.close();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/DataInputOutputStreamTest.java b/luni/src/test/java/tests/api/java/io/DataInputOutputStreamTest.java
deleted file mode 100644
index 137f6a8..0000000
--- a/luni/src/test/java/tests/api/java/io/DataInputOutputStreamTest.java
+++ /dev/null
@@ -1,529 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.ByteArrayInputStream;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.EOFException;
-import java.io.IOException;
-
-import tests.support.Support_OutputStream;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-@TestTargetClass(DataOutputStream.class)
-public class DataInputOutputStreamTest extends junit.framework.TestCase {
-
- private DataOutputStream os;
-
- private DataInputStream dis;
-
- private Support_OutputStream sos;
-
- String unihw = "\u0048\u0065\u006C\u006C\u006F\u0020\u0057\u006F\u0072\u006C\u0064";
-
- /**
- * @tests java.io.DataInputStream#readBoolean()
- * @tests java.io.DataOutputStream#writeBoolean(boolean)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeBoolean",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readBoolean",
- args = {},
- clazz = DataInputStream.class
- )
- })
- public void test_read_writeBoolean() throws IOException {
- os.writeBoolean(true);
- sos.setThrowsException(true);
- try {
- os.writeBoolean(false);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sos.setThrowsException(false);
-
- os.close();
- openDataInputStream();
- assertTrue("Test 2: Incorrect boolean written or read.",
- dis.readBoolean());
-
- try {
- dis.readBoolean();
- fail("Test 3: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- dis.close();
- try {
- dis.readBoolean();
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataInputStream#readByte()
- * @tests java.io.DataOutputStream#writeByte(int)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeByte",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readByte",
- args = {},
- clazz = DataInputStream.class
- )
- })
- public void test_read_writeByte() throws IOException {
- os.writeByte((byte) 127);
- sos.setThrowsException(true);
- try {
- os.writeByte((byte) 127);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sos.setThrowsException(false);
-
- os.close();
- openDataInputStream();
- assertEquals("Test 2: Incorrect byte written or read;",
- (byte) 127, dis.readByte());
-
- try {
- dis.readByte();
- fail("Test 3: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- dis.close();
- try {
- dis.readByte();
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataInputStream#readChar()
- * @tests java.io.DataOutputStream#writeChar(int)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeChar",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readChar",
- args = {},
- clazz = DataInputStream.class
- )
- })
- public void test_read_writeChar() throws IOException {
- os.writeChar('b');
- sos.setThrowsException(true);
- try {
- os.writeChar('k');
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sos.setThrowsException(false);
-
- os.close();
- openDataInputStream();
- assertEquals("Test 2: Incorrect char written or read;",
- 'b', dis.readChar());
-
- try {
- dis.readChar();
- fail("Test 3: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- dis.close();
- try {
- dis.readChar();
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataInputStream#readDouble()
- * @tests java.io.DataOutputStream#writeDouble(double)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeDouble",
- args = {double.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readDouble",
- args = {},
- clazz = DataInputStream.class
- )
- })
- public void test_read_writeDouble() throws IOException {
- os.writeDouble(2345.76834720202);
- sos.setThrowsException(true);
- try {
- os.writeDouble(2345.76834720202);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sos.setThrowsException(false);
-
- os.close();
- openDataInputStream();
- assertEquals("Test 1: Incorrect double written or read;",
- 2345.76834720202, dis.readDouble());
-
- try {
- dis.readDouble();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- dis.close();
- try {
- dis.readDouble();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataInputStream#readFloat()
- * @tests java.io.DataOutputStream#writeFloat(float)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeFloat",
- args = {float.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readFloat",
- args = {},
- clazz = DataInputStream.class
- )
- })
- public void test_read_writeFloat() throws IOException {
- os.writeFloat(29.08764f);
- sos.setThrowsException(true);
- try {
- os.writeFloat(29.08764f);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sos.setThrowsException(false);
-
- os.close();
- openDataInputStream();
- assertEquals("Test 2: Incorrect float written or read;",
- 29.08764f, dis.readFloat());
-
- try {
- dis.readFloat();
- fail("Test 3: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- dis.close();
- try {
- dis.readFloat();
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataInputStream#readInt()
- * @tests java.io.DataOutputStream#writeInt(int)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeInt",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readInt",
- args = {},
- clazz = DataInputStream.class
- )
- })
- public void test_read_writeInt() throws IOException {
- os.writeInt(768347202);
- sos.setThrowsException(true);
- try {
- os.writeInt(768347202);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sos.setThrowsException(false);
-
- os.close();
- openDataInputStream();
- assertEquals("Test 1: Incorrect int written or read;",
- 768347202, dis.readInt());
-
- try {
- dis.readInt();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- dis.close();
- try {
- dis.readInt();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataInputStream#readLong()
- * @tests java.io.DataOutputStream#writeLong(long)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeLong",
- args = {long.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readLong",
- args = {},
- clazz = DataInputStream.class
- )
- })
- public void test_read_writeLong() throws IOException {
- os.writeLong(9875645283333L);
- sos.setThrowsException(true);
- try {
- os.writeLong(9875645283333L);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sos.setThrowsException(false);
-
- os.close();
- openDataInputStream();
- assertEquals("Test 2: Incorrect long written or read;",
- 9875645283333L, dis.readLong());
-
- try {
- dis.readLong();
- fail("Test 3: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- dis.close();
- try {
- dis.readLong();
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataInputStream#readShort()
- * @tests java.io.DataOutputStream#writeShort(short)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeShort",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readShort",
- args = {},
- clazz = DataInputStream.class
- )
- })
- public void test_read_writeShort() throws IOException {
- os.writeShort(9875);
- sos.setThrowsException(true);
- try {
- os.writeShort(9875);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sos.setThrowsException(false);
-
- os.close();
- openDataInputStream();
- assertEquals("Test 1: Incorrect short written or read;",
- 9875, dis.readShort());
-
- try {
- dis.readShort();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- dis.close();
- try {
- dis.readShort();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
-
- /**
- * @tests java.io.DataInputStream#readUTF()
- * @tests java.io.DataOutputStream#writeUTF(java.lang.String)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeUTF",
- args = {String.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readUTF",
- args = {},
- clazz = DataInputStream.class
- )
- })
- public void test_read_writeUTF() throws IOException {
- os.writeUTF(unihw);
- sos.setThrowsException(true);
- try {
- os.writeUTF(unihw);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sos.setThrowsException(false);
-
- os.close();
- openDataInputStream();
- assertTrue("Test 1: Incorrect UTF-8 string written or read.",
- dis.readUTF().equals(unihw));
-
- try {
- dis.readUTF();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- dis.close();
- try {
- dis.readUTF();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- private void openDataInputStream() throws IOException {
- dis = new DataInputStream(new ByteArrayInputStream(sos.toByteArray()));
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- sos = new Support_OutputStream(256);
- os = new DataOutputStream(sos);
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- try {
- os.close();
- } catch (Exception e) {
- }
- try {
- dis.close();
- } catch (Exception e) {
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/DataInputStreamTest.java b/luni/src/test/java/tests/api/java/io/DataInputStreamTest.java
deleted file mode 100644
index cde968a..0000000
--- a/luni/src/test/java/tests/api/java/io/DataInputStreamTest.java
+++ /dev/null
@@ -1,517 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.EOFException;
-import java.io.IOException;
-
-import tests.support.Support_ASimpleInputStream;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(DataInputStream.class)
-public class DataInputStreamTest extends junit.framework.TestCase {
-
- private DataOutputStream os;
-
- private DataInputStream dis;
-
- private ByteArrayOutputStream bos;
-
- String unihw = "\u0048\u0065\u006C\u006C\u006F\u0020\u0057\u006F\u0072\u006C\u0064";
-
- public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_DataInputStream\n";
-
- private final int testLength = fileString.length();
-
- /**
- * @tests java.io.DataInputStream#DataInputStream(java.io.InputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies DataInputStream(java.io.InputStream) constructor.",
- method = "DataInputStream",
- args = {java.io.InputStream.class}
- )
- public void test_ConstructorLjava_io_InputStream() {
- // Test for method java.io.DataInputStream(java.io.InputStream)
- try {
- os.writeChar('t');
- os.close();
- openDataInputStream();
- } catch (IOException e) {
- fail("IOException during constructor test : " + e.getMessage());
- } finally {
- try {
- dis.close();
- } catch (IOException e) {
- fail("IOException during constructor test : " + e.getMessage());
- }
- }
- }
-
- /**
- * @tests java.io.DataInputStream#read(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "read",
- args = {byte[].class}
- )
- public void test_read$B() throws IOException {
- byte rbytes[] = new byte[testLength - 5];
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream();
- int r;
-
- os.write(fileString.getBytes());
- os.close();
- openDataInputStream();
-
- r = dis.read(rbytes);
- assertEquals("Test 1: Incorrect number of bytes read;",
- testLength - 5, r);
- assertTrue("Test 2: Incorrect data written or read.",
- new String(rbytes).equals(fileString.substring(0, testLength - 5)));
-
- r = dis.read(rbytes);
- assertEquals("Test 3: Incorrect number of bytes read;", 5, r);
- assertTrue("Test 4: Incorrect data written or read.",
- new String(rbytes, 0, 5).equals(fileString.substring(testLength - 5)));
-
- dis.close();
- sis.throwExceptionOnNextUse = true;
- dis = new DataInputStream(sis);
- try {
- dis.read(rbytes);
- fail("Test 5: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataInputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII() throws IOException {
- byte rbytes[] = new byte[testLength - 5];
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream();
- int r;
-
- os.write(fileString.getBytes());
- os.close();
- openDataInputStream();
-
- r = dis.read(rbytes, 1, testLength - 10);
- assertEquals("Test 1: Incorrect number of bytes read;",
- testLength - 10, r);
- assertEquals("Test 2: Incorrect data read.", 0, rbytes[0]);
- assertTrue("Test 3: Incorrect data written or read.",
- new String(rbytes, 1, r).equals(fileString.substring(0, r)));
-
- r = dis.read(rbytes, 0, 15);
- assertEquals("Test 3: Incorrect number of bytes read;", 10, r);
- assertTrue("Test 4: Incorrect data written or read.",
- new String(rbytes, 0, r).equals(fileString.substring(testLength - 10)));
-
- dis.close();
- sis.throwExceptionOnNextUse = true;
- dis = new DataInputStream(sis);
- try {
- dis.read(rbytes, 1, 5);
- fail("Test 5: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataInputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII_Exception() throws IOException {
- byte rbytes[] = new byte[testLength - 5];
-
- os.write(fileString.getBytes());
- os.close();
- openDataInputStream();
-
- try {
- dis.read(rbytes, -1, 1);
- fail("IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- dis.read(rbytes, 0, -1);
- fail("IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- dis.read(rbytes, rbytes.length, 1);
- fail("IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.io.DataInputStream#readFully(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "readFully",
- args = {byte[].class}
- )
- public void test_readFully$B() throws IOException {
- byte rbytes[] = new byte[testLength];
-
- os.write(fileString.getBytes());
- os.close();
- openDataInputStream();
-
- dis.readFully(rbytes);
- assertTrue("Test 1: Incorrect data written or read.",
- new String(rbytes, 0, testLength).equals(fileString));
-
- dis.close();
- try {
- dis.readFully(rbytes);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- openDataInputStream();
- dis.readByte();
- try {
- dis.readFully(rbytes);
- fail("Test 3: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataInputStream#readFully(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies everything except illegal argument values.",
- method = "readFully",
- args = {byte[].class, int.class, int.class}
- )
- public void test_readFully$BII() throws IOException {
- byte rbytes[] = new byte[testLength];
-
- os.write(fileString.getBytes());
- os.close();
- openDataInputStream();
-
- dis.readFully(rbytes, 2, testLength - 4);
- assertTrue("Test 1: Incorrect data written or read.",
- new String(rbytes, 2, testLength - 4).equals(
- fileString.substring(0, testLength - 4)));
-
- dis.close();
- try {
- dis.readFully(rbytes, 0, testLength);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- openDataInputStream();
- dis.readByte();
- try {
- dis.readFully(rbytes, 0, testLength);
- fail("Test 3: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataInputStream#readFully(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies that exceptions are thrown for illegal arguments.",
- method = "readFully",
- args = {byte[].class, int.class, int.class}
- )
- public void test_readFully$BII_Exception() throws IOException {
- DataInputStream is = new DataInputStream(new ByteArrayInputStream(new byte[testLength]));
-
- byte[] byteArray = new byte[testLength];
-
- try {
- is.readFully(byteArray, 0, -1);
- fail("Test 1: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- is.readFully(byteArray, 0, byteArray.length + 1);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- is.readFully(byteArray, 1, byteArray.length);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- is.readFully(byteArray, -1, byteArray.length);
- fail("Test 4: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- is.readFully(null, 0, 1);
- fail("Test 5: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
-
- is = new DataInputStream(null);
-
- try {
- is.readFully(byteArray, 0, 1);
- fail("Test 6: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataInputStream#readLine()
- */
- @SuppressWarnings("deprecation")
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "readLine",
- args = {}
- )
- public void test_readLine() throws IOException {
- String line;
- os.writeBytes("Lorem\nipsum\rdolor sit amet...");
- os.close();
- openDataInputStream();
- line = dis.readLine();
- assertTrue("Test 1: Incorrect line written or read: " + line,
- line.equals("Lorem"));
- line = dis.readLine();
- assertTrue("Test 2: Incorrect line written or read: " + line,
- line.equals("ipsum"));
- line = dis.readLine();
- assertTrue("Test 3: Incorrect line written or read: " + line,
- line.equals("dolor sit amet..."));
-
- dis.close();
- try {
- dis.readLine();
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataInputStream#readUnsignedByte()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "readUnsignedByte",
- args = {}
- )
- public void test_readUnsignedByte() throws IOException {
- os.writeByte((byte) -127);
- os.close();
- openDataInputStream();
- assertEquals("Test 1: Incorrect byte written or read;",
- 129, dis.readUnsignedByte());
-
- try {
- dis.readUnsignedByte();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- dis.close();
- try {
- dis.readUnsignedByte();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataInputStream#readUnsignedShort()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "readUnsignedShort",
- args = {}
- )
- public void test_readUnsignedShort() throws IOException {
- os.writeShort(Short.MIN_VALUE);
- os.close();
- openDataInputStream();
- assertEquals("Test 1: Incorrect short written or read;",
- (Short.MAX_VALUE + 1), dis.readUnsignedShort());
-
- try {
- dis.readUnsignedShort();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- dis.close();
- try {
- dis.readUnsignedShort();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataInputStream#readUTF(java.io.DataInput)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "readUTF",
- args = {java.io.DataInput.class}
- )
- public void test_readUTFLjava_io_DataInput() throws IOException {
- os.writeUTF(unihw);
- os.close();
- openDataInputStream();
- assertTrue("Test 1: Incorrect UTF-8 string written or read.",
- DataInputStream.readUTF(dis).equals(unihw));
-
- try {
- DataInputStream.readUTF(dis);
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- dis.close();
- try {
- DataInputStream.readUTF(dis);
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataInputStream#skipBytes(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "skipBytes",
- args = {int.class}
- )
- public void test_skipBytesI() {
- // Test for method int java.io.DataInputStream.skipBytes(int)
- try {
- byte fileBytes[] = fileString.getBytes();
- os.write(fileBytes);
- os.close();
- openDataInputStream();
- dis.skipBytes(100);
- byte rbytes[] = new byte[testLength];
- dis.read(rbytes, 0, 50);
- dis.close();
- assertTrue("Incorrect data read", new String(rbytes, 0, 50)
- .equals(fileString.substring(100, 150)));
- } catch (IOException e) {
- fail("IOException during skipBytes test 1 : " + e.getMessage());
- }
- try {
- // boolean eofException = false; //what is this var for?
- int skipped = 0;
- openDataInputStream();
- try {
- skipped = dis.skipBytes(50000);
- } catch (EOFException e) {
- // eofException = true;
- }
- ;
- assertTrue("Skipped should report " + testLength + " not "
- + skipped, skipped == testLength);
- } catch (IOException e) {
- fail("IOException during skipBytes test 2 : " + e.getMessage());
- }
- }
-
- private void openDataInputStream() throws IOException {
- dis = new DataInputStream(new ByteArrayInputStream(bos.toByteArray()));
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- bos = new ByteArrayOutputStream();
- os = new DataOutputStream(bos);
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- try {
- os.close();
- } catch (Exception e) {
- }
- try {
- dis.close();
- } catch (Exception e) {
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/DataOutputStreamTest.java b/luni/src/test/java/tests/api/java/io/DataOutputStreamTest.java
deleted file mode 100644
index c93c888..0000000
--- a/luni/src/test/java/tests/api/java/io/DataOutputStreamTest.java
+++ /dev/null
@@ -1,297 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.BufferedOutputStream;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-
-import tests.support.Support_OutputStream;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(
- value = DataOutputStream.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "Implicitely tested in setUp().",
- method = "DataOutputStream",
- args = {java.io.OutputStream.class}
- )
- }
-)
-public class DataOutputStreamTest extends junit.framework.TestCase {
-
- private DataOutputStream os;
-
- private DataInputStream dis;
-
- private ByteArrayOutputStream bos;
-
- private Support_OutputStream sos;
-
- String unihw = "\u0048\u0065\u006C\u006C\u006F\u0020\u0057\u006F\u0072\u006C\u0064";
-
- private static final String testString = "Lorem ipsum dolor sit amet,\n" +
- "consectetur adipisicing elit,\nsed do eiusmod tempor incididunt ut" +
- "labore et dolore magna aliqua.\n";
-
- private static final int testLength = testString.length();
-
- /**
- * @tests java.io.DataOutputStream#flush()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "flush",
- args = {}
- )
- public void test_flush() throws IOException {
- BufferedOutputStream buf = new BufferedOutputStream(bos);
-
- os = new DataOutputStream(buf);
- os.writeInt(9087589);
- assertTrue("Test 1: Written data should not be available.",
- bos.toByteArray().length == 0);
- os.flush();
- assertTrue("Test 2: Written data should be available.",
- bos.toByteArray().length > 0);
- os.close();
-
- openDataInputStream();
- int c = dis.readInt();
- assertEquals("Test 3: Failed to flush correctly;", 9087589, c);
- dis.close();
-
- os = new DataOutputStream(sos);
- try {
- os.flush();
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataOutputStream#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies size() method.",
- method = "size",
- args = {}
- )
- public void test_size() {
- // Test for method int java.io.DataOutputStream.size()
-
- try {
- os.write(testString.getBytes(), 0, testLength / 2);
- os.close();
- assertEquals("Incorrect size returned", testLength / 2, os.size());
- openDataInputStream();
- byte[] rbuf = new byte[testLength / 2];
- dis.read(rbuf, 0, testLength / 2);
- dis.close();
- } catch (IOException e) {
- fail("Exception during write test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.DataOutputStream#write(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException checking missed.",
- method = "write",
- args = {byte[].class, int.class, int.class}
- )
- public void test_write$BII() throws IOException {
- int r;
- os.write(testString.getBytes(), 5, testLength - 7);
- os.close();
- openDataInputStream();
- byte[] rbuf = new byte[testLength];
- r = dis.read(rbuf, 0, testLength);
- assertEquals("Test 1: Incorrect number of bytes read;",
- testLength - 7, r);
- dis.close();
- assertTrue("Test 2: Incorrect bytes written or read.",
- new String(rbuf, 0, r).equals(
- testString.substring(5, testLength - 2)));
- }
-
- /**
- * @tests java.io.DataOutputStream#write(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Illegal argument checks.",
- method = "write",
- args = {byte[].class, int.class, int.class}
- )
- public void test_write$BII_Exception() throws IOException {
- byte[] nullByteArray = null;
- byte[] byteArray = new byte[10];
-
- try {
- os.write(nullByteArray, 0, 1);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
-
- try {
- os.write(byteArray, -1, 1);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- os.write(byteArray, 0, -1);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- os.write(byteArray, 1, 10);
- fail("Test 4: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataOutputStream#write(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "write",
- args = {int.class}
- )
- public void test_writeI() throws IOException {
- os.write(42);
- os.close();
-
- openDataInputStream();
- assertEquals("Test 1: Incorrect int written or read;",
- 42, dis.read());
- dis.close();
-
- os = new DataOutputStream(sos);
- try {
- os.write(42);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataOutputStream#writeBytes(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "writeBytes",
- args = {java.lang.String.class}
- )
- public void test_writeBytesLjava_lang_String() throws IOException {
- os.writeBytes(testString);
- os.close();
-
- openDataInputStream();
- byte[] rbuf = new byte[testLength];
- dis.read(rbuf, 0, testLength);
- dis.close();
- assertTrue("Test 1: Incorrect bytes written or read.",
- new String(rbuf, 0, testLength).equals(testString));
-
- os = new DataOutputStream(sos);
- try {
- os.writeBytes(testString);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.DataOutputStream#writeChars(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "writeChars",
- args = {java.lang.String.class}
- )
- public void test_writeCharsLjava_lang_String() throws IOException {
- os.writeChars(unihw);
- os.close();
- openDataInputStream();
- char[] chars = new char[unihw.length()];
- int i, a = dis.available() / 2;
- for (i = 0; i < a; i++) chars[i] = dis.readChar();
- assertEquals("Test 1: Incorrect chars written or read;",
- unihw, new String(chars, 0, i)
- );
- dis.close();
-
- os = new DataOutputStream(sos);
- try {
- os.writeChars(unihw);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- private void openDataInputStream() throws IOException {
- dis = new DataInputStream(new ByteArrayInputStream(bos.toByteArray()));
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- sos = new Support_OutputStream(true);
- bos = new ByteArrayOutputStream();
- os = new DataOutputStream(bos);
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- sos.setThrowsException(false);
- try {
- if (os != null)
- os.close();
- if (dis != null)
- dis.close();
- } catch (IOException e) {
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/EOFExceptionTest.java b/luni/src/test/java/tests/api/java/io/EOFExceptionTest.java
deleted file mode 100644
index b1a20f5..0000000
--- a/luni/src/test/java/tests/api/java/io/EOFExceptionTest.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.ByteArrayInputStream;
-import java.io.DataInputStream;
-import java.io.EOFException;
-
-@TestTargetClass(EOFException.class)
-public class EOFExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.io.EOFException#EOFException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "EOFException",
- args = {}
- )
- public void test_Constructor() {
- try {
- new DataInputStream(new ByteArrayInputStream(new byte[1]))
- .readShort();
- fail("Test 1: EOFException expected.");
- } catch (EOFException e) {
- assertNull("Test 2: Null expected for exceptions constructed without a message.",
- e.getMessage());
- } catch (Exception e) {
- fail("Test 3: Unexpected exception: " + e.toString());
- }
- }
-
- /**
- * @tests java.io.EOFException#EOFException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "EOFException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- try {
- if (true) // Needed to avoid unreachable code compilation error.
- throw new EOFException("Something went wrong.");
- fail("Test 1: EOFException expected.");
- } catch (EOFException e) {
- assertEquals("Test 2: Incorrect message;",
- "Something went wrong.", e.getMessage());
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/ExternalizableTest.java b/luni/src/test/java/tests/api/java/io/ExternalizableTest.java
deleted file mode 100644
index 1048bc7..0000000
--- a/luni/src/test/java/tests/api/java/io/ExternalizableTest.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package tests.api.java.io;
-
-import junit.framework.TestCase;
-
-import java.io.Externalizable;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(
- value = Externalizable.class,
- untestedMethods = {
- @TestTargetNew(
- method = "readExternal",
- args = {ObjectInput.class},
- level = TestLevel.NOT_FEASIBLE,
- notes = "There are no classes in the current core " +
- "libraries that implement this method."
- ),
- @TestTargetNew(
- method = "writeExternal",
- args = {ObjectOutput.class},
- level = TestLevel.NOT_FEASIBLE,
- notes = "There are no classes in the current core " +
- "libraries that implement this method."
- )
- }
-)
-public class ExternalizableTest extends TestCase {
-
-}
diff --git a/luni/src/test/java/tests/api/java/io/FileDescriptorTest.java b/luni/src/test/java/tests/api/java/io/FileDescriptorTest.java
deleted file mode 100644
index 8aefb71..0000000
--- a/luni/src/test/java/tests/api/java/io/FileDescriptorTest.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileDescriptor;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.RandomAccessFile;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(FileDescriptor.class)
-public class FileDescriptorTest extends junit.framework.TestCase {
-
- private static String platformId = "JDK"
- + System.getProperty("java.vm.version").replace('.', '-');
-
- FileOutputStream fos;
-
- BufferedOutputStream os;
-
- FileInputStream fis;
-
- File f;
-
- /**
- * @tests java.io.FileDescriptor#FileDescriptor()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "FileDescriptor",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.io.FileDescriptor()
- FileDescriptor fd = new FileDescriptor();
- assertTrue("Failed to create FileDescriptor",
- fd instanceof FileDescriptor);
- }
-
- /**
- * @tests java.io.FileDescriptor#sync()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "SyncFailedException not checked since it is only thrown" +
- "by the native implementation of sync().",
- method = "sync",
- args = {}
- )
- public void test_sync() throws Exception {
- // Test for method void java.io.FileDescriptor.sync()
- f = File.createTempFile("fd" + platformId, ".tst");
- f.delete();
- fos = new FileOutputStream(f.getPath());
- fos.write("Test String".getBytes());
- fis = new FileInputStream(f.getPath());
- FileDescriptor fd = fos.getFD();
- fd.sync();
- int length = "Test String".length();
- assertEquals("Bytes were not written after sync", length, fis
- .available());
-
- // Regression test for Harmony-1494
- fd = fis.getFD();
- fd.sync();
- assertEquals("Bytes were not written after sync", length, fis
- .available());
-
- RandomAccessFile raf = new RandomAccessFile(f, "r");
- fd = raf.getFD();
- fd.sync();
- raf.close();
- }
-
- /**
- * @tests java.io.FileDescriptor#valid()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "valid",
- args = {}
- )
- public void test_valid() {
- // Test for method boolean java.io.FileDescriptor.valid()
- try {
- f = new File(System.getProperty("java.io.tmpdir"), "fd.tst");
- f.delete();
- os = new BufferedOutputStream(fos = new FileOutputStream(f
- .getPath()), 4096);
- FileDescriptor fd = fos.getFD();
- assertTrue("Valid fd returned false", fd.valid());
- os.close();
- assertTrue("Invalid fd returned true", !fd.valid());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
-
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- try {
- os.close();
- } catch (Exception e) {
- }
- try {
- fis.close();
- } catch (Exception e) {
- }
- try {
- fos.close();
- } catch (Exception e) {
- }
- try {
- f.delete();
- } catch (Exception e) {
- }
- }
-
- protected void doneSuite() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/FileFilterTest.java b/luni/src/test/java/tests/api/java/io/FileFilterTest.java
deleted file mode 100644
index 68bafc8..0000000
--- a/luni/src/test/java/tests/api/java/io/FileFilterTest.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package tests.api.java.io;
-
-import java.io.File;
-import java.io.FileFilter;
-
-import junit.framework.TestCase;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(
- value = FileFilter.class,
- untestedMethods = {
- @TestTargetNew(
- method = "accept",
- args = {File.class},
- level = TestLevel.NOT_FEASIBLE,
- notes = "There are no classes in the current core " +
- "libraries that implement this method."
- )
- }
-)
-public class FileFilterTest extends TestCase {
-
-}
diff --git a/luni/src/test/java/tests/api/java/io/FileInputStreamTest.java b/luni/src/test/java/tests/api/java/io/FileInputStreamTest.java
deleted file mode 100644
index 9d32971..0000000
--- a/luni/src/test/java/tests/api/java/io/FileInputStreamTest.java
+++ /dev/null
@@ -1,511 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.File;
-import java.io.FileDescriptor;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.nio.channels.FileChannel;
-
-import tests.support.Support_PlatformFile;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(
- value = FileInputStream.class,
- untestedMethods = {
- @TestTargetNew(
- method = "finalize",
- args = {},
- level = TestLevel.NOT_FEASIBLE,
- notes = "Hard to test since it requires that the " +
- "garbage collector runs; add test later."
- )
- }
-)
-public class FileInputStreamTest extends junit.framework.TestCase {
-
- public String fileName;
-
- private FileInputStream is;
-
- byte[] ibuf = new byte[4096];
-
- public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_java_io_File\nTest_java_io_FileDescriptor\nTest_FileInputStream\nTest_java_io_FileNotFoundException\nTest_java_io_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
-
- /**
- * @tests FileInputStream#FileInputStream(File)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "FileInputStream",
- args = {File.class}
- )
- public void test_ConstructorLjava_io_File() {
- // Test for method FileInputStream(File)
- try {
- File f = new File(fileName);
- is = new FileInputStream(f);
- is.close();
- } catch (Exception e) {
- fail("Failed to create FileInputStream : " + e.getMessage());
- }
- File f2 = new File("ImprobableFile.42");
- try {
- is = new FileInputStream(f2);
- is.close();
- f2.delete();
- fail("FileNotFoundException expected.");
- } catch (FileNotFoundException e) {
- // Expected.
- } catch (IOException e) {
- fail("Unexpected IOException: " + e.getMessage());
- }
- }
-
- /**
- * @tests FileInputStream#FileInputStream(FileDescriptor)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "FileInputStream",
- args = {FileDescriptor.class}
- )
- public void test_ConstructorLjava_io_FileDescriptor() {
- // Test for method FileInputStream(FileDescriptor)
- try {
- FileOutputStream fos = new FileOutputStream(fileName);
- FileInputStream fis = new FileInputStream(fos.getFD());
- fos.close();
- fis.close();
- } catch (Exception e) {
- fail("Exception during constrcutor test: " + e.toString());
- }
- try {
- FileInputStream fis = new FileInputStream((FileDescriptor) null);
- fis.close();
- fail("NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- } catch (IOException e) {
- fail("Unexpected IOException: " + e.getMessage());
- }
- }
-
- /**
- * @tests FileInputStream#FileInputStream(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "FileInputStream",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method FileInputStream(java.lang.String)
- try {
- is = new FileInputStream(fileName);
- is.close();
- } catch (Exception e) {
- fail("Failed to create FileInputStream : " + e.getMessage());
- }
- try {
- is = new FileInputStream("ImprobableFile.42");
- is.close();
- new File("ImprobableFile.42").delete();
- fail("FileNotFoundException expected.");
- } catch (FileNotFoundException e) {
- // Expected.
- } catch (IOException e) {
- fail("Unexpected IOException: " + e.getMessage());
- }
- }
-
- /**
- * @tests FileInputStream#available()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "available",
- args = {}
- )
- public void test_available() throws IOException {
- is = new FileInputStream(fileName);
- assertEquals("Test 1: Returned incorrect number of available bytes;",
- fileString.length(), is.available());
- is.close();
- try {
- is.available();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests FileInputStream#close()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "No IOException test since this is only thrown" +
- "by a native method.",
- method = "close",
- args = {}
- )
- public void test_close() throws IOException {
- is = new FileInputStream(fileName);
- is.close();
-
- try {
- is.read();
- fail("Test 1: Read from closed stream succeeded.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests FileInputStream#getChannel()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getChannel",
- args = {}
- )
- public void test_getChannel() {
- // Test for method FileChannel FileInputStream.getChannel()
- FileChannel channel;
- byte[] buffer = new byte[100];
- byte[] stringBytes;
- final int offset = 5;
- boolean equal = true;
-
- try {
- FileInputStream fis = new FileInputStream(fileName);
- channel = fis.getChannel();
- assertNotNull(channel);
- assertTrue("Channel is closed.", channel.isOpen());
-
- // Check that the channel is associated with the input stream.
- channel.position(offset);
- fis.read(buffer, 0, 10);
- stringBytes = fileString.getBytes();
- for (int i = 0; i < 10; i++) {
- equal &= (buffer[i] == stringBytes[i + offset]);
- }
- assertTrue("Channel is not associated with this stream.", equal);
-
- fis.close();
- assertFalse("Channel has not been closed.", channel.isOpen());
- } catch (FileNotFoundException e) {
- fail("Could not find : " + fileName);
- }
-
- catch (IOException e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * @tests FileInputStream#getFD()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "No IOException check since it is never thrown.",
- method = "getFD",
- args = {}
- )
- public void test_getFD() {
- // Test for method FileDescriptor
- // FileInputStream.getFD()
- try {
-
- FileInputStream fis = new FileInputStream(fileName);
- assertTrue("Returned invalid fd", fis.getFD().valid());
- fis.close();
- assertTrue("Returned invalid fd", !fis.getFD().valid());
- } catch (FileNotFoundException e) {
- fail("Could not find : " + fileName);
- }
- catch (IOException e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * @tests FileInputStream#read()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "read",
- args = {}
- )
- public void test_read() throws IOException {
- is = new FileInputStream(fileName);
- int c = is.read();
- assertEquals("Test 1: Read returned incorrect char;",
- fileString.charAt(0), c);
-
- is.close();
- try {
- is.read();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests FileInputStream#read(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "read",
- args = {byte[].class}
- )
- public void test_read$B() throws IOException {
- byte[] buf1 = new byte[100];
- is = new FileInputStream(fileName);
- is.skip(3000);
- is.read(buf1);
- is.close();
- assertTrue("Test 1: Failed to read correct data.",
- new String(buf1, 0, buf1.length).equals(
- fileString.substring(3000, 3100)));
-
- is.close();
- try {
- is.read(buf1);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests FileInputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII() {
- // Test for method int FileInputStream.read(byte [], int, int)
- byte[] buf1 = new byte[100];
- try {
- is = new FileInputStream(fileName);
- is.skip(3000);
- is.read(buf1, 0, buf1.length);
- is.close();
- assertTrue("Failed to read correct data", new String(buf1, 0,
- buf1.length).equals(fileString.substring(3000, 3100)));
-
- } catch (Exception e) {
- fail("Exception during read test : " + e.getMessage());
- }
- }
-
- /**
- * @tests FileInputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Illegal argument checks.",
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII_Exception() throws IOException {
- byte[] buf = null;
- try {
- is = new FileInputStream(fileName);
- is.read(buf, 0, 0);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- } finally {
- is.close();
- }
-
- buf = new byte[1000];
- try {
- is = new FileInputStream(fileName);
- is.read(buf, -1, 0);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- } finally {
- is.close();
- }
-
- try {
- is = new FileInputStream(fileName);
- is.read(buf, 0, -1);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- } finally {
- is.close();
- }
-
- try {
- is = new FileInputStream(fileName);
- is.read(buf, -1, -1);
- fail("Test 4: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- } finally {
- is.close();
- }
-
- try {
- is = new FileInputStream(fileName);
- is.read(buf, 0, 1001);
- fail("Test 5: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- } finally {
- is.close();
- }
-
- try {
- is = new FileInputStream(fileName);
- is.read(buf, 1001, 0);
- fail("Test 6: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- } finally {
- is.close();
- }
-
- try {
- is = new FileInputStream(fileName);
- is.read(buf, 500, 501);
- fail("Test 7: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- } finally {
- is.close();
- }
-
- try {
- is = new FileInputStream(fileName);
- is.close();
- is.read(buf, 0, 100);
- fail("Test 8: IOException expected.");
- } catch (IOException e) {
- // Expected.
- } finally {
- is.close();
- }
- }
-
- /**
- * @tests FileInputStream#skip(long)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "skip",
- args = {long.class}
- )
- public void test_skipJ() throws IOException {
- byte[] buf1 = new byte[10];
- is = new FileInputStream(fileName);
- is.skip(1000);
- is.read(buf1, 0, buf1.length);
- assertTrue("Test 1: Failed to skip to correct position.",
- new String(buf1, 0, buf1.length).equals(
- fileString.substring(1000, 1010)));
-
- is.close();
- try {
- is.read();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests FileInputStream#skip(long)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies that skip(long) method throws IOException if " +
- "this method is called with negative argument.",
- method = "skip",
- args = {long.class}
- )
- public void test_skipNegativeArgumentJ() throws IOException{
-
- FileInputStream fis = new FileInputStream(fileName);
-
- try {
- fis.skip(-5);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected IOException
- } catch (Exception e) {
- fail("Test 2: IOException expected but found: " + e.getMessage());
- }
-
- fis.close();
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- try {
- fileName = System.getProperty("java.io.tmpdir");
- String separator = System.getProperty("file.separator");
- if (fileName.charAt(fileName.length() - 1) == separator.charAt(0))
- fileName = Support_PlatformFile.getNewPlatformFile(fileName,
- "input.tst");
- else
- fileName = Support_PlatformFile.getNewPlatformFile(fileName
- + separator, "input.tst");
- java.io.OutputStream fos = new FileOutputStream(fileName);
- fos.write(fileString.getBytes());
- fos.close();
- } catch (java.io.IOException e) {
- System.out.println("Exception during setup");
- e.printStackTrace();
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- try {
- if (is != null) {
- is.close();
- }
- new File(fileName).delete();
- } catch (IOException e) {
- // Ignored.
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/FileNotFoundExceptionTest.java b/luni/src/test/java/tests/api/java/io/FileNotFoundExceptionTest.java
deleted file mode 100644
index 6d625d0..0000000
--- a/luni/src/test/java/tests/api/java/io/FileNotFoundExceptionTest.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.FileNotFoundException;
-
-@TestTargetClass(FileNotFoundException.class)
-public class FileNotFoundExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.io.FileNotFoundException#FileNotFoundException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "FileNotFoundException",
- args = {}
- )
- public void test_Constructor() {
- try {
- if (true) // To avoid unreachable code compilation error.
- throw new FileNotFoundException();
- fail("Test 1: FileNotFoundException expected.");
- } catch (FileNotFoundException e) {
- assertNull("Test 2: Null expected for exceptions constructed without a message.",
- e.getMessage());
- }
- }
-
- /**
- * @tests java.io.FileNotFoundException#FileNotFoundException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "FileNotFoundException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- try {
- if (true) // To avoid unreachable code compilation error.
- throw new FileNotFoundException("Something went wrong.");
- fail("Test 1: FileNotFoundException expected.");
- } catch (FileNotFoundException e) {
- assertEquals("Test 2: Incorrect message;",
- "Something went wrong.", e.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/FileOutputStreamTest.java b/luni/src/test/java/tests/api/java/io/FileOutputStreamTest.java
deleted file mode 100644
index eb14a3c..0000000
--- a/luni/src/test/java/tests/api/java/io/FileOutputStreamTest.java
+++ /dev/null
@@ -1,451 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.File;
-import java.io.FileDescriptor;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(
- value = FileOutputStream.class,
- untestedMethods = {
- @TestTargetNew(
- method = "finalize",
- args = {},
- level = TestLevel.NOT_FEASIBLE,
- notes = "Hard to test since it requires that the " +
- "garbage collector runs; add test later."
- )
- }
-)
-public class FileOutputStreamTest extends junit.framework.TestCase {
-
- public String fileName;
-
- FileOutputStream fos;
-
- FileInputStream fis;
-
- File f;
-
- String tmpDirName = System.getProperty("java.io.tmpdir");
-
- File tmpDir = new File(tmpDirName);
-
- byte[] ibuf = new byte[4096];
-
- public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_java_io_File\nTest_java_io_FileDescriptor\nTest_java_io_FileInputStream\nTest_java_io_FileNotFoundException\nTest_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
-
- /**
- * @tests java.io.FileOutputStream#FileOutputStream(java.io.File)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "FileOutputStream",
- args = {java.io.File.class}
- )
- public void test_ConstructorLjava_io_File() throws Exception {
- try {
- fos = new FileOutputStream(tmpDir);
- fail("Test 1: FileNotFoundException expected.");
- } catch (FileNotFoundException e) {
- // Expected.
- }
-
- f = new File(fileName = System.getProperty("java.io.tmpdir"), "fos.tst");
- fos = new FileOutputStream(f);
- }
-
- /**
- * @tests java.io.FileOutputStream#FileOutputStream(java.lang.String,
- * boolean)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "FileOutputStream",
- args = {java.io.File.class, boolean.class}
- )
- public void test_ConstructorLjava_io_FileZ() throws Exception {
- try {
- fos = new FileOutputStream(tmpDir, false);
- fail("Test 1: FileNotFoundException expected.");
- } catch (FileNotFoundException e) {
- // Expected.
- }
-
- f = new File(tmpDirName, "fos.tst");
- fos = new FileOutputStream(f, false);
- fos.write("FZ1".getBytes(), 0, 3);
- fos.close();
- // Append data to existing file
- fos = new FileOutputStream(f, true);
- fos.write(fileString.getBytes());
- fos.close();
- byte[] buf = new byte[fileString.length() + 3];
- fis = new FileInputStream(f);
- fis.read(buf, 0, buf.length);
- assertTrue("Test 2: Failed to create appending stream.", new String(buf, 0,
- buf.length).equals("FZ1" + fileString));
- fis.close();
-
- // Check that the existing file is overwritten
- fos = new FileOutputStream(f, false);
- fos.write("FZ2".getBytes(), 0, 3);
- fos.close();
- fis = new FileInputStream(f);
- int bytesRead = fis.read(buf, 0, buf.length);
- assertTrue("Test 3: Failed to overwrite stream.", new String(buf, 0,
- bytesRead).equals("FZ2"));
- }
-
- /**
- * @tests java.io.FileOutputStream#FileOutputStream(java.io.FileDescriptor)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "FileOutputStream",
- args = {java.io.FileDescriptor.class}
- )
- public void test_ConstructorLjava_io_FileDescriptor() throws Exception {
- // Test for method java.io.FileOutputStream(java.io.FileDescriptor)
- f = new File(tmpDirName, "fos.tst");
- fileName = f.getAbsolutePath();
- fos = new FileOutputStream(fileName);
- fos.write('l');
- fos.close();
- fis = new FileInputStream(fileName);
- fos = new FileOutputStream(fis.getFD());
- fos.close();
- fis.close();
- }
-
- /**
- * @tests java.io.FileOutputStream#FileOutputStream(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "FileOutputStream",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() throws Exception {
- try {
- fos = new FileOutputStream(tmpDirName);
- fail("Test 1: FileNotFoundException expected.");
- } catch (FileNotFoundException e) {
- // Expected.
- }
-
- f = new File(tmpDirName, "fos.tst");
- fileName = f.getAbsolutePath();
- fos = new FileOutputStream(fileName);
- }
-
- /**
- * @tests java.io.FileOutputStream#FileOutputStream(java.lang.String,
- * boolean)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "FileOutputStream",
- args = {java.lang.String.class, boolean.class}
- )
- public void test_ConstructorLjava_lang_StringZ() throws Exception {
- try {
- fos = new FileOutputStream(tmpDirName, true);
- fail("Test 1: FileNotFoundException expected.");
- } catch (FileNotFoundException e) {
- // Expected.
- }
-
- f = new File(tmpDirName, "fos.tst");
- fos = new FileOutputStream(f.getPath(), false);
- fos.write("HI".getBytes(), 0, 2);
- fos.close();
- // Append data to existing file
- fos = new FileOutputStream(f.getPath(), true);
- fos.write(fileString.getBytes());
- fos.close();
- byte[] buf = new byte[fileString.length() + 2];
- fis = new FileInputStream(f.getPath());
- fis.read(buf, 0, buf.length);
- assertTrue("Failed to create appending stream", new String(buf, 0,
- buf.length).equals("HI" + fileString));
- fis.close();
-
- // Check that the existing file is overwritten
- fos = new FileOutputStream(f.getPath(), false);
- fos.write("HI".getBytes(), 0, 2);
- fos.close();
- fis = new FileInputStream(f.getPath());
- int bytesRead = fis.read(buf, 0, buf.length);
- assertTrue("Failed to overwrite stream", new String(buf, 0,
- bytesRead).equals("HI"));
- }
-
- /**
- * @tests java.io.FileOutputStream#close()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException not checked because it would be thrown" +
- "by a native method.",
- method = "close",
- args = {}
- )
- public void test_close() throws Exception {
- f = new File(System.getProperty("java.io.tmpdir"), "output.tst");
- fos = new FileOutputStream(f.getPath());
- fos.close();
-
- try {
- fos.write(fileString.getBytes());
- fail("Test 1: IOException expected.");
- } catch (java.io.IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.FileOutputStream#getFD()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException not checked because it never gets thrown.",
- method = "getFD",
- args = {}
- )
- public void test_getFD() throws Exception {
- // Test for method java.io.FileDescriptor
- // java.io.FileOutputStream.getFD()
- f = new File(fileName = System.getProperty("java.io.tmpdir"), "testfd");
- fileName = f.getAbsolutePath();
- fos = new FileOutputStream(f);
- assertTrue("Returned invalid fd", fos.getFD().valid());
- fos.close();
- assertTrue("Returned invalid fd", !fos.getFD().valid());
- }
-
- /**
- * @tests java.io.FileOutputStream#write(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "write",
- args = {byte[].class}
- )
- public void test_write$B() throws Exception {
- // Test for method void java.io.FileOutputStream.write(byte [])
- f = new File(System.getProperty("java.io.tmpdir"), "output.tst");
- fos = new FileOutputStream(f.getPath());
- fos.write(fileString.getBytes());
- fos.close();
- try {
- fos.write(fileString.getBytes());
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- fis = new FileInputStream(f.getPath());
- byte rbytes[] = new byte[4000];
- fis.read(rbytes, 0, fileString.length());
- assertTrue("Test 2: Incorrect string written or read.",
- new String(rbytes, 0, fileString.length()).equals(fileString));
- }
-
- /**
- * @tests java.io.FileOutputStream#write(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "write",
- args = {byte[].class, int.class, int.class}
- )
- public void test_write$BII() throws Exception {
- // Test for method void java.io.FileOutputStream.write(byte [], int,
- // int)
- f = new File(System.getProperty("java.io.tmpdir"), "output.tst");
- fos = new FileOutputStream(f.getPath());
- fos.write(fileString.getBytes(), 0, fileString.length());
- fis = new FileInputStream(f.getPath());
- byte rbytes[] = new byte[4000];
- fis.read(rbytes, 0, fileString.length());
- assertTrue("Incorrect bytes written", new String(rbytes, 0, fileString
- .length()).equals(fileString));
- }
-
- /**
- * @tests java.io.FileOutputStream#write(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "write",
- args = {int.class}
- )
- public void test_writeI() throws IOException {
- // Test for method void java.io.FileOutputStream.write(int)
- f = new File(System.getProperty("java.io.tmpdir"), "output.tst");
- fos = new FileOutputStream(f.getPath());
- fos.write('t');
- fos.close();
- try {
- fos.write(42);
- fail("Test: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- fis = new FileInputStream(f.getPath());
- assertEquals("Test 1: Incorrect char written or read.",
- 't', fis.read());
- }
-
- /**
- * @tests java.io.FileOutputStream#write(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Illegal argument and IOException checks.",
- method = "write",
- args = {byte[].class, int.class, int.class}
- )
- public void test_write$BII2() throws Exception {
- f = new File(tmpDirName, "output.tst");
- fos = new FileOutputStream(f.getPath());
-
- try {
- fos.write(null, 0, 0);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {}
-
- try {
- fos.write(new byte[1], -1, 0);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- fos.write(new byte[1], 0, -1);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- fos.write(new byte[1], 0, 5);
- fail("Test 4: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- fos.write(new byte[10], Integer.MAX_VALUE, 5);
- fail("Test 5: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- fos.write(new byte[10], 5, Integer.MAX_VALUE);
- fail("Test 6: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- fos.close();
- try {
- fos.write(new byte[10], 5, 4);
- fail("Test 7: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- }
-
- /**
- * @tests java.io.FileOutputStream#write(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "write",
- args = {byte[].class, int.class, int.class}
- )
- public void test_write$BII3() {
- try {
- new FileOutputStream(new FileDescriptor()).write(new byte[1], 0, 0);
- } catch (Exception e) {
- fail("Unexpected exception: " + e);
- }
- }
-
- /**
- * @tests java.io.FileOutputStream#getChannel()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies getChannel() method.",
- method = "getChannel",
- args = {}
- )
- @AndroidOnly("The position of the FileChannel for a file opened in " +
- "append mode is 0 for the RI and corresponds to the " +
- "next position to write to on Android.")
- public void test_getChannel() throws Exception {
- // Make sure that system properties are set correctly
- if (tmpDir == null) {
- throw new Exception("System property java.io.tmpdir not defined.");
- }
- File tmpfile = File.createTempFile("FileOutputStream", "tmp");
- tmpfile.deleteOnExit();
- FileOutputStream fos = new FileOutputStream(tmpfile);
- byte[] b = new byte[10];
- for (int i = 10; i < b.length; i++) {
- b[i] = (byte) i;
- }
- fos.write(b);
- fos.flush();
- fos.close();
- FileOutputStream f = new FileOutputStream(tmpfile, true);
- assertEquals(10, f.getChannel().position());
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- try {
- if (f != null)
- f.delete();
- if (fis != null)
- fis.close();
- if (fos != null)
- fos.close();
- } catch (Exception e) {}
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/FilePermissionTest.java b/luni/src/test/java/tests/api/java/io/FilePermissionTest.java
deleted file mode 100644
index 27f416d..0000000
--- a/luni/src/test/java/tests/api/java/io/FilePermissionTest.java
+++ /dev/null
@@ -1,261 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.File;
-import java.io.FilePermission;
-import java.security.PermissionCollection;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(FilePermission.class)
-public class FilePermissionTest extends junit.framework.TestCase {
-
- FilePermission readAllFiles = new FilePermission("<<ALL FILES>>", "read");
-
- FilePermission alsoReadAllFiles = new FilePermission("<<ALL FILES>>",
- "read");
-
- FilePermission allInCurrent = new FilePermission("*",
- "read, write, execute,delete");
-
- FilePermission readInCurrent = new FilePermission("*", "read");
-
- FilePermission readInFile = new FilePermission("aFile.file", "read");
-
- /**
- * @tests java.io.FilePermission#FilePermission(java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies FilePermission(java.lang.String, java.lang.String) constructor.",
- method = "FilePermission",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_String() {
- // Test for method java.io.FilePermission(java.lang.String,
- // java.lang.String)
- assertTrue("Used to test", true);
- FilePermission constructFile = new FilePermission("test constructor",
- "write");
- assertEquals("action given to the constructor did not correspond - constructor failed",
- "write", constructFile.getActions());
- assertTrue(
- "name given to the construcotr did not correspond - construcotr failed",
- constructFile.getName() == "test constructor");
-
- // Regression test for HARMONY-1050
- try {
- new FilePermission(null, "drink");
- fail("Expected IAE");
- } catch (IllegalArgumentException e) {
- // Expected
- }
-
- try {
- new FilePermission(null, "read");
- fail("Expected NPE");
- } catch (NullPointerException e) {
- // Expected
- }
-
- try {
- new FilePermission(null, null);
- fail("Expected IAE");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.io.FilePermission#getActions()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies getActions() method.",
- method = "getActions",
- args = {}
- )
- public void test_getActions() {
- // Test for method java.lang.String java.io.FilePermission.getActions()
- assertEquals("getActions should have returned only read", "read", readAllFiles
- .getActions());
- assertEquals("getActions should have returned all actions", "read,write,execute,delete", allInCurrent
- .getActions());
- }
-
- /**
- * @tests java.io.FilePermission#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies equals(java.lang.Object) method.",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- // test for method java.io.FilePermission.equals()
- assertTrue(
- "returned false when two instance of FilePermission is equal",
- readAllFiles.equals(alsoReadAllFiles));
- assertTrue(
- "returned true when two instance of FilePermission is not equal",
- !(readInCurrent.equals(readInFile)));
- }
-
- /**
- * @tests java.io.FilePermission#implies(java.security.Permission)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies implies(java.security.Permission) method.",
- method = "implies",
- args = {java.security.Permission.class}
- )
- public void test_impliesLjava_security_Permission() {
- // Test for method boolean
- // java.io.FilePermission.implies(java.security.Permission)
- assertTrue("Returned true for non-subset of actions", !readAllFiles
- .implies(allInCurrent));
- assertTrue("Returned true for non-subset of files", !allInCurrent
- .implies(readAllFiles));
- assertTrue("Returned false for subset of actions", allInCurrent
- .implies(readInCurrent));
- assertTrue("Returned false for subset of files", readAllFiles
- .implies(readInCurrent));
- assertTrue("Returned false for subset of files and actions",
- allInCurrent.implies(readInFile));
- assertTrue("Returned false for equal FilePermissions", readAllFiles
- .implies(alsoReadAllFiles));
-
- FilePermission fp3 = new FilePermission("/bob/*".replace('/',
- File.separatorChar), "read,write");
- FilePermission fp4 = new FilePermission("/bob/".replace('/',
- File.separatorChar), "write");
- assertTrue("returned true for same dir using * and not *", !fp3
- .implies(fp4));
- FilePermission fp5 = new FilePermission("/bob/file".replace('/',
- File.separatorChar), "write");
- assertTrue("returned false for same dir using * and file", fp3
- .implies(fp5));
-
- FilePermission fp6 = new FilePermission("/bob/".replace('/',
- File.separatorChar), "read,write");
- FilePermission fp7 = new FilePermission("/bob/*".replace('/',
- File.separatorChar), "write");
- assertTrue("returned false for same dir using not * and *", !fp6
- .implies(fp7));
- assertTrue("returned false for same subdir", fp6.implies(fp4));
-
- FilePermission fp8 = new FilePermission("/".replace('/',
- File.separatorChar), "read,write");
- FilePermission fp9 = new FilePermission("/".replace('/',
- File.separatorChar), "write");
- assertTrue("returned false for same dir", fp8.implies(fp9));
-
- FilePermission fp10 = new FilePermission("/".replace('/',
- File.separatorChar), "read,write");
- FilePermission fp11 = new FilePermission("/".replace('/',
- File.separatorChar), "write");
- assertTrue("returned false for same dir", fp10.implies(fp11));
-
- FilePermission fp12 = new FilePermission("/*".replace('/',
- File.separatorChar), "read,write");
- assertTrue("returned false for same dir using * and dir", !fp12
- .implies(fp10));
- }
-
- /**
- * @tests java.io.FilePermission#newPermissionCollection()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies newPermissionCollection() method.",
- method = "newPermissionCollection",
- args = {}
- )
- public void test_newPermissionCollection() {
- // test for method java.io.FilePermission.newPermissionCollection
- char s = File.separatorChar;
- FilePermission perm[] = new FilePermission[4];
- perm[0] = readAllFiles;
- perm[1] = allInCurrent;
- perm[2] = new FilePermission(s + "tmp" + s + "test" + s + "*",
- "read,write");
- perm[3] = new FilePermission(s + "tmp" + s + "test" + s
- + "collection.file", "read");
-
- PermissionCollection collect = perm[0].newPermissionCollection();
- for (int i = 0; i < perm.length; i++) {
- collect.add(perm[i]);
- }
- assertTrue("returned false for subset of files", collect
- .implies(new FilePermission("*", "write")));
- assertTrue("returned false for subset of name and action", collect
- .implies(new FilePermission(s + "tmp", "read")));
- assertTrue("returned true for non subset of file and action", collect
- .implies(readInFile));
-
- FilePermission fp1 = new FilePermission("/tmp/-".replace('/',
- File.separatorChar), "read");
- PermissionCollection fpc = fp1.newPermissionCollection();
- fpc.add(fp1);
- fpc.add(new FilePermission("/tmp/scratch/foo/*".replace('/',
- File.separatorChar), "write"));
- FilePermission fp2 = new FilePermission("/tmp/scratch/foo/file"
- .replace('/', File.separatorChar), "read,write");
- assertTrue("collection does not collate", fpc.implies(fp2));
- }
-
- /**
- * @tests java.io.FilePermission#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies hashCode() method.",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- // test method java.io.FilePermission.hasCode()
- assertTrue(
- "two equal filePermission instances returned different hashCode",
- readAllFiles.hashCode() == alsoReadAllFiles.hashCode());
- assertTrue(
- "two filePermission instances with same permission name returned same hashCode",
- readInCurrent.hashCode() != allInCurrent.hashCode());
-
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/FileReaderTest.java b/luni/src/test/java/tests/api/java/io/FileReaderTest.java
deleted file mode 100644
index 07f5416..0000000
--- a/luni/src/test/java/tests/api/java/io/FileReaderTest.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.FileWriter;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(FileReader.class)
-public class FileReaderTest extends junit.framework.TestCase {
-
- FileReader br;
-
- BufferedWriter bw;
-
- FileInputStream fis;
-
- File f;
-
- /**
- * @tests java.io.FileReader#FileReader(java.io.File)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "FileReader",
- args = {java.io.File.class}
- )
- public void test_ConstructorLjava_io_File() {
- // Test for method java.io.FileReader(java.io.File)
- try {
- bw = new BufferedWriter(new FileWriter(f.getPath()));
- bw.write(" After test string", 0, 18);
- bw.close();
- br = new FileReader(f);
- char[] buf = new char[100];
- int r = br.read(buf);
- br.close();
- assertEquals("Test 1: Failed to read correct chars",
- " After test string", new String(buf, 0, r));
- } catch (Exception e) {
- fail("Exception during Constructor test " + e.toString());
- }
-
- File noFile = new File(System.getProperty("java.io.tmpdir"), "noreader.tst");
- try {
- br = new FileReader(noFile);
- fail("Test 2: FileNotFoundException expected.");
- } catch (FileNotFoundException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.FileReader#FileReader(java.io.FileDescriptor)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies FileReader(java.io.FileDescriptor) constructor.",
- method = "FileReader",
- args = {java.io.FileDescriptor.class}
- )
- public void test_ConstructorLjava_io_FileDescriptor() {
- // Test for method java.io.FileReader(java.io.FileDescriptor)
- try {
- bw = new BufferedWriter(new FileWriter(f.getPath()));
- bw.write(" After test string", 0, 18);
- bw.close();
- FileInputStream fis = new FileInputStream(f.getPath());
- br = new FileReader(fis.getFD());
- char[] buf = new char[100];
- int r = br.read(buf);
- br.close();
- fis.close();
- assertEquals("Failed to read correct chars",
- " After test string", new String(buf, 0, r));
- } catch (Exception e) {
- fail("Exception during Constructor test " + e.toString());
- }
- }
-
- /**
- * @tests java.io.FileReader#FileReader(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "FileReader",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.io.FileReader(java.lang.String)
- try {
- bw = new BufferedWriter(new FileWriter(f.getPath()));
- bw.write(" After test string", 0, 18);
- bw.close();
- br = new FileReader(f.getPath());
- char[] buf = new char[100];
- int r = br.read(buf);
- br.close();
- assertEquals("Test 1: Failed to read correct chars",
- " After test string", new String(buf, 0, r));
- } catch (Exception e) {
- fail("Exception during Constructor test " + e.toString());
- }
-
- try {
- br = new FileReader(System.getProperty("java.io.tmpdir") + "/noreader.tst");
- fail("Test 2: FileNotFoundException expected.");
- } catch (FileNotFoundException e) {
- // Expected.
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
-
- f = new File(System.getProperty("java.io.tmpdir"), "reader.tst");
-
- if (f.exists()) {
- if (!f.delete()) {
- fail("Unable to delete test file");
- }
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
-
- try {
- bw.close();
- br.close();
- } catch (Exception e) {
- }
-
- try {
- if (fis != null)
- fis.close();
- } catch (Exception e) {
- }
- f.delete();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/FileTest.java b/luni/src/test/java/tests/api/java/io/FileTest.java
deleted file mode 100644
index 865717e..0000000
--- a/luni/src/test/java/tests/api/java/io/FileTest.java
+++ /dev/null
@@ -1,2533 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.File;
-import java.io.FileFilter;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.io.ObjectStreamClass;
-import java.io.ObjectStreamField;
-import java.io.RandomAccessFile;
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-
-import tests.support.Support_Exec;
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-@TestTargetClass(File.class)
-public class FileTest extends junit.framework.TestCase {
-
- /** Location to store tests in */
- private File tempDirectory;
-
- /** Temp file that does exist */
- private File tempFile;
-
- /** File separator */
- private String slash = File.separator;
-
- public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_File\nTest_FileDescriptor\nTest_FileInputStream\nTest_FileNotFoundException\nTest_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
-
- private static String platformId = "Android"
- + System.getProperty("java.vm.version").replace('.', '-');
-
- {
- // Delete all old temporary files
- File tempDir = new File(System.getProperty("java.io.tmpdir"));
- String[] files = tempDir.list();
- for (int i = 0; i < files.length; i++) {
- File f = new File(tempDir, files[i]);
- if (f.isDirectory()) {
- if (files[i].startsWith("hyts_resources"))
- deleteTempFolder(f);
- }
- if (files[i].startsWith("hyts_") || files[i].startsWith("hyjar_"))
- new File(tempDir, files[i]).delete();
- }
- }
-
- private void deleteTempFolder(File dir) {
- String files[] = dir.list();
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- if (f.isDirectory())
- deleteTempFolder(f);
- else {
- f.delete();
- }
- }
- dir.delete();
-
- }
-
- /**
- * @tests java.io.File#File(java.io.File, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "File",
- args = {java.io.File.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_io_FileLjava_lang_String() throws Exception {
- String error;
- String dirName = System.getProperty("java.io.tmpdir");
- String oldUserDir = System.getProperty("user.dir");
- System.setProperty("user.dir", dirName);
-
- File d = new File(dirName);
- File f = new File(d, "input.tst");
- if (!dirName.regionMatches((dirName.length() - 1), slash, 0, 1))
- dirName += slash;
- dirName += "input.tst";
- error = String.format("Test 1: Incorrect file created: %s; %s expected.", f.getPath(), dirName);
- assertTrue(error, f.getPath().equals(dirName));
-
- String fileName = null;
- try {
- f = new File(d, fileName);
- fail("Test 2: NullPointerException expected.");
- } catch (NullPointerException e) {
- }
-
- d = null;
- f = new File(d, "input.tst");
- error = String.format("Test 3: Incorrect file created: %s; %s expected.",
- f.getAbsolutePath(), dirName);
- assertTrue(error, f.getAbsolutePath().equals(dirName));
-
- // Regression test for Harmony-382
- File s = null;
- f = new File("/abc");
- d = new File(s, "/abc");
- assertEquals("Test 4: Incorrect file created;",
- f.getAbsolutePath(), d.getAbsolutePath());
-
- System.setProperty("user.dir", oldUserDir);
- }
-
- /**
- * @tests java.io.File#File(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies File(java.lang.String) constructor.",
- method = "File",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.io.File(java.lang.String)
- String fileName = null;
- try {
- new File(fileName);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- }
-
- fileName = System.getProperty("java.io.tmpdir");
- if (!fileName.regionMatches((fileName.length() - 1), slash, 0, 1))
- fileName += slash;
- fileName += "input.tst";
-
- File f = new File(fileName);
- assertTrue("Created incorrect file " + f.getPath(), f.getPath().equals(
- fileName));
- }
-
- /**
- * @tests java.io.File#File(java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "File",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_String() {
- String error;
- String dirName = null;
- String fileName = "input.tst";
-
- String userDir = System.getProperty("java.io.tmpdir");
- String oldUserDir = System.getProperty("user.dir");
- System.setProperty("user.dir", userDir);
-
- File f = new File(dirName, fileName);
- if (!userDir.regionMatches((userDir.length() - 1), slash, 0, 1))
- userDir += slash;
- userDir += "input.tst";
- error = String.format("Test 1: Incorrect file created: %s; %s expected.",
- f.getAbsolutePath(), userDir);
- assertTrue(error, f.getAbsolutePath().equals(userDir));
-
- dirName = System.getProperty("java.io.tmpdir");
- fileName = null;
- try {
- f = new File(dirName, fileName);
- fail("Test 2: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
-
- fileName = "input.tst";
- f = new File(dirName, fileName);
- assertTrue("Test 3: Incorrect file created.", f.getPath()
- .equals(userDir));
-
- // Regression test for Harmony-382
- String s = null;
- f = new File("/abc");
- File d = new File(s, "/abc");
- assertEquals("Test 4: Incorrect file created;", d.getAbsolutePath(), f
- .getAbsolutePath());
- assertEquals("Test3: Created Incorrect File", "/abc", f
- .getAbsolutePath());
-
- System.setProperty("user.dir", oldUserDir);
- }
-
- /**
- * @tests java.io.File#File(java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "File",
- args = {java.lang.String.class, java.lang.String.class}
- )
- @AndroidOnly("Test 3 incorrectly fails on the RI; Android is more " +
- "better at resolving path names.")
- public void test_ConstructorLjava_lang_StringLjava_lang_String_112270() {
- File ref1 = new File("/dir1/file1");
-
- File file1 = new File("/", "/dir1/file1");
- assertEquals("wrong result 1: " + file1, ref1.getPath(), file1
- .getPath());
- File file2 = new File("/", "//dir1/file1");
- assertTrue("wrong result 2: " + file2, file2.getPath().equals(
- ref1.getPath()));
- File file3 = new File("\\", "\\dir1\\file1");
- assertTrue("wrong result 3: " + file3, file3.getPath().equals(
- ref1.getPath()));
- File file4 = new File("\\", "\\\\dir1\\file1");
- assertTrue("wrong result 4: " + file4, file4.getPath().equals(
- ref1.getPath()));
-
- File ref2 = new File("/lib/content-types.properties");
- File file5 = new File("/", "lib/content-types.properties");
- assertTrue("wrong result 5: " + file5, file5.getPath().equals(
- ref2.getPath()));
-
- }
-
- /**
- * @tests java.io.File#File(java.io.File, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "File",
- args = {java.io.File.class, java.lang.String.class}
- )
- @AndroidOnly("Test 3 incorrectly fails on the RI; Android is more " +
- "better at resolving path names.")
- public void test_ConstructorLjava_io_FileLjava_lang_String_112270() {
- File ref1 = new File("/dir1/file1");
-
- File root = new File("/");
- File file1 = new File(root, "/dir1/file1");
- assertTrue("wrong result 1: " + file1, file1.getPath().equals(
- ref1.getPath()));
- File file2 = new File(root, "//dir1/file1");
- assertTrue("wrong result 2: " + file2, file2.getPath().equals(
- ref1.getPath()));
- File file3 = new File(root, "\\dir1\\file1");
- assertTrue("wrong result 3: " + file3, file3.getPath().equals(
- ref1.getPath()));
- File file4 = new File(root, "\\\\dir1\\file1");
- assertTrue("wrong result 4: " + file4, file4.getPath().equals(
- ref1.getPath()));
-
- File ref2 = new File("/lib/content-types.properties");
- File file5 = new File(root, "lib/content-types.properties");
- assertTrue("wrong result 5: " + file5, file5.getPath().equals(
- ref2.getPath()));
- }
-
- /**
- * @tests java.io.File#File(java.net.URI)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies File(java.net.URI) constructor with incorrect parameter.",
- method = "File",
- args = {java.net.URI.class}
- )
- public void test_ConstructorLjava_net_URI() {
- // Test for method java.io.File(java.net.URI)
- URI uri = null;
- try {
- new File(uri);
- fail("NullPointerException Not Thrown.");
- } catch (NullPointerException e) {
- }
-
- // invalid file URIs
- String[] uris = new String[] { "mailto:user@domain.com", // not
- // hierarchical
- "ftp:///path", // not file scheme
- "//host/path/", // not absolute
- "file://host/path", // non empty authority
- "file:///path?query", // non empty query
- "file:///path#fragment", // non empty fragment
- "file:///path?", "file:///path#" };
-
- for (int i = 0; i < uris.length; i++) {
- try {
- uri = new URI(uris[i]);
- } catch (URISyntaxException e) {
- fail("Unexpected exception:" + e);
- }
- try {
- new File(uri);
- fail("Expected IllegalArgumentException for new File(" + uri
- + ")");
- } catch (IllegalArgumentException e) {
- }
- }
-
- // a valid File URI
- try {
- File f = new File(new URI("file:///pa%20th/another\u20ac/pa%25th"));
- assertTrue("Created incorrect File " + f.getPath(), f.getPath()
- .equals(
- slash + "pa th" + slash + "another\u20ac" + slash
- + "pa%th"));
- } catch (URISyntaxException e) {
- fail("Unexpected exception:" + e);
- } catch (IllegalArgumentException e) {
- fail("Unexpected exception:" + e);
- }
- }
-
- /**
- * @tests java.io.File#canRead()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "canRead",
- args = {}
- )
- public void test_canRead() {
- // Test for method boolean java.io.File.canRead()
- // canRead only returns if the file exists so cannot be fully tested.
- File f = new File(System.getProperty("java.io.tmpdir"), platformId
- + "canRead.tst");
- try {
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- assertTrue("canRead returned false", f.canRead());
- f.delete();
- } catch (IOException e) {
- fail("Unexpected IOException: " + e.getMessage());
- } finally {
- f.delete();
- }
- }
-
- /**
- * @tests java.io.File#canWrite()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "canWrite",
- args = {}
- )
- public void test_canWrite() {
- // Test for method boolean java.io.File.canWrite()
- // canWrite only returns if the file exists so cannot be fully tested.
- File f = new File(System.getProperty("java.io.tmpdir"), platformId
- + "canWrite.tst");
- try {
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- assertTrue("canWrite returned false", f.canWrite());
- } catch (IOException e) {
- fail("Unexpected IOException: " + e.getMessage());
- } finally {
- f.delete();
- }
- }
-
- /**
- * @tests java.io.File#compareTo(java.io.File)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies compareTo(java.io.File) method.",
- method = "compareTo",
- args = {java.io.File.class}
- )
- public void test_compareToLjava_io_File() {
- File f1 = new File("thisFile.file");
- File f2 = new File("thisFile.file");
- File f3 = new File("thatFile.file");
- assertEquals("Equal files did not answer zero for compareTo", 0, f1
- .compareTo(f2));
- assertTrue("f3.compareTo(f1) did not result in value < 0", f3
- .compareTo(f1) < 0);
- assertTrue("f1.compareTo(f3) did not result in vale > 0", f1
- .compareTo(f3) > 0);
- }
-
- /**
- * @tests java.io.File#createNewFile()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException checked.",
- method = "createNewFile",
- args = {}
- )
- public void test_createNewFile_EmptyString() {
- File f = new File("");
- try {
- f.createNewFile();
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.File#createNewFile()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "createNewFile",
- args = {}
- )
- public void test_createNewFile() throws IOException {
- // Test for method java.io.File.createNewFile()
- String base = System.getProperty("java.io.tmpdir");
- boolean dirExists = true;
- int numDir = 1;
- File dir = new File(base, String.valueOf(numDir));
- // Making sure that the directory does not exist.
- while (dirExists) {
- // If the directory exists, add one to the directory number
- // (making
- // it a new directory name.)
- if (dir.exists()) {
- numDir++;
- dir = new File(base, String.valueOf(numDir));
- } else {
- dirExists = false;
- }
- }
-
- // Test for trying to create a file in a directory that does not
- // exist.
- try {
- // Try to create a file in a directory that does not exist
- File f1 = new File(dir, "tempfile.tst");
- f1.createNewFile();
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- dir.mkdir();
-
- File f1 = new File(dir, "tempfile.tst");
- File f2 = new File(dir, "tempfile.tst");
- f1.deleteOnExit();
- f2.deleteOnExit();
- dir.deleteOnExit();
- assertFalse("Test 2: File should not exist.", f1.isFile());
- f1.createNewFile();
- assertTrue("Test 3: File should exist.", f1.isFile());
- assertTrue("Test 4: File should exist.", f2.isFile());
- String dirName = f1.getParent();
- if (!dirName.endsWith(slash))
- dirName += slash;
- assertTrue("Test 5: File saved in the wrong directory.",
- dirName.equals(dir.getPath() + slash));
- assertEquals("Test 6: File saved with incorrect name;",
- "tempfile.tst", f1.getName());
-
- // Test for creating a file that already exists.
- assertFalse("Test 7: File already exists, createNewFile should " +
- "return false.", f2.createNewFile());
-
- // Trying to create an illegal file.
- String sep = File.separator;
- f1 = new File(sep+"a"+sep+".."+sep+".."+sep);
- try {
- f1.createNewFile();
- fail("Test 8: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- f1 = new File(base);
- assertFalse("Test 9: False expected when trying to create an " +
- "existing file", f1.createNewFile());
- }
-
- /**
- * @tests java.io.File#createTempFile(java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "createTempFile",
- args = {java.lang.String.class, java.lang.String.class}
- )
- @AndroidOnly("The RI does not throw an IOException when an illegal" +
- "file prefix is passed to createTempFile.")
- public void test_createTempFileLjava_lang_StringLjava_lang_String() {
- // Test for method java.io.File.createTempFile(String, String)
- // Error protection against using a suffix without a "."?
- File f1 = null;
- File f2 = null;
- try {
- f1 = File.createTempFile("hyts_abc", ".tmp");
- f2 = File.createTempFile("hyts_tf", null);
- String fileLocation = f1.getParent();
- if (!fileLocation.endsWith(slash))
- ;
- fileLocation += slash;
- String tempDir = System.getProperty("java.io.tmpdir");
- if (!tempDir.endsWith(slash))
- tempDir += slash;
- assertTrue(
- "File did not save to the default temporary-file location.",
- fileLocation.equals(tempDir));
-
- // Test to see if correct suffix was used to create the tempfile.
- File currentFile;
- String fileName;
- // Testing two files, one with suffix ".tmp" and one with null
- for (int i = 0; i < 2; i++) {
- currentFile = i == 0 ? f1 : f2;
- fileName = currentFile.getPath();
- assertTrue("File Created With Incorrect Suffix.", fileName
- .endsWith(".tmp"));
- }
-
- // Tests to see if the correct prefix was used to create the
- // tempfiles.
- fileName = f1.getName();
- assertTrue("Test 1: File Created With Incorrect Prefix.", fileName
- .startsWith("hyts_abc"));
- fileName = f2.getName();
- assertTrue("Test 2: File Created With Incorrect Prefix.", fileName
- .startsWith("hyts_tf"));
-
- // Tests for creating a tempfile with a filename shorter than 3
- // characters.
- try {
- File f3 = File.createTempFile("ab", ".tst");
- f3.delete();
- fail("IllegalArgumentException Not Thrown.");
- } catch (IllegalArgumentException e) {
- }
- try {
- File f3 = File.createTempFile("a", ".tst");
- f3.delete();
- fail("IllegalArgumentException Not Thrown.");
- } catch (IllegalArgumentException e) {
- }
- try {
- File f3 = File.createTempFile("", ".tst");
- f3.delete();
- fail("IllegalArgumentException Not Thrown.");
- } catch (IllegalArgumentException e) {
- }
- try {
- // Providing an illegal file prefix.
- File f3 = File.createTempFile("/../../../../../", null);
- f3.delete();
- fail("IOException not thrown");
- } catch (IOException e) {
- }
-
- } catch (IOException e) {
- fail("Unexpected IOException: " + e.getMessage());
- } finally {
- if (f1 != null)
- f1.delete();
- if (f2 != null)
- f2.delete();
- }
- }
-
- /**
- * @tests java.io.File#createTempFile(java.lang.String, java.lang.String,
- * java.io.File)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "createTempFile",
- args = {java.lang.String.class, java.lang.String.class, java.io.File.class}
- )
- public void test_createTempFileLjava_lang_StringLjava_lang_StringLjava_io_File() {
- // Test for method java.io.File.createTempFile(String, String, File)
- File f1 = null;
- File f2 = null;
- String base = System.getProperty("java.io.tmpdir");
- try {
-
- // Test to make sure that the tempfile was saved in the correct
- // location
- // and with the correct prefix/suffix.
- f1 = File.createTempFile("hyts_tf", null, null);
- File dir = new File(base);
- f2 = File.createTempFile("hyts_tf", ".tmp", dir);
- File currentFile;
- String fileLocation;
- String fileName;
- for (int i = 0; i < 2; i++) {
- currentFile = i == 0 ? f1 : f2;
- fileLocation = currentFile.getParent();
- if (!fileLocation.endsWith(slash))
- fileLocation += slash;
- if (!base.endsWith(slash))
- base += slash;
- assertTrue(
- "File not created in the default temporary-file location.",
- fileLocation.equals(base));
- fileName = currentFile.getName();
- assertTrue("File created with incorrect suffix.", fileName
- .endsWith(".tmp"));
- assertTrue("File created with incorrect prefix.", fileName
- .startsWith("hyts_tf"));
- currentFile.delete();
- }
-
- // Test for creating a tempfile in a directory that does not exist.
- int dirNumber = 1;
- boolean dirExists = true;
- // Set dir to a non-existent directory inside the temporary
- // directory
- dir = new File(base, String.valueOf(dirNumber));
- // Making sure that the directory does not exist.
- while (dirExists) {
- // If the directory exists, add one to the directory number
- // (making it
- // a new directory name.)
- if (dir.exists()) {
- dirNumber++;
- dir = new File(base, String.valueOf(dirNumber));
- } else {
- dirExists = false;
- }
- }
- try {
- // Try to create a file in a directory that does not exist
- File f3 = File.createTempFile("hyts_tf", null, dir);
- f3.delete();
- fail("IOException not thrown");
- } catch (IOException e) {
- }
- dir.delete();
-
- // Tests for creating a tempfile with a filename shorter than 3
- // characters.
- try {
- File f4 = File.createTempFile("ab", null, null);
- f4.delete();
- fail("IllegalArgumentException not thrown.");
- } catch (IllegalArgumentException e) {
- }
- try {
- File f4 = File.createTempFile("a", null, null);
- f4.delete();
- fail("IllegalArgumentException not thrown.");
- } catch (IllegalArgumentException e) {
- }
- try {
- File f4 = File.createTempFile("", null, null);
- f4.delete();
- fail("IllegalArgumentException not thrown.");
- } catch (IllegalArgumentException e) {
- }
-
- } catch (IOException e) {
- fail("Unexpected IOException: " + e.getMessage());
- } finally {
- if (f1 != null)
- f1.delete();
- if (f2 != null)
- f1.delete();
- }
- }
-
- /**
- * @tests java.io.File#delete()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "delete",
- args = {}
- )
- public void test_delete() {
- // Test for method boolean java.io.File.delete()
- try {
- File dir = new File(System.getProperty("java.io.tmpdir"), platformId
- + "filechk");
- dir.mkdir();
- assertTrue("Directory Does Not Exist", dir.exists()
- && dir.isDirectory());
- File f = new File(dir, "filechk.tst");
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- assertTrue("Error Creating File For Delete Test", f.exists());
- dir.delete();
- assertTrue("Directory Should Not Have Been Deleted.", dir.exists());
- f.delete();
- assertTrue("File Was Not Deleted", !f.exists());
- dir.delete();
- assertTrue("Directory Was Not Deleted", !dir.exists());
- } catch (IOException e) {
- fail("Unexpected IOException During Delete Test : "
- + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.File#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies equals() method.",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean java.io.File.equals(java.lang.Object)
- File f1 = new File("filechk.tst");
- File f2 = new File("filechk.tst");
- File f3 = new File("xxxx");
-
- assertTrue("Equality test failed", f1.equals(f2));
- assertTrue("Files Should Not Return Equal.", !f1.equals(f3));
-
- f3 = new File("FiLeChK.tst");
- boolean onWindows = File.separatorChar == '\\';
- boolean onUnix = File.separatorChar == '/';
- if (onWindows)
- assertTrue("Files Should Return Equal.", f1.equals(f3));
- else if (onUnix)
- assertTrue("Files Should NOT Return Equal.", !f1.equals(f3));
-
- try {
- f1 = new File(System.getProperty("java.io.tmpdir"), "casetest.tmp");
- f2 = new File(System.getProperty("java.io.tmpdir"), "CaseTest.tmp");
- new FileOutputStream(f1).close(); // create the file
- if (f1.equals(f2)) {
- try {
- new FileInputStream(f2);
- } catch (IOException e) {
- fail("File system is case sensitive");
- }
- } else {
- boolean exception = false;
- try {
- new FileInputStream(f2);
- } catch (IOException e) {
- exception = true;
- }
- assertTrue("File system is case insensitive", exception);
- }
- f1.delete();
- } catch (IOException e) {
- fail("Unexpected using case sensitive test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.File#exists()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "exists",
- args = {}
- )
- public void test_exists() {
- // Test for method boolean java.io.File.exists()
- try {
- File f = new File(System.getProperty("java.io.tmpdir"), platformId
- + "exists.tst");
- assertTrue("Exists returned true for non-existent file", !f
- .exists());
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- assertTrue("Exists returned false file", f.exists());
- f.delete();
- } catch (IOException e) {
- fail("Unexpected IOException During Test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.File#getAbsoluteFile()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "getAbsoluteFile",
- args = {}
- )
- public void test_getAbsoluteFile() {
- // Test for method java.io.File getAbsoluteFile()
- String base = System.getProperty("java.io.tmpdir");
- if (!base.endsWith(slash))
- base += slash;
- File f = new File(base, "temp.tst");
- File f2 = f.getAbsoluteFile();
- assertEquals("Test 1: Incorrect File Returned.", 0, f2.compareTo(f
- .getAbsoluteFile()));
- f = new File(base + "Temp" + slash + slash + "temp.tst");
- f2 = f.getAbsoluteFile();
- assertEquals("Test 2: Incorrect File Returned.", 0, f2.compareTo(f
- .getAbsoluteFile()));
- f = new File(base + slash + ".." + slash + "temp.tst");
- f2 = f.getAbsoluteFile();
- assertEquals("Test 3: Incorrect File Returned.", 0, f2.compareTo(f
- .getAbsoluteFile()));
- f.delete();
- f2.delete();
- }
-
- /**
- * @tests java.io.File#getAbsolutePath()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "getAbsolutePath",
- args = {}
- )
- public void test_getAbsolutePath() {
- // Test for method java.lang.String java.io.File.getAbsolutePath()
- String base = System.getProperty("java.io.tmpdir");
- if (!base.regionMatches((base.length() - 1), slash, 0, 1))
- base += slash;
- File f = new File(base, "temp.tst");
- assertTrue("Test 1: Incorrect path returned.", f.getAbsolutePath()
- .equals(base + "temp.tst"));
- f = new File(base + "Temp" + slash + slash + slash + "Testing" + slash
- + "temp.tst");
- assertTrue("Test 2: Incorrect path returned.", f.getAbsolutePath()
- .equals(base + "Temp" + slash + "Testing" + slash + "temp.tst"));
- f = new File(base + "a" + slash + slash + ".." + slash + "temp.tst");
- assertTrue("Test 3: Incorrect path returned." + f.getAbsolutePath(), f
- .getAbsolutePath().equals(
- base + "a" + slash + ".." + slash + "temp.tst"));
- f.delete();
- }
-
- /**
- * @tests java.io.File#getCanonicalFile()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException not checked since it may only occur if" +
- "the native access to the filesystem fails.",
- method = "getCanonicalFile",
- args = {}
- )
- public void test_getCanonicalFile() {
- // Test for method java.io.File.getCanonicalFile()
- try {
- String base = System.getProperty("java.io.tmpdir");
- if (!base.endsWith(slash))
- base += slash;
- File f = new File(base, "temp.tst");
- File f2 = f.getCanonicalFile();
- assertEquals("Test 1: Incorrect file returned.", 0, f2
- .getCanonicalFile().compareTo(f.getCanonicalFile()));
- f = new File(base + "Temp" + slash + slash + "temp.tst");
- f2 = f.getCanonicalFile();
- assertEquals("Test 2: Incorrect file returned.", 0, f2
- .getCanonicalFile().compareTo(f.getCanonicalFile()));
- f = new File(base + "Temp" + slash + slash + ".." + slash
- + "temp.tst");
- f2 = f.getCanonicalFile();
- assertEquals("Test 3: Incorrect file returned.", 0, f2
- .getCanonicalFile().compareTo(f.getCanonicalFile()));
-
- // Test for when long directory/file names in Windows
- boolean onWindows = File.separatorChar == '\\';
- // String userDir = System.getProperty("java.io.tmpdir");
- if (onWindows) {
- File testdir = new File(base, "long-" + platformId);
- testdir.mkdir();
- File dir = new File(testdir, "longdirectory" + platformId);
- try {
- dir.mkdir();
- f = new File(dir, "longfilename.tst");
- f2 = f.getCanonicalFile();
- assertEquals("Test 4: Incorrect file returned.",
- 0, f2.getCanonicalFile().compareTo(
- f.getCanonicalFile()));
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- f2 = new File(testdir + slash + "longdi~1" + slash
- + "longfi~1.tst");
- File canonicalf2 = f2.getCanonicalFile();
- /*
- * If the "short file name" doesn't exist, then assume that
- * the 8.3 file name compatibility is disabled.
- */
- if (canonicalf2.exists()) {
- assertTrue("Test 5: Incorrect file returned: "
- + canonicalf2, canonicalf2.compareTo(f
- .getCanonicalFile()) == 0);
- }
- } finally {
- f.delete();
- f2.delete();
- dir.delete();
- testdir.delete();
- }
- }
- } catch (IOException e) {
- fail ("Unexpected IOException during Test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.File#getCanonicalPath()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException not checked since it may only occur if" +
- "the native access to the filesystem fails.",
- method = "getCanonicalPath",
- args = {}
- )
- public void test_getCanonicalPath() {
- // Test for method java.lang.String java.io.File.getCanonicalPath()
- // Should work for Unix/Windows.
- String dots = "..";
- String expected;
- String error;
- String tmpDir = System.getProperty("java.io.tmpdir");
- String oldUserDir = System.getProperty("user.dir");
- System.setProperty("user.dir", tmpDir);
- try {
- String base = new File(tmpDir).getCanonicalPath();
- if (!base.regionMatches((base.length() - 1), slash, 0, 1))
- base += slash;
- File f = new File(base, "temp.tst");
- assertEquals("Test 1: Incorrect Path Returned.", base + "temp.tst", f
- .getCanonicalPath());
- f = new File(base + "Temp" + slash + dots + slash + "temp.tst");
- assertEquals("Test 2: Incorrect Path Returned.", base + "temp.tst", f
- .getCanonicalPath());
-
- // Finding a non-existent directory for tests 3 and 4
- // This is necessary because getCanonicalPath is case sensitive and
- // could
- // cause a failure in the test if the directory exists but with
- // different
- // case letters (e.g "Temp" and "temp")
- int dirNumber = 1;
- boolean dirExists = true;
- File dir1 = new File(base, String.valueOf(dirNumber));
- while (dirExists) {
- if (dir1.exists()) {
- dirNumber++;
- dir1 = new File(base, String.valueOf(dirNumber));
- } else {
- dirExists = false;
- }
- }
- f = new File(base + dirNumber + slash + dots + slash + dirNumber + slash
- + "temp.tst");
- assertEquals("Test 3: Incorrect path returned.", base + dirNumber + slash
- + "temp.tst", f.getCanonicalPath());
- f = new File(base + dirNumber + slash + "Temp" + slash + dots + slash + "Test"
- + slash + "temp.tst");
- assertEquals("Test 4: Incorrect path returned.", base + dirNumber + slash + "Test"
- + slash + "temp.tst", f.getCanonicalPath());
-
- f = new File("1234.567");
- expected = System.getProperty("user.dir") + "/1234.567";
- error = String.format("Test 5: Incorrect path %s returned; %s expected.",
- f.getCanonicalPath(), expected);
- assertTrue(error, f.getCanonicalPath().equals(expected));
-
- } catch (IOException e) {
- fail("Unexpected IOException During Test : " + e.getMessage());
- } finally {
- System.setProperty("user.dir", oldUserDir);
- }
- }
-
- /**
- * @tests java.io.File#getName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies getName() method.",
- method = "getName",
- args = {}
- )
- public void test_getName() {
- // Test for method java.lang.String java.io.File.getName()
- File f = new File("name.tst");
- assertEquals("Test 1: Returned incorrect name",
- "name.tst", f.getName());
-
- f = new File("");
- assertTrue("Test 2: Returned incorrect name", f.getName().equals(""));
-
- f.delete();
- }
-
- /**
- * @tests java.io.File#getParent()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies getParent() method.",
- method = "getParent",
- args = {}
- )
- public void test_getParent() throws Exception {
- // Test for method java.lang.String java.io.File.getParent()
- String dir = System.getProperty("java.io.tmpdir");
- if (dir == null)
- throw new Exception("System property java.io.tmpdir not defined.");
-
- File f = new File("p.tst");
- assertNull("Test 1: Incorrect path returned", f.getParent());
- f = new File(dir, "p.tst");
- assertTrue("Test 2: Incorrect path returned",
- f.getParent().equals(dir));
- try {
- f.delete();
- } catch (Exception e) {
- fail("Unexpected exception during tests : " + e.getMessage());
- }
-
- File f1 = new File("/directory");
- assertTrue("Wrong parent test 1", f1.getParent().equals(slash));
- f1 = new File("/directory/file");
- assertTrue("Wrong parent test 2", f1.getParent().equals(
- slash + "directory"));
- f1 = new File("directory/file");
- assertEquals("Wrong parent test 3", "directory", f1.getParent());
- f1 = new File("/");
- assertNull("Wrong parent test 4", f1.getParent());
- f1 = new File("directory");
- assertNull("Wrong parent test 5", f1.getParent());
-
- if (File.separatorChar == '\\' && new File("d:/").isAbsolute()) {
- f1 = new File("d:/directory");
- assertTrue("Wrong parent test 1a", f1.getParent().equals(
- "d:" + slash));
- f1 = new File("d:/directory/file");
- assertTrue("Wrong parent test 2a", f1.getParent().equals(
- "d:" + slash + "directory"));
- f1 = new File("d:directory/file");
- assertEquals("Wrong parent test 3a",
- "d:directory", f1.getParent());
- f1 = new File("d:/");
- assertNull("Wrong parent test 4a", f1.getParent());
- f1 = new File("d:directory");
- assertEquals("Wrong parent test 5a", "d:", f1.getParent());
- }
- }
-
- /**
- * @tests java.io.File#getParentFile()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies getParentFile() method.",
- method = "getParentFile",
- args = {}
- )
- public void test_getParentFile() {
- // Test for method java.io.File.getParentFile()
- File f = new File("tempfile.tst");
- assertNull("Incorrect path returned", f.getParentFile());
- f = new File(System.getProperty("java.io.tmpdir"), "tempfile1.tmp");
- File f2 = new File(System.getProperty("java.io.tmpdir"), "tempfile2.tmp");
- File f3 = new File(System.getProperty("java.io.tmpdir"), "/a/tempfile.tmp");
- assertEquals("Incorrect file returned", 0, f.getParentFile().compareTo(
- f2.getParentFile()));
- assertTrue("Incorrect file returned", f.getParentFile().compareTo(
- f3.getParentFile()) != 0);
- f.delete();
- f2.delete();
- f3.delete();
- }
-
- /**
- * @tests java.io.File#getPath()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies getPath() method.",
- method = "getPath",
- args = {}
- )
- public void test_getPath() {
- System.setProperty("user.home", System.getProperty("java.io.tmpdir"));
- String base = System.getProperty("user.home");
- String fname;
- File f1;
- if (!base.regionMatches((base.length() - 1), slash, 0, 1))
- base += slash;
- fname = base + "filechk.tst";
- f1 = new File(base, "filechk.tst");
- File f2 = new File("filechk.tst");
- File f3 = new File("c:");
- File f4 = new File(base + "a" + slash + slash + ".." + slash
- + "filechk.tst");
- assertTrue("getPath returned incorrect path(f1) " + f1.getPath(), f1
- .getPath().equals(fname));
- assertTrue("getPath returned incorrect path(f2) " + f2.getPath(), f2
- .getPath().equals("filechk.tst"));
- assertTrue("getPath returned incorrect path(f3) " + f3.getPath(), f3
- .getPath().equals("c:"));
- assertTrue("getPath returned incorrect path(f4) " + f4.getPath(), f4
- .getPath().equals(
- base + "a" + slash + ".." + slash + "filechk.tst"));
- f1.delete();
- f2.delete();
- f3.delete();
- f4.delete();
- }
-
- /**
- * @tests java.io.File#isAbsolute()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies isAbsolute() method.",
- method = "isAbsolute",
- args = {}
- )
- public void test_isAbsolute() {
- // Test for method boolean java.io.File.isAbsolute()
- if (File.separatorChar == '\\') {
- File f = new File("c:\\test");
- File f1 = new File("\\test");
- // One or the other should be absolute on Windows or CE
- assertTrue("Absolute returned false", (f.isAbsolute() && !f1
- .isAbsolute())
- || (!f.isAbsolute() && f1.isAbsolute()));
- } else {
- File f = new File("/test");
- assertTrue("Absolute returned false", f.isAbsolute());
- }
- assertTrue("Non-Absolute returned true", !new File("../test")
- .isAbsolute());
- }
-
- /**
- * @tests java.io.File#isDirectory()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "isDirectory",
- args = {}
- )
- public void test_isDirectory() {
- // Test for method boolean java.io.File.isDirectory()
-
- String base = System.getProperty("java.io.tmpdir");
- if (!base.regionMatches((base.length() - 1), slash, 0, 1))
- base += slash;
- File f = new File(base);
- assertTrue("Test 1: Directory returned false", f.isDirectory());
- f = new File(base + "zxzxzxz" + platformId);
- assertTrue("Test 2: (Not created) directory returned true.", !f
- .isDirectory());
- f.mkdir();
- try {
- assertTrue("Test 3: Directory returned false.", f.isDirectory());
- } finally {
- f.delete();
- }
- }
-
- /**
- * @tests java.io.File#isFile()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "isFile",
- args = {}
- )
- public void test_isFile() {
- // Test for method boolean java.io.File.isFile()
- try {
- String base = System.getProperty("java.io.tmpdir");
- File f = new File(base);
- assertTrue("Directory returned true as being a file.", !f.isFile());
- if (!base.regionMatches((base.length() - 1), slash, 0, 1))
- base += slash;
- f = new File(base, platformId + "amiafile");
- assertTrue("Non-existent file returned true", !f.isFile());
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- assertTrue("File returned false", f.isFile());
- f.delete();
- } catch (IOException e) {
- fail("IOException during isFile " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.File#isHidden()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "isHidden",
- args = {}
- )
- public void test_isHidden() {
- // Test for method boolean java.io.File.isHidden()
- boolean onUnix = File.separatorChar == '/';
-
- try {
- File f = File.createTempFile("hyts_", ".tmp");
- // On Unix hidden files are marked with a "." at the beginning
- // of the file name.
- if (onUnix) {
- File f2 = new File(System.getProperty("java.io.tmpdir"), ".test.tst" + platformId);
- FileOutputStream fos2 = new FileOutputStream(f2);
- fos2.close();
- assertTrue("File returned hidden on Unix", !f.isHidden());
- assertTrue("File returned visible on Unix", f2.isHidden());
- assertTrue("File did not delete.", f2.delete());
- } else {
- // For windows, the file is being set hidden by the attrib
- // command.
- Runtime r = Runtime.getRuntime();
- assertTrue("File returned hidden", !f.isHidden());
- Process p = r.exec("attrib +h \"" + f.getAbsolutePath() + "\"");
- p.waitFor();
- assertTrue("File returned visible", f.isHidden());
- p = r.exec("attrib -h \"" + f.getAbsolutePath() + "\"");
- p.waitFor();
- assertTrue("File returned hidden", !f.isHidden());
- }
- f.delete();
- } catch (IOException e) {
- fail("Unexpected IOException during test : " + e.getMessage());
- } catch (InterruptedException e) {
- fail("Unexpected InterruptedException during test : "
- + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.File#lastModified()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "lastModified",
- args = {}
- )
- public void test_lastModified() {
- // Test for method long java.io.File.lastModified()
- try {
- File f = new File(System.getProperty("java.io.tmpdir"), platformId
- + "lModTest.tst");
- f.delete();
- long lastModifiedTime = f.lastModified();
- assertEquals("LastModified Time Should Have Returned 0.",
- 0, lastModifiedTime);
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- f.setLastModified(315550800000L);
- lastModifiedTime = f.lastModified();
- assertTrue("LastModified Time Incorrect: " + lastModifiedTime,
- lastModifiedTime == 315550800000L);
- f.delete();
-
- // Regression for Harmony-2146
- f = new File("/../");
- assertTrue(f.lastModified() > 0);
- } catch (IOException e) {
- fail("Unexpected IOException during test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.File#length()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "length",
- args = {}
- )
- public void test_length() throws Exception {
- // Test for method long java.io.File.length()
- try {
- File f = new File(System.getProperty("java.io.tmpdir"), platformId
- + "input.tst");
- assertEquals("File length should have returned 0.", 0, f.length());
- FileOutputStream fos = new FileOutputStream(f);
- fos.write(fileString.getBytes());
- fos.close();
- assertTrue("Incorrect file length returned: " + f.length(), f
- .length() == fileString.length());
- f.delete();
- } catch (IOException e) {
- fail("Unexpected IOException during test : " + e.getMessage());
- }
-
- // regression test for Harmony-1497
- File f = File.createTempFile("cts", ".tmp");
- f.deleteOnExit();
- RandomAccessFile raf = new RandomAccessFile(f, "rwd");
- raf.write(0x41);
- assertEquals(1, f.length());
- }
-
- /**
- * @tests java.io.File#list()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "list",
- args = {}
- )
- public void test_list() {
- // Test for method java.lang.String [] java.io.File.list()
-
- String base = System.getProperty("java.io.tmpdir");
- // Old test left behind "garbage files" so this time it creates a
- // directory
- // that is guaranteed not to already exist (and deletes it afterward.)
- int dirNumber = 1;
- boolean dirExists = true;
- File dir = null;
- dir = new File(base, platformId + String.valueOf(dirNumber));
- while (dirExists) {
- if (dir.exists()) {
- dirNumber++;
- dir = new File(base, String.valueOf(dirNumber));
- } else {
- dirExists = false;
- }
- }
-
- String[] flist = dir.list();
-
- assertNull("Method list() Should Have Returned null.", flist);
-
- assertTrue("Could not create parent directory for list test", dir
- .mkdir());
-
- String[] files = { "mtzz1.xx", "mtzz2.xx", "mtzz3.yy", "mtzz4.yy" };
- try {
- assertEquals("Method list() Should Have Returned An Array Of Length 0.",
- 0, dir.list().length);
-
- File file = new File(dir, "notADir.tst");
- try {
- FileOutputStream fos = new FileOutputStream(file);
- fos.close();
- assertNull(
- "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
- file.list());
- } catch (IOException e) {
- fail("Unexpected IOException during test : " + e.getMessage());
- } finally {
- file.delete();
- }
-
- try {
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- }
- } catch (IOException e) {
- fail("Unexpected IOException during test : " + e.getMessage());
- }
-
- flist = dir.list();
- if (flist.length != files.length) {
- fail("Incorrect list returned");
- }
-
- // Checking to make sure the correct files were are listed in the
- // array.
- boolean[] check = new boolean[flist.length];
- for (int i = 0; i < check.length; i++)
- check[i] = false;
- for (int i = 0; i < files.length; i++) {
- for (int j = 0; j < flist.length; j++) {
- if (flist[j].equals(files[i])) {
- check[i] = true;
- break;
- }
- }
- }
- int checkCount = 0;
- for (int i = 0; i < check.length; i++) {
- if (check[i] == false)
- checkCount++;
- }
- assertEquals("Invalid file returned in listing", 0, checkCount);
-
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- f.delete();
- }
-
- assertTrue("Could not delete parent directory for list test.", dir
- .delete());
- } finally {
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- f.delete();
- }
- dir.delete();
- }
-
- }
-
- /**
- * @tests java.io.File#listFiles()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "listFiles",
- args = {}
- )
- public void test_listFiles() {
- // Test for method java.io.File.listFiles()
-
- try {
- String base = System.getProperty("java.io.tmpdir");
- // Finding a non-existent directory to create.
- int dirNumber = 1;
- boolean dirExists = true;
- File dir = new File(base, platformId + String.valueOf(dirNumber));
- // Making sure that the directory does not exist.
- while (dirExists) {
- // If the directory exists, add one to the directory number
- // (making
- // it a new directory name.)
- if (dir.exists()) {
- dirNumber++;
- dir = new File(base, String.valueOf(dirNumber));
- } else {
- dirExists = false;
- }
- }
- // Test for attempting to cal listFiles on a non-existent directory.
- assertNull("listFiles Should Return Null.", dir.listFiles());
-
- assertTrue("Failed To Create Parent Directory.", dir.mkdir());
-
- String[] files = { "1.tst", "2.tst", "3.tst", "" };
- try {
- assertEquals("listFiles Should Return An Array Of Length 0.", 0, dir
- .listFiles().length);
-
- File file = new File(dir, "notADir.tst");
- try {
- FileOutputStream fos = new FileOutputStream(file);
- fos.close();
- assertNull(
- "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
- file.listFiles());
- } catch (IOException e) {
- fail("Unexpected IOException during test : " + e.getMessage());
- } finally {
- file.delete();
- }
-
- for (int i = 0; i < (files.length - 1); i++) {
- File f = new File(dir, files[i]);
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- }
-
- new File(dir, "doesNotExist.tst");
- File[] flist = dir.listFiles();
-
- // Test to make sure that only the 3 files that were created are
- // listed.
- assertEquals("Incorrect Number Of Files Returned.",
- 3, flist.length);
-
- // Test to make sure that listFiles can read hidden files.
- boolean onUnix = File.separatorChar == '/';
- boolean onWindows = File.separatorChar == '\\';
- if (onWindows) {
- files[3] = "4.tst";
- File f = new File(dir, "4.tst");
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- Runtime r = Runtime.getRuntime();
- Process p = r.exec("attrib +h \"" + f.getPath() + "\"");
- p.waitFor();
- }
- if (onUnix) {
- files[3] = ".4.tst";
- File f = new File(dir, ".4.tst");
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- }
- flist = dir.listFiles();
- assertEquals("Incorrect Number Of Files Returned.",
- 4, flist.length);
-
- // Checking to make sure the correct files were are listed in
- // the array.
- boolean[] check = new boolean[flist.length];
- for (int i = 0; i < check.length; i++)
- check[i] = false;
- for (int i = 0; i < files.length; i++) {
- for (int j = 0; j < flist.length; j++) {
- if (flist[j].getName().equals(files[i])) {
- check[i] = true;
- break;
- }
- }
- }
- int checkCount = 0;
- for (int i = 0; i < check.length; i++) {
- if (check[i] == false)
- checkCount++;
- }
- assertEquals("Invalid file returned in listing", 0, checkCount);
-
- if (onWindows) {
- Runtime r = Runtime.getRuntime();
- Process p = r.exec("attrib -h \""
- + new File(dir, files[3]).getPath() + "\"");
- p.waitFor();
- }
-
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- f.delete();
- }
- assertTrue("Parent Directory Not Deleted.", dir.delete());
- } finally {
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- f.delete();
- }
- dir.delete();
- }
- } catch (IOException e) {
- fail("Unexpected IOException during test : " + e.getMessage());
- } catch (InterruptedException e) {
- fail("Unexpected InterruptedException during test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.File#listFiles(java.io.FileFilter)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "listFiles",
- args = {java.io.FileFilter.class}
- )
- public void test_listFilesLjava_io_FileFilter() {
- // Test for method java.io.File.listFiles(File Filter filter)
-
- String base = System.getProperty("java.io.tmpdir");
- // Finding a non-existent directory to create.
- int dirNumber = 1;
- boolean dirExists = true;
- File baseDir = new File(base, platformId + String.valueOf(dirNumber));
- // Making sure that the directory does not exist.
- while (dirExists) {
- // If the directory exists, add one to the directory number (making
- // it a new directory name.)
- if (baseDir.exists()) {
- dirNumber++;
- baseDir = new File(base, String.valueOf(dirNumber));
- } else {
- dirExists = false;
- }
- }
-
- // Creating a filter that catches directories.
- FileFilter dirFilter = new FileFilter() {
- public boolean accept(File f) {
- if (f.isDirectory())
- return true;
- else
- return false;
- }
- };
-
- assertNull("listFiles Should Return Null.", baseDir
- .listFiles(dirFilter));
-
- assertTrue("Failed To Create Parent Directory.", baseDir.mkdir());
-
- File dir1 = null;
- String[] files = { "1.tst", "2.tst", "3.tst" };
- try {
- assertEquals("listFiles Should Return An Array Of Length 0.", 0, baseDir
- .listFiles(dirFilter).length);
-
- File file = new File(baseDir, "notADir.tst");
- try {
- FileOutputStream fos = new FileOutputStream(file);
- fos.close();
- assertNull(
- "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
- file.listFiles(dirFilter));
- } catch (IOException e) {
- fail("Unexpected IOException During Test.");
- } finally {
- file.delete();
- }
-
- try {
- for (int i = 0; i < files.length; i++) {
- File f = new File(baseDir, files[i]);
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- }
- } catch (IOException e) {
- fail("Unexpected IOException during test : " + e.getMessage());
- }
- dir1 = new File(baseDir, "Temp1");
- dir1.mkdir();
-
- // Creating a filter that catches files.
- FileFilter fileFilter = new FileFilter() {
- public boolean accept(File f) {
- if (f.isFile())
- return true;
- else
- return false;
- }
- };
-
- // Test to see if the correct number of directories are returned.
- File[] directories = baseDir.listFiles(dirFilter);
- assertEquals("Incorrect Number Of Directories Returned.",
- 1, directories.length);
-
- // Test to see if the directory was saved with the correct name.
- assertEquals("Incorrect Directory Returned.", 0, directories[0]
- .compareTo(dir1));
-
- // Test to see if the correct number of files are returned.
- File[] flist = baseDir.listFiles(fileFilter);
- assertTrue("Incorrect Number Of Files Returned.",
- flist.length == files.length);
-
- // Checking to make sure the correct files were are listed in the
- // array.
- boolean[] check = new boolean[flist.length];
- for (int i = 0; i < check.length; i++)
- check[i] = false;
- for (int i = 0; i < files.length; i++) {
- for (int j = 0; j < flist.length; j++) {
- if (flist[j].getName().equals(files[i])) {
- check[i] = true;
- break;
- }
- }
- }
- int checkCount = 0;
- for (int i = 0; i < check.length; i++) {
- if (check[i] == false)
- checkCount++;
- }
- assertEquals("Invalid file returned in listing", 0, checkCount);
-
- for (int i = 0; i < files.length; i++) {
- File f = new File(baseDir, files[i]);
- f.delete();
- }
- dir1.delete();
- assertTrue("Parent Directory Not Deleted.", baseDir.delete());
- } finally {
- for (int i = 0; i < files.length; i++) {
- File f = new File(baseDir, files[i]);
- f.delete();
- }
- if (dir1 != null)
- dir1.delete();
- baseDir.delete();
- }
- }
-
- /**
- * @tests java.io.File#listFiles(java.io.FilenameFilter)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "listFiles",
- args = {java.io.FilenameFilter.class}
- )
- public void test_listFilesLjava_io_FilenameFilter() {
- // Test for method java.io.File.listFiles(FilenameFilter filter)
-
- String base = System.getProperty("java.io.tmpdir");
- // Finding a non-existent directory to create.
- int dirNumber = 1;
- boolean dirExists = true;
- File dir = new File(base, platformId + String.valueOf(dirNumber));
- // Making sure that the directory does not exist.
- while (dirExists) {
- // If the directory exists, add one to the directory number (making
- // it a new directory name.)
- if (dir.exists()) {
- dirNumber++;
- dir = new File(base, platformId + String.valueOf(dirNumber));
- } else {
- dirExists = false;
- }
- }
-
- // Creating a filter that catches "*.tst" files.
- FilenameFilter tstFilter = new FilenameFilter() {
- public boolean accept(File f, String fileName) {
- // If the suffix is ".tst" then send it to the array
- if (fileName.endsWith(".tst"))
- return true;
- else
- return false;
- }
- };
-
- assertNull("listFiles Should Return Null.",
- dir.listFiles(tstFilter));
-
- assertTrue("Failed To Create Parent Directory.", dir.mkdir());
-
- String[] files = { "1.tst", "2.tst", "3.tmp" };
- try {
- assertEquals("listFiles Should Return An Array Of Length 0.", 0, dir
- .listFiles(tstFilter).length);
-
- File file = new File(dir, "notADir.tst");
- try {
- FileOutputStream fos = new FileOutputStream(file);
- fos.close();
- assertNull(
- "listFiles Should Have Returned Null When Used On A File Instead Of A Directory.",
- file.listFiles(tstFilter));
- } catch (IOException e) {
- fail("Unexpected IOException during test : " + e.getMessage());
- } finally {
- file.delete();
- }
-
- try {
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- }
- } catch (IOException e) {
- fail("Unexpected IOException During Test : " + e.getMessage());
- }
-
- // Creating a filter that catches "*.tmp" files.
- FilenameFilter tmpFilter = new FilenameFilter() {
- public boolean accept(File f, String fileName) {
- // If the suffix is ".tmp" then send it to the array
- if (fileName.endsWith(".tmp"))
- return true;
- else
- return false;
- }
- };
-
- // Tests to see if the correct number of files were returned.
- File[] flist = dir.listFiles(tstFilter);
- assertEquals("Incorrect Number Of Files Passed Through tstFilter.",
- 2, flist.length);
- for (int i = 0; i < flist.length; i++)
- assertTrue("File Should Not Have Passed The tstFilter.",
- flist[i].getPath().endsWith(".tst"));
-
- flist = dir.listFiles(tmpFilter);
- assertEquals("Incorrect Number Of Files Passed Through tmpFilter.",
- 1, flist.length);
- assertTrue("File Should Not Have Passed The tmpFilter.", flist[0]
- .getPath().endsWith(".tmp"));
-
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- f.delete();
- }
- assertTrue("Parent Directory Not Deleted.", dir.delete());
- } finally {
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- f.delete();
- }
- dir.delete();
- }
- }
-
- /**
- * @tests java.io.File#list(java.io.FilenameFilter)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "list",
- args = {java.io.FilenameFilter.class}
- )
- public void test_listLjava_io_FilenameFilter() {
- // Test for method java.lang.String []
- // java.io.File.list(java.io.FilenameFilter)
-
- String base = System.getProperty("java.io.tmpdir");
- // Old test left behind "garbage files" so this time it creates a
- // directory
- // that is guaranteed not to already exist (and deletes it afterward.)
- int dirNumber = 1;
- boolean dirExists = true;
- File dir = new File(base, platformId + String.valueOf(dirNumber));
- while (dirExists) {
- if (dir.exists()) {
- dirNumber++;
- dir = new File(base, String.valueOf(dirNumber));
- } else {
- dirExists = false;
- }
- }
-
- FilenameFilter filter = new FilenameFilter() {
- public boolean accept(File dir, String name) {
- return !name.equals("mtzz1.xx");
- }
- };
-
- String[] flist = dir.list(filter);
- assertNull("Method list(FilenameFilter) Should Have Returned Null.",
- flist);
-
- assertTrue("Could not create parent directory for test", dir.mkdir());
-
- String[] files = { "mtzz1.xx", "mtzz2.xx", "mtzz3.yy", "mtzz4.yy" };
- try {
- /*
- * Do not return null when trying to use list(Filename Filter) on a
- * file rather than a directory. All other "list" methods return
- * null for this test case.
- */
- /*
- * File file = new File(dir, "notADir.tst"); try { FileOutputStream
- * fos = new FileOutputStream(file); fos.close(); } catch
- * (IOException e) { fail("Unexpected IOException During
- * Test."); } flist = dir.list(filter); assertNull("listFiles
- * Should Have Returned Null When Used On A File Instead Of A
- * Directory.", flist); file.delete();
- */
-
- flist = dir.list(filter);
- assertEquals("Array Of Length 0 Should Have Returned.",
- 0, flist.length);
-
- try {
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- FileOutputStream fos = new FileOutputStream(f);
- fos.close();
- }
- } catch (IOException e) {
- fail("Unexpected IOException during test : " + e.getMessage());
- }
-
- flist = dir.list(filter);
-
- if (flist.length != files.length - 1) {
- fail("Incorrect list returned");
- }
-
- // Checking to make sure the correct files were are listed in the
- // array.
- boolean[] check = new boolean[flist.length];
- for (int i = 0; i < check.length; i++)
- check[i] = false;
- String[] wantedFiles = { "mtzz2.xx", "mtzz3.yy", "mtzz4.yy" };
- for (int i = 0; i < wantedFiles.length; i++) {
- for (int j = 0; j < flist.length; j++) {
- if (flist[j].equals(wantedFiles[i])) {
- check[i] = true;
- break;
- }
- }
- }
- int checkCount = 0;
- for (int i = 0; i < check.length; i++) {
- if (check[i] == false)
- checkCount++;
- }
- assertEquals("Invalid file returned in listing", 0, checkCount);
-
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- f.delete();
- }
- assertTrue("Could not delete parent directory for test.", dir
- .delete());
- } finally {
- for (int i = 0; i < files.length; i++) {
- File f = new File(dir, files[i]);
- f.delete();
- }
- dir.delete();
- }
- }
-
- /**
- * @tests java.io.File#listRoots()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies listRoots() method.",
- method = "listRoots",
- args = {}
- )
- public void test_listRoots() {
- // Test for method java.io.File.listRoots()
-
- File[] roots = File.listRoots();
- boolean onUnix = File.separatorChar == '/';
- boolean onWindows = File.separatorChar == '\\';
- if (onUnix) {
- assertEquals("Incorrect Number Of Root Directories.",
- 1, roots.length);
- String fileLoc = roots[0].getPath();
- assertTrue("Incorrect Root Directory Returned.", fileLoc
- .startsWith(slash));
- } else if (onWindows) {
- // Need better test for Windows
- assertTrue("Incorrect Number Of Root Directories.",
- roots.length > 0);
- }
- }
-
- /**
- * @tests java.io.File#mkdir()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "mkdir",
- args = {}
- )
- public void test_mkdir() throws IOException {
- // Test for method boolean java.io.File.mkdir()
-
- String base = System.getProperty("java.io.tmpdir");
- // Old test left behind "garbage files" so this time it creates a
- // directory
- // that is guaranteed not to already exist (and deletes it afterward.)
- int dirNumber = 1;
- boolean dirExists = true;
- File dir = new File(base, String.valueOf(dirNumber));
- while (dirExists) {
- if (dir.exists()) {
- dirNumber++;
- dir = new File(base, String.valueOf(dirNumber));
- } else {
- dirExists = false;
- }
- }
-
- assertTrue("mkdir failed", dir.mkdir() && dir.exists());
- dir.deleteOnExit();
-
- String longDirName = "abcdefghijklmnopqrstuvwx";// 24 chars
- StringBuilder sb = new StringBuilder(dir + File.separator);
- StringBuilder sb2 = new StringBuilder(dir + File.separator);
-
- // Test make a long path
- while (dir.getCanonicalPath().length() < 256 - longDirName.length()) {
- sb.append(longDirName + File.separator);
- dir = new File(sb.toString());
- assertTrue("mkdir failed", dir.mkdir() && dir.exists());
- dir.deleteOnExit();
- }
-
- while (dir.getCanonicalPath().length() < 256) {
- sb.append(0);
- dir = new File(sb.toString());
- assertTrue("mkdir " + dir.getCanonicalPath().length() + " failed",
- dir.mkdir() && dir.exists());
- dir.deleteOnExit();
- }
-
- // Test make many paths
- while (dir.getCanonicalPath().length() < 256) {
- sb2.append(0);
- dir = new File(sb2.toString());
- assertTrue("mkdir " + dir.getCanonicalPath().length() + " failed",
- dir.mkdir() && dir.exists());
- dir.deleteOnExit();
- }
- }
-
- /**
- * @tests java.io.File#mkdirs()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "mkdirs",
- args = {}
- )
- public void test_mkdirs() {
- // Test for method boolean java.io.File.mkdirs()
-
- String userHome = System.getProperty("java.io.tmpdir");
- if (!userHome.endsWith(slash))
- userHome += slash;
- File f = new File(userHome + "mdtest" + platformId + slash + "mdtest2",
- "p.tst");
- File g = new File(userHome + "mdtest" + platformId + slash + "mdtest2");
- File h = new File(userHome + "mdtest" + platformId);
- f.mkdirs();
- try {
- assertTrue("Base Directory not created", h.exists());
- assertTrue("Directories not created", g.exists());
- assertTrue("File not created", f.exists());
- } finally {
- f.delete();
- g.delete();
- h.delete();
- }
- }
-
- /**
- * @tests java.io.File#renameTo(java.io.File)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "renameTo",
- args = {java.io.File.class}
- )
- public void test_renameToLjava_io_File() {
- // Test for method boolean java.io.File.renameTo(java.io.File)
- String base = System.getProperty("java.io.tmpdir");
- File dir = new File(base, platformId);
- dir.mkdir();
- File f = new File(dir, "xxx.xxx");
- File rfile = new File(dir, "yyy.yyy");
- File f2 = new File(dir, "zzz.zzz");
- try {
- FileOutputStream fos = new FileOutputStream(f);
- fos.write(fileString.getBytes());
- fos.close();
- long lengthOfFile = f.length();
-
- rfile.delete(); // in case it already exists
-
- try {
- f.renameTo(null);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
-
- assertTrue("Test 2: File rename failed.", f.renameTo(rfile));
- assertTrue("Test 3: File rename failed.", rfile.exists());
- assertTrue("Test 4: Size Of File Changed.",
- rfile.length() == lengthOfFile);
-
- fos = new FileOutputStream(rfile);
- fos.close();
-
- f2.delete(); // in case it already exists
- assertTrue("Test 5: File rename failed.", rfile.renameTo(f2));
- assertTrue("Test 6: File rename failed.", f2.exists());
- } catch (IOException e) {
- fail("Unexpected IOException during test : " + e.getMessage());
- } finally {
- f.delete();
- rfile.delete();
- f2.delete();
- dir.delete();
- }
- }
-
- /**
- * @tests java.io.File#setLastModified(long)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "setLastModified",
- args = {long.class}
- )
- public void test_setLastModifiedJ() {
- // Test for method java.io.File.setLastModified()
- File f1 = null;
- try {
- // f1 = File.createTempFile("hyts_tf" , ".tmp");
- // jclRM does not include File.createTempFile
- f1 = new File(System.getProperty("java.io.tmpdir"),
- platformId + "hyts_tf_slm.tst");
- f1.createNewFile();
- long orgTime = f1.lastModified();
- // Subtracting 100 000 milliseconds from the orgTime of File f1
- f1.setLastModified(orgTime - 100000);
- long lastModified = f1.lastModified();
- assertTrue("Test 1: LastModifed time incorrect: " + lastModified,
- lastModified == (orgTime - 100000));
- // Subtracting 10 000 000 milliseconds from the orgTime of File f1
- f1.setLastModified(orgTime - 10000000);
- lastModified = f1.lastModified();
- assertTrue("Test 2: LastModifed time incorrect: " + lastModified,
- lastModified == (orgTime - 10000000));
- // Adding 100 000 milliseconds to the orgTime of File f1
- f1.setLastModified(orgTime + 100000);
- lastModified = f1.lastModified();
- assertTrue("Test 3: LastModifed time incorrect: " + lastModified,
- lastModified == (orgTime + 100000));
- // Adding 10 000 000 milliseconds from the orgTime of File f1
- f1.setLastModified(orgTime + 10000000);
- lastModified = f1.lastModified();
- assertTrue("Test 4: LastModifed time incorrect: " + lastModified,
- lastModified == (orgTime + 10000000));
- // Trying to set time to an exact number
- f1.setLastModified(315550800000L);
- lastModified = f1.lastModified();
- assertTrue("Test 5: LastModified time incorrect: " + lastModified,
- lastModified == 315550800000L);
- String osName = System.getProperty("os.name", "unknown");
- if (osName.equals("Windows 2000") || osName.equals("Windows NT")) {
- // Trying to set time to a large exact number
- boolean result = f1.setLastModified(4354837199000L);
- long next = f1.lastModified();
- // Dec 31 23:59:59 EST 2107 is overflow on FAT file systems, and
- // the call fails
- assertTrue("Test 6: LastModified time incorrect: " + next,
- !result || next == 4354837199000L);
- }
- // Trying to set time to a negative number
- try {
- f1.setLastModified(-25);
- fail("IllegalArgumentException not thrown.");
- } catch (IllegalArgumentException e) {
- }
- } catch (IOException e) {
- fail("Unexpected IOException during test : " + e.getMessage());
- } finally {
- if (f1 != null)
- f1.delete();
- }
- }
-
- /**
- * @tests java.io.File#setReadOnly()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "setReadOnly",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "canWrite",
- args = {}
- )
- })
- @KnownFailure("canWrite() returns true even when a file is marked " +
- "read-only (Test 2). It is also possible to open this file " +
- "for writing (Test 3).")
- public void test_setReadOnly() {
- // Test for method java.io.File.setReadOnly()
-
- File f1 = null;
- File f2 = null;
- Runtime r = Runtime.getRuntime();
- Process p;
- try {
- f1 = File.createTempFile("hyts_tf", ".tmp");
- f2 = File.createTempFile("hyts_tf", ".tmp");
-
- assertTrue("Test 1: File is read-only." , f1.canWrite());
- f1.setReadOnly();
- assertTrue("Test 2: File is not read-only." , !f1.canWrite());
-
- try {
- // Attempt to write to a file that is read-only.
- new FileOutputStream(f1);
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- p = r.exec("chmod +w " + f1.getAbsolutePath());
- p.waitFor();
-
- assertTrue("Test 4: File is read-only." , f1.canWrite());
- try {
- FileOutputStream fos = new FileOutputStream(f1);
- fos.write(fileString.getBytes());
- fos.close();
- assertTrue("Test 5: Unable to write to the file.",
- f1.length() == fileString.length());
- } catch (IOException e) {
- fail("Test 6: Unexpected IOException while attempting to " +
- "write to the file. " + e);
- }
- assertTrue("Test 7: File has not been deleted.", f1.delete());
-
- // Assert is flawed because canWrite does not work.
- // assertTrue("File f2 Is Set To ReadOnly." , f2.canWrite());
- FileOutputStream fos = new FileOutputStream(f2);
- // Write to a file.
- fos.write(fileString.getBytes());
- fos.close();
- f2.setReadOnly();
- // Assert is flawed because canWrite does not work.
- // assertTrue("File f2 Is Not Set To ReadOnly." , !f2.canWrite());
- try {
- // Attempt to write to a file that has previously been written
- // to.
- // and is now set to read only.
- fos = new FileOutputStream(f2);
- fail("Test 8: IOException expected.");
- } catch (IOException e) {
- }
- p = r.exec("chmod +w " + f2.getAbsolutePath());
- p.waitFor();
- assertTrue("Test 9: File is read-only.", f2.canWrite());
- try {
- fos = new FileOutputStream(f2);
- fos.write(fileString.getBytes());
- fos.close();
- } catch (IOException e) {
- fail("Test 10: Unexpected IOException while attempting to " +
- "write to the file. " + e);
- }
- f2.setReadOnly();
- assertTrue("Test 11: File has not been deleted.", f2.delete());
- // Similarly, trying to delete a read-only directory should succeed
- f2 = new File(System.getProperty("java.io.tmpdir"), "deltestdir");
- f2.mkdir();
- f2.setReadOnly();
- assertTrue("Test 12: Directory has not been deleted.",
- f2.delete());
- assertTrue("Test 13: Directory has not been deleted.",
- ! f2.exists());
-
- } catch (IOException e) {
- fail("Test 14: Unexpected IOException: " + e.getMessage());
- } catch (InterruptedException e) {
- fail("Test 15: Unexpected InterruptedException: " + e);
- } finally {
- if (f1 != null)
- f1.delete();
- if (f2 != null)
- f2.delete();
- }
- }
-
- /**
- * @tests java.io.File#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies toString() method.",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.io.File.toString()
- String fileName = System.getProperty("java.io.tmpdir") + slash + "input.tst";
- File f = new File(fileName);
- assertTrue("Incorrect string returned", f.toString().equals(fileName));
-
- if (File.separatorChar == '\\') {
- String result = new File("c:\\").toString();
- assertTrue("Removed backslash: " + result, result.equals("c:\\"));
- }
- }
-
- /**
- * @tests java.io.File#toURI()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies toURI() method.",
- method = "toURI",
- args = {}
- )
- public void test_toURI() {
- // Test for method java.io.File.toURI()
- try {
- // Need a directory that exists
- File dir = new File(System.getProperty("java.io.tmpdir"));
-
- // Test for toURI when the file is a directory.
- String newURIPath = dir.getAbsolutePath();
- newURIPath = newURIPath.replace(File.separatorChar, '/');
- if (!newURIPath.startsWith("/"))
- newURIPath = "/" + newURIPath;
- if (!newURIPath.endsWith("/"))
- newURIPath += '/';
-
- URI uri = dir.toURI();
- assertTrue("Test 1A: Incorrect URI Returned.", new File(uri)
- .equals(dir.getAbsoluteFile()));
- assertTrue("Test 1B: Incorrect URI Returned.", uri.equals(new URI(
- "file", null, newURIPath, null, null)));
-
- // Test for toURI with a file name with illegal chars.
- File f = new File(dir, "te% \u20ac st.tst");
- newURIPath = f.getAbsolutePath();
- newURIPath = newURIPath.replace(File.separatorChar, '/');
- if (!newURIPath.startsWith("/"))
- newURIPath = "/" + newURIPath;
-
- uri = f.toURI();
- assertTrue("Test 2A: Incorrect URI Returned.", new File(uri)
- .equals(f.getAbsoluteFile()));
- assertTrue("Test 2B: Incorrect URI Returned.", uri.equals(new URI(
- "file", null, newURIPath, null, null)));
-
- // Regression test for HARMONY-3207
- dir = new File(""); // current directory
- uri = dir.toURI();
- assertTrue("Test current dir: URI does not end with slash.",
- uri.toString().endsWith("/"));
- } catch (URISyntaxException e1) {
- fail("Unexpected URISyntaxException: " + e1);
- }
- }
-
- /**
- * @tests java.io.File#toURI()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies that toURI() method works with URIs created with null parameters.",
- method = "toURI",
- args = {}
- )
- public void test_toURI2() {
-
- File f = new File(System.getProperty("java.io.tmpdir"), "a/b/c/../d/e/./f");
-
- String path = f.getAbsolutePath();
- path = path.replace(File.separatorChar, '/');
- if (!path.startsWith("/"))
- path = "/" + path;
-
- try {
- URI uri1 = new URI("file", null, path, null);
- URI uri2 = f.toURI();
- assertEquals("uris not equal", uri1, uri2);
- } catch (URISyntaxException e1) {
- fail("Unexpected URISyntaxException," + e1);
- }
- }
-
- /**
- * @tests java.io.File#toURL()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "toURL",
- args = {}
- )
- public void test_toURL() {
- // Test for method java.io.File.toURL()
-
- try {
- // Need a directory that exists
- File dir = new File(System.getProperty("java.io.tmpdir"));
-
- // Test for toURL when the file is a directory.
- String newDirURL = dir.getAbsolutePath();
- newDirURL = newDirURL.replace(File.separatorChar, '/');
- if (newDirURL.startsWith("/"))
- newDirURL = "file:" + newDirURL;
- else
- newDirURL = "file:/" + newDirURL;
- if (!newDirURL.endsWith("/"))
- newDirURL += '/';
- assertEquals("Test 1: Incorrect URL returned;", newDirURL,
- dir.toURL().toString());
-
- // Test for toURL with a file.
- File f = new File(dir, "test.tst");
- String newURL = f.getAbsolutePath();
- newURL = newURL.replace(File.separatorChar, '/');
- if (newURL.startsWith("/"))
- newURL = "file:" + newURL;
- else
- newURL = "file:/" + newURL;
- assertEquals("Test 2: Incorrect URL returned;", newURL,
- f.toURL().toString());
- } catch (java.net.MalformedURLException e) {
- fail("Unexpected java.net.MalformedURLException during test.");
- }
- }
-
- /**
- * @tests java.io.File#toURL()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "toURL",
- args = {}
- )
- public void test_toURL2() {
-
- File f = new File(System.getProperty("java.io.tmpdir"), "a/b/c/../d/e/./f");
-
- String path = f.getAbsolutePath();
- path = path.replace(File.separatorChar, '/');
- if (!path.startsWith("/"))
- path = "/" + path;
-
- try {
- URL url1 = new URL("file", "", path);
- URL url2 = f.toURL();
- assertEquals("urls not equal", url1, url2);
- } catch (MalformedURLException e) {
- fail("Unexpected MalformedURLException," + e);
- }
- }
-
- /**
- * @tests java.io.File#toURL()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "toURL",
- args = {}
- )
- @AndroidOnly("Incorrectly fails on the RI.")
- public void test_toURL3() throws MalformedURLException {
- File dir = new File(""); // current directory
- String newDirURL = dir.toURL().toString();
- assertTrue("Test 1: URL does not end with slash.",
- newDirURL.endsWith("/"));
- }
-
- /**
- * @tests java.io.File#deleteOnExit()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "deleteOnExit",
- args = {}
- )
- @AndroidOnly("This test only runs on Android because it instantiates " +
- "a second Dalvik VM.")
- public void test_deleteOnExit() throws IOException, InterruptedException {
- String cts = System.getProperty("java.io.tmpdir");
- File dir = new File(cts + "/hello");
- dir.mkdir();
- assertTrue(dir.exists());
- File subDir = new File(cts + "/hello/world");
- subDir.mkdir();
- assertTrue(subDir.exists());
-
- Support_Exec.execJava(new String[] {
- "tests.support.Support_DeleteOnExitTest",
- dir.getAbsolutePath(), subDir.getAbsolutePath() },
- new String[] {}, false);
- Thread.sleep(2000);
- assertFalse(dir.exists());
- assertFalse(subDir.exists());
- }
-
- /**
- * @tests serialization
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "regression test",
- method = "!Serialization",
- args = {}
- )
- public void test_objectStreamClass_getFields() throws Exception {
- //Regression for HARMONY-2674
- ObjectStreamClass objectStreamClass = ObjectStreamClass
- .lookup(File.class);
- ObjectStreamField[] objectStreamFields = objectStreamClass.getFields();
- assertEquals(1, objectStreamFields.length);
- ObjectStreamField objectStreamField = objectStreamFields[0];
- assertEquals("path", objectStreamField.getName());
- assertEquals(String.class, objectStreamField.getType());
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() throws Exception {
- // Make sure that system properties are set correctly
- String userDir = System.getProperty("java.io.tmpdir");
- if (userDir == null)
- throw new Exception("System property java.io.tmpdir not defined.");
- System.setProperty("java.io.tmpdir", userDir);
-
- /** Setup the temporary directory */
- if (!userDir.regionMatches((userDir.length() - 1), slash, 0, 1))
- userDir += slash;
- tempDirectory = new File(userDir + "tempDir"
- + String.valueOf(System.currentTimeMillis()));
- if (!tempDirectory.mkdir())
- System.out.println("Setup for FileTest failed (1).");
-
- /** Setup the temporary file */
- tempFile = new File(tempDirectory, "tempfile");
- FileOutputStream tempStream;
- try {
- tempStream = new FileOutputStream(tempFile.getPath(), false);
- tempStream.close();
- } catch (IOException e) {
- System.out.println("Setup for FileTest failed (2).");
- return;
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- if (tempFile.exists() && !tempFile.delete())
- System.out
- .println("FileTest.tearDown() failed, could not delete file!");
- if (!tempDirectory.delete())
- System.out
- .println("FileTest.tearDown() failed, could not delete directory!");
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/FileWriterTest.java b/luni/src/test/java/tests/api/java/io/FileWriterTest.java
deleted file mode 100644
index 8e30fd0..0000000
--- a/luni/src/test/java/tests/api/java/io/FileWriterTest.java
+++ /dev/null
@@ -1,409 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStreamReader;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(FileWriter.class)
-public class FileWriterTest extends junit.framework.TestCase {
-
- FileWriter fw;
-
- FileInputStream fis;
-
- BufferedWriter bw;
-
- File f;
-
- FileOutputStream fos;
-
- BufferedReader br;
-
- /**
- * @tests java.io.FileWriter#FileWriter(java.io.File)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "FileWriter",
- args = {java.io.File.class}
- )
- public void test_ConstructorLjava_io_File() {
- // Test for method java.io.FileWriter(java.io.File)
- try {
- fos = new FileOutputStream(f.getPath());
- fos.write("Test String".getBytes());
- fos.close();
- bw = new BufferedWriter(new FileWriter(f));
- bw.write(" After test string", 0, 18);
- bw.close();
- br = new BufferedReader(new FileReader(f.getPath()));
- char[] buf = new char[100];
- int r = br.read(buf);
- br.close();
- assertEquals("Failed to write correct chars", " After test string", new String(buf, 0, r)
- );
- } catch (Exception e) {
- fail("Exception during Constructor test " + e.toString());
- }
- }
-
- /**
- * @tests java.io.FileWriter#FileWriter(java.io.File)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks IOException.",
- method = "FileWriter",
- args = {java.io.File.class}
- )
- public void test_ConstructorLjava_io_File_IOException() {
- File dir = new File(System.getProperty("java.io.tmpdir"));
-
- try {
- fw = new FileWriter(dir);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.FileWriter#FileWriter(java.io.File, boolean)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies FileWriter(java.io.File, boolean) constructor.",
- method = "FileWriter",
- args = {java.io.File.class, boolean.class}
- )
- public void test_ConstructorLjava_io_FileZ() throws Exception {
- // Test for method java.io.FileWriter(java.io.File)
- //append = true
- {
- FileWriter fileWriter = new FileWriter(f);
-
- String first = "The first string for testing. ";
- fileWriter.write(first);
- fileWriter.close();
-
- fileWriter = new FileWriter(f, true);
- String second = "The second String for testing.";
- fileWriter.write(second);
- fileWriter.close();
-
- FileReader fileReader = new FileReader(f);
- char[] out = new char[first.length() + second.length() + 10];
- int length = fileReader.read(out);
- fileReader.close();
- assertEquals(first + second, new String(out, 0, length));
- }
- //append = false
- {
- FileWriter fileWriter = new FileWriter(f);
- String first = "The first string for testing. ";
- fileWriter.write(first);
- fileWriter.close();
-
- fileWriter = new FileWriter(f, false);
- String second = "The second String for testing.";
- fileWriter.write(second);
- fileWriter.close();
-
- FileReader fileReader = new FileReader(f);
- char[] out = new char[first.length() + second.length() + 10];
- int length = fileReader.read(out);
- fileReader.close();
- assertEquals(second, new String(out, 0, length));
- }
- }
-
- /**
- * @tests java.io.FileWriter#FileWriter(java.io.File, boolean)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks IOException.",
- method = "FileWriter",
- args = {java.io.File.class, boolean.class}
- )
- public void test_ConstructorLjava_io_FileZ_IOException() {
- File dir = new File(System.getProperty("java.io.tmpdir"));
-
- try {
- fw = new FileWriter(dir, true);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.FileWriter#FileWriter(java.io.FileDescriptor)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies FileWriter(java.io.FileDescriptor) constructor.",
- method = "FileWriter",
- args = {java.io.FileDescriptor.class}
- )
- public void test_ConstructorLjava_io_FileDescriptor() {
- // Test for method java.io.FileWriter(java.io.FileDescriptor)
- try {
- fos = new FileOutputStream(f.getPath());
- fos.write("Test String".getBytes());
- fos.close();
- fis = new FileInputStream(f.getPath());
- br = new BufferedReader(new FileReader(fis.getFD()));
- char[] buf = new char[100];
- int r = br.read(buf);
- br.close();
- fis.close();
- assertTrue("Failed to write correct chars: "
- + new String(buf, 0, r), new String(buf, 0, r)
- .equals("Test String"));
- } catch (Exception e) {
- fail("Exception during Constructor test " + e.toString());
- }
- }
-
- /**
- * @tests java.io.FileWriter#FileWriter(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "FileWriter",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.io.FileWriter(java.lang.String)
- try {
- fos = new FileOutputStream(f.getPath());
- fos.write("Test String".getBytes());
- fos.close();
- bw = new BufferedWriter(new FileWriter(f.getPath()));
- bw.write(" After test string", 0, 18);
- bw.close();
- br = new BufferedReader(new FileReader(f.getPath()));
- char[] buf = new char[100];
- int r = br.read(buf);
- br.close();
- assertEquals("Failed to write correct chars", " After test string", new String(buf, 0, r)
- );
- } catch (Exception e) {
- fail("Exception during Constructor test " + e.toString());
- }
- }
-
- /**
- * @tests java.io.FileWriter#FileWriter(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks IOException.",
- method = "FileWriter",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String_IOException() {
- try {
- fw = new FileWriter(System.getProperty("java.io.tmpdir"));
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.FileWriter#FileWriter(java.lang.String, boolean)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "FileWriter",
- args = {java.lang.String.class, boolean.class}
- )
- public void test_ConstructorLjava_lang_StringZ() {
- // Test for method java.io.FileWriter(java.lang.String, boolean)
-
- try {
- fos = new FileOutputStream(f.getPath());
- fos.write("Test String".getBytes());
- fos.close();
- bw = new BufferedWriter(new FileWriter(f.getPath(), true));
- bw.write(" After test string", 0, 18);
- bw.close();
- br = new BufferedReader(new FileReader(f.getPath()));
- char[] buf = new char[100];
- int r = br.read(buf);
- br.close();
- assertEquals("Failed to append to file", "Test String After test string", new String(buf, 0, r)
- );
-
- fos = new FileOutputStream(f.getPath());
- fos.write("Test String".getBytes());
- fos.close();
- bw = new BufferedWriter(new FileWriter(f.getPath(), false));
- bw.write(" After test string", 0, 18);
- bw.close();
- br = new BufferedReader(new FileReader(f.getPath()));
- buf = new char[100];
- r = br.read(buf);
- br.close();
- assertEquals("Failed to overwrite file", " After test string", new String(buf, 0, r)
- );
- } catch (Exception e) {
- fail("Exception during Constructor test " + e.toString());
- }
-
- }
-
- /**
- * @tests java.io.FileWriter#FileWriter(java.lang.String, boolean)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks IOException.",
- method = "FileWriter",
- args = {java.lang.String.class, boolean.class}
- )
- public void test_ConstructorLjava_lang_StringZ_IOException() {
- try {
- fw = new FileWriter(System.getProperty("java.io.tmpdir"), false);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {char[].class, int.class, int.class}
- )
- public void test_handleEarlyEOFChar_1() {
- String str = "All work and no play makes Jack a dull boy\n"; //$NON-NLS-1$
- int NUMBER = 2048;
- int j = 0;
- int len = str.length() * NUMBER;
- /* == 88064 *//* NUMBER compulsively written copies of the same string */
- char[] strChars = new char[len];
- for (int i = 0; i < NUMBER; ++i) {
- for (int k = 0; k < str.length(); ++k) {
- strChars[j++] = str.charAt(k);
- }
- }
- File f = null;
- FileWriter fw = null;
- try {
- f = File.createTempFile("ony", "by_one");
- fw = new FileWriter(f);
- fw.write(strChars);
- fw.close();
- InputStreamReader in = null;
- FileInputStream fis = new FileInputStream(f);
- in = new InputStreamReader(fis);
- int b;
- int errors = 0;
- for (int offset = 0; offset < strChars.length; ++offset) {
- b = in.read();
- if (b == -1) {
- fail("Early EOF at offset " + offset + "\n");
- return;
- }
- }
- assertEquals(0, errors);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {char[].class, int.class, int.class}
- )
- public void test_handleEarlyEOFChar_2() throws IOException {
- int capacity = 65536;
- byte[] bytes = new byte[capacity];
- byte[] bs = {
- 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'
- };
- for (int i = 0; i < bytes.length; i++) {
- bytes[i] = bs[i / 8192];
- }
- String inputStr = new String(bytes);
- int len = inputStr.length();
- File f = File.createTempFile("FileWriterBugTest ", null); //$NON-NLS-1$
- FileWriter writer = new FileWriter(f);
- writer.write(inputStr);
- writer.close();
- long flen = f.length();
-
- FileReader reader = new FileReader(f);
- char[] outChars = new char[capacity];
- int outCount = reader.read(outChars);
- String outStr = new String(outChars, 0, outCount);
-
- f.deleteOnExit();
- assertEquals(len, flen);
- assertEquals(inputStr, outStr);
- }
-
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() throws Exception {
-
- f = File.createTempFile("writer", ".tst");
-
- if (f.exists())
- if (!f.delete()) {
- fail("Unable to delete test file");
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- try {
- bw.close();
- } catch (Exception e) {
- }
- try {
- fis.close();
- } catch (Exception e) {
- }
- f.delete();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/FilenameFilterTest.java b/luni/src/test/java/tests/api/java/io/FilenameFilterTest.java
deleted file mode 100644
index 9a2df5d..0000000
--- a/luni/src/test/java/tests/api/java/io/FilenameFilterTest.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package tests.api.java.io;
-
-import junit.framework.TestCase;
-
-import java.io.FilenameFilter;
-import java.io.File;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(
- value = FilenameFilter.class,
- untestedMethods = {
- @TestTargetNew(
- method = "accept",
- args = {File.class , String.class},
- level = TestLevel.NOT_FEASIBLE,
- notes = "There are no classes in the current core " +
- "libraries that implement this method."
- )
- }
-)
-public class FilenameFilterTest extends TestCase {
-
-}
diff --git a/luni/src/test/java/tests/api/java/io/FilterInputStreamTest.java b/luni/src/test/java/tests/api/java/io/FilterInputStreamTest.java
deleted file mode 100644
index 579ad8e..0000000
--- a/luni/src/test/java/tests/api/java/io/FilterInputStreamTest.java
+++ /dev/null
@@ -1,454 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.BufferedInputStream;
-import java.io.FilterInputStream;
-import java.io.IOException;
-import java.util.Arrays;
-
-import tests.support.Support_ASimpleInputStream;
-import tests.support.Support_PlatformFile;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-@TestTargetClass(FilterInputStream.class)
-public class FilterInputStreamTest extends junit.framework.TestCase {
-
- static class MyFilterInputStream extends java.io.FilterInputStream {
- public MyFilterInputStream(java.io.InputStream is) {
- super(is);
- }
- }
-
- private String fileName;
-
- private FilterInputStream is;
-
- byte[] ibuf = new byte[4096];
-
- private static final String testString = "Lorem ipsum dolor sit amet,\n" +
- "consectetur adipisicing elit,\nsed do eiusmod tempor incididunt ut" +
- "labore et dolore magna aliqua.\n";
-
- private static final int testLength = testString.length();
-
- /**
- * @tests java.io.FilterInputStream#InputStream()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies constructor FilterInputStream(InputStream).",
- method = "FilterInputStream",
- args = {java.io.InputStream.class}
- )
- public void test_Constructor() {
- // The FilterInputStream object has already been created in setUp().
- // If anything has gone wrong, closing it should throw a
- // NullPointerException.
- try {
- is.close();
- } catch (IOException e) {
- fail("Unexpected IOException: " + e.getMessage());
- } catch (NullPointerException npe) {
- fail("Unexpected NullPointerException.");
- }
- }
-
- /**
- * @tests java.io.FilterInputStream#available()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "available",
- args = {}
- )
- public void test_available() throws IOException {
- assertEquals("Test 1: Returned incorrect number of available bytes;",
- testLength, is.available());
-
- is.close();
- try {
- is.available();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.FilterInputStream#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "close",
- args = {}
- )
- public void test_close() throws IOException {
- is.close();
-
- try {
- is.read();
- fail("Test 1: Read from closed stream succeeded.");
- } catch (IOException e) {
- // Expected.
- }
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(true);
- is = new MyFilterInputStream(sis);
- try {
- is.close();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- }
-
- /**
- * @tests java.io.FilterInputStream#mark(int)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies mark(int) in combination with reset().",
- method = "mark",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies mark(int) in combination with reset().",
- method = "reset",
- args = {}
- )
- })
- public void test_markI() throws Exception {
- // Test for method void java.io.FilterInputStream.mark(int)
- final int bufSize = 10;
- byte[] buf1 = new byte[bufSize];
- byte[] buf2 = new byte[bufSize];
-
- // Purpose 1: Check that mark() does nothing if the filtered stream
- // is a FileInputStream.
- is.read(buf1, 0, bufSize);
- is.mark(2 * bufSize);
- is.read(buf1, 0, bufSize);
- try {
- is.reset();
- } catch (IOException e) {
- // Expected
- }
- is.read(buf2, 0, bufSize);
- assertFalse("Test 1: mark() should have no effect.",
- Arrays.equals(buf1, buf2));
- is.close();
-
- // Purpose 2: Check that mark() in combination with reset() works if
- // the filtered stream is a BufferedInputStream.
- is = new MyFilterInputStream(new BufferedInputStream(
- new java.io.FileInputStream(fileName), 100));
- is.read(buf1, 0, bufSize);
- is.mark(2 * bufSize);
- is.read(buf1, 0, bufSize);
- is.reset();
- is.read(buf2, 0, bufSize);
- assertTrue("Test 2: mark() or reset() has failed.",
- Arrays.equals(buf1, buf2));
- }
-
- /**
- * @tests java.io.FilterInputStream#markSupported()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies markSupported() method.",
- method = "markSupported",
- args = {}
- )
- public void test_markSupported() throws Exception {
- // Test for method boolean java.io.FilterInputStream.markSupported()
-
- // Test 1: Check that markSupported() returns false for a filtered
- // input stream that is known to not support mark().
- assertFalse("Test 1: markSupported() incorrectly returned true " +
- "for a FileInputStream.", is.markSupported());
- is.close();
- // Test 2: Check that markSupported() returns true for a filtered
- // input stream that is known to support mark().
- is = new MyFilterInputStream(new BufferedInputStream(
- new java.io.FileInputStream(fileName), 100));
- assertTrue("Test 2: markSupported() incorrectly returned false " +
- "for a BufferedInputStream.", is.markSupported());
- }
-
- /**
- * @tests java.io.FilterInputStream#read()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "read",
- args = {}
- )
- public void test_read() throws IOException {
- int c = is.read();
- assertEquals("Test 1: Read returned incorrect char;",
- testString.charAt(0), c);
-
- is.close();
- try {
- is.read();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.FilterInputStream#read(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "read",
- args = {byte[].class}
- )
- public void test_read$B() throws IOException {
- // Test for method int java.io.FilterInputStream.read(byte [])
- byte[] buf1 = new byte[100];
- is.read(buf1);
- assertTrue("Test 1: Failed to read correct data.",
- new String(buf1, 0, buf1.length).equals(
- testString.substring(0, 100)));
-
- is.close();
- try {
- is.read(buf1);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.FilterInputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII() throws IOException {
- byte[] buf1 = new byte[20];
- is.skip(10);
- is.read(buf1, 0, buf1.length);
- assertTrue("Failed to read correct data", new String(buf1, 0,
- buf1.length).equals(testString.substring(10, 30)));
- }
-
- /**
- * @tests FilterInputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Illegal argument checks.",
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII_Exception() throws IOException {
- byte[] buf = null;
- try {
- is.read(buf, -1, 0);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
-
- buf = new byte[1000];
- try {
- is.read(buf, -1, 0);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- is.read(buf, 0, -1);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- is.read(buf, -1, -1);
- fail("Test 4: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- is.read(buf, 0, 1001);
- fail("Test 5: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- is.read(buf, 1001, 0);
- fail("Test 6: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- is.read(buf, 500, 501);
- fail("Test 7: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- is.close();
- try {
- is.read(buf, 0, 100);
- fail("Test 8: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.FilterInputStream#reset()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies reset() in combination with mark().",
- method = "reset",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies reset() in combination with mark().",
- method = "mark",
- args = { int.class }
- )
- })
- public void test_reset() throws Exception {
- // Test for method void java.io.FilterInputStream.reset()
-
- // Test 1: Check that reset() throws an IOException if the
- // filtered stream is a FileInputStream.
- try {
- is.reset();
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // expected
- }
-
- // Test 2: Check that reset() throws an IOException if the
- // filtered stream is a BufferedInputStream but mark() has not
- // yet been called.
- is = new MyFilterInputStream(new BufferedInputStream(
- new java.io.FileInputStream(fileName), 100));
- try {
- is.reset();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // expected
- }
-
- // Test 3: Check that reset() in combination with mark()
- // works correctly.
- final int bufSize = 10;
- byte[] buf1 = new byte[bufSize];
- byte[] buf2 = new byte[bufSize];
- is.read(buf1, 0, bufSize);
- is.mark(2 * bufSize);
- is.read(buf1, 0, bufSize);
- try {
- is.reset();
- } catch (IOException e) {
- fail("Test 3: Unexpected IOException.");
- }
- is.read(buf2, 0, bufSize);
- assertTrue("Test 4: mark() or reset() has failed.",
- Arrays.equals(buf1, buf2));
- }
-
- /**
- * @tests java.io.FilterInputStream#skip(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "skip",
- args = {long.class}
- )
- public void test_skipJ() throws IOException {
- byte[] buf1 = new byte[10];
- is.skip(10);
- is.read(buf1, 0, buf1.length);
- assertTrue("Test 1: Failed to skip to the correct position.",
- new String(buf1, 0, buf1.length).equals(
- testString.substring(10, 20)));
-
- is.close();
- try {
- is.read();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- try {
- fileName = System.getProperty("java.io.tmpdir");
- String separator = System.getProperty("file.separator");
- if (fileName.charAt(fileName.length() - 1) == separator.charAt(0))
- fileName = Support_PlatformFile.getNewPlatformFile(fileName,
- "input.tst");
- else
- fileName = Support_PlatformFile.getNewPlatformFile(fileName
- + separator, "input.tst");
- java.io.OutputStream fos = new java.io.FileOutputStream(fileName);
- fos.write(testString.getBytes());
- fos.close();
- is = new MyFilterInputStream(new java.io.FileInputStream(fileName));
- } catch (java.io.IOException e) {
- System.out.println("Exception during setup");
- e.printStackTrace();
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- try {
- is.close();
- } catch (Exception e) {
- System.out.println("Unexpected exception in tearDown().");
- }
- new java.io.File(fileName).delete();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/FilterOutputStreamTest.java b/luni/src/test/java/tests/api/java/io/FilterOutputStreamTest.java
deleted file mode 100644
index ab0bebc..0000000
--- a/luni/src/test/java/tests/api/java/io/FilterOutputStreamTest.java
+++ /dev/null
@@ -1,269 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.FilterOutputStream;
-import java.io.IOException;
-
-import tests.support.Support_OutputStream;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(java.io.FilterOutputStream.class)
-public class FilterOutputStreamTest extends junit.framework.TestCase {
-
- private java.io.FilterOutputStream os;
-
- java.io.ByteArrayOutputStream bos;
-
- java.io.ByteArrayInputStream bis;
-
- byte[] ibuf = new byte[4096];
-
- private final String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_java_io_File\nTest_java_io_FileDescriptor\nTest_java_io_FileInputStream\nTest_java_io_FileNotFoundException\nTest_java_io_FileOutputStream\nTest_java_io_FilterInputStream\nTest_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
-
- private final int testLength = fileString.length();
-
-
- /**
- * @tests java.io.FilterOutputStream#FilterOutputStream(java.io.OutputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies FilterOutputStream(java.io.OutputStream) constructor.",
- method = "FilterOutputStream",
- args = {java.io.OutputStream.class}
- )
- public void test_ConstructorLjava_io_OutputStream() {
- // Test for method java.io.FilterOutputStream(java.io.OutputStream)
- try {
- bos = new ByteArrayOutputStream();
- os = new FilterOutputStream(bos);
- os.write('t');
- } catch (java.io.IOException e) {
- fail("Constructor test failed : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.FilterOutputStream#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "close",
- args = {}
- )
- public void test_close() throws IOException {
- Support_OutputStream sos = new Support_OutputStream();
- os = new FilterOutputStream(sos);
- os.close();
-
- try {
- os.write(42);
- } catch (java.io.IOException e) {
- fail("Test 1: Unexpected IOException.");
- }
-
- sos.setThrowsException(true);
- try {
- os.write(42);
- fail("Test 2: IOException expected.");
- } catch (java.io.IOException e) {
- // Expected.
- }
-
- os = new FilterOutputStream(sos);
- try {
- os.close();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.FilterOutputStream#flush()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "flush",
- args = {}
- )
- public void test_flush() throws IOException {
- Support_OutputStream sos = new Support_OutputStream(550);
- os = new FilterOutputStream(sos);
- os.write(fileString.getBytes(), 0, 500);
- os.flush();
- assertEquals("Test 1: Bytes not written after flush;",
- 500, sos.size());
-
- sos.setThrowsException(true);
- try {
- os.flush();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sos.setThrowsException(false);
- }
-
- /**
- * @tests java.io.FilterOutputStream#write(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "write",
- args = {byte[].class}
- )
- public void test_write$B() throws IOException {
- Support_OutputStream sos = new Support_OutputStream(testLength);
- os = new FilterOutputStream(sos);
- os.write(fileString.getBytes());
-
- bis = new ByteArrayInputStream(sos.toByteArray());
- assertTrue("Test 1: Bytes have not been written.",
- bis.available() == testLength);
- byte[] wbytes = new byte[testLength];
- bis.read(wbytes, 0, testLength);
- assertTrue("Test 2: Incorrect bytes written or read.",
- fileString.equals(new String(wbytes)));
-
- try {
- // Support_OutputStream throws an IOException if the internal
- // buffer is full, which it should be now.
- os.write(42);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.FilterOutputStream#write(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "write",
- args = {byte[].class, int.class, int.class}
- )
- public void test_write$BII() throws IOException {
- Support_OutputStream sos = new Support_OutputStream(testLength);
- os = new FilterOutputStream(sos);
- os.write(fileString.getBytes(), 10, testLength - 10);
-
- bis = new ByteArrayInputStream(sos.toByteArray());
- assertTrue("Test 1: Bytes have not been written.",
- bis.available() == testLength - 10);
- byte[] wbytes = new byte[testLength - 10];
- bis.read(wbytes);
- assertTrue("Test 2: Incorrect bytes written or read.",
- fileString.substring(10).equals(new String(wbytes)));
-
- try {
- // Support_OutputStream throws an IOException if the internal
- // buffer is full, which it should be eventually.
- os.write(fileString.getBytes());
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.FilterOutputStream#write(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "write",
- args = {byte[].class, int.class, int.class}
- )
- public void test_write$BII_Exception() throws IOException {
- Support_OutputStream sos = new Support_OutputStream(testLength);
- os = new FilterOutputStream(sos);
- byte[] buf = new byte[10];
-
- try {
- os.write(buf, -1, 1);
- fail("IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- os.write(buf, 0, -1);
- fail("IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- os.write(buf, 10, 1);
- fail("IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.FilterOutputStream#write(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "write",
- args = {int.class}
- )
- public void test_writeI() throws IOException {
- Support_OutputStream sos = new Support_OutputStream(1);
- os = new FilterOutputStream(sos);
- os.write(42);
-
- bis = new ByteArrayInputStream(sos.toByteArray());
- assertTrue("Test 1: Byte has not been written.",
- bis.available() == 1);
- assertEquals("Test 2: Incorrect byte written or read;",
- 42, bis.read());
-
- try {
- // Support_OutputStream throws an IOException if the internal
- // buffer is full, which it should be now.
- os.write(42);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- try {
- if (bos != null)
- bos.close();
- if (bis != null)
- bis.close();
- if (os != null)
- os.close();
- } catch (Exception e) {
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/FilterReaderTest.java b/luni/src/test/java/tests/api/java/io/FilterReaderTest.java
deleted file mode 100644
index 14313d0..0000000
--- a/luni/src/test/java/tests/api/java/io/FilterReaderTest.java
+++ /dev/null
@@ -1,279 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.ByteArrayInputStream;
-import java.io.FilterReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(FilterReader.class)
-public class FilterReaderTest extends junit.framework.TestCase {
-
- private boolean called;
- private FilterReader fr;
-
- static class MyFilterReader extends java.io.FilterReader {
- public MyFilterReader(java.io.Reader reader) {
- super(reader);
- }
- }
-
- class MockReader extends java.io.Reader {
- public MockReader() {
- }
-
- public void close() throws IOException {
- called = true;
- }
-
- public void mark(int readLimit) throws IOException {
- called = true;
- }
-
- public boolean markSupported() {
- called = true;
- return false;
- }
-
- public int read() throws IOException {
- called = true;
- return 0;
- }
-
- public int read(char[] buffer, int offset, int count) throws IOException {
- called = true;
- return 0;
- }
-
- public boolean ready() throws IOException {
- called = true;
- return true;
- }
-
- public void reset() throws IOException {
- called = true;
- }
-
- public long skip(long count) throws IOException {
- called = true;
- return 0;
- }
- }
-
- /**
- * @tests java.io.FilterReader#FilterReader(java.io.Reader)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies constructor FilterReader(java.io.Reader).",
- method = "FilterReader",
- args = {java.io.Reader.class}
- )
- public void test_ConstructorLjava_io_Reader() {
-
- FilterReader myReader = null;
-
- called = true;
-
- try {
- myReader = new MyFilterReader(null);
- fail("NullPointerException expected.");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.FilterReader#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies close().",
- method = "close",
- args = {}
- )
- public void test_close() throws IOException {
- fr.close();
- assertTrue("close() has not been called.", called);
- }
-
- /**
- * @tests java.io.FilterReader#mark(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies mark(int).",
- method = "mark",
- args = {int.class}
- )
- public void test_markI() throws IOException {
- fr.mark(0);
- assertTrue("mark(int) has not been called.", called);
- }
-
- /**
- * @tests java.io.FilterReader#markSupported()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies markSupported().",
- method = "markSupported",
- args = {}
- )
- public void test_markSupported() {
- fr.markSupported();
- assertTrue("markSupported() has not been called.", called);
- }
-
- /**
- * @tests java.io.FilterReader#read()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies read().",
- method = "read",
- args = {}
- )
- public void test_read() throws IOException {
- fr.read();
- assertTrue("read() has not been called.", called);
- }
-
- /**
- * @tests java.io.FilterReader#read(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies read(char[], int, int).",
- method = "read",
- args = {char[].class, int.class, int.class}
- )
- public void test_read$CII() throws IOException {
- char[] buffer = new char[5];
- fr.read(buffer, 0, 5);
- assertTrue("read(char[], int, int) has not been called.", called);
- }
-
- /**
- * @tests java.io.FilterReader#read(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies read(char[], int, int).",
- method = "read",
- args = {char[].class, int.class, int.class}
- )
- public void test_read$CII_Exception() throws IOException {
- byte[] bbuffer = new byte[20];
- char[] buffer = new char[10];
-
- fr = new MyFilterReader(new InputStreamReader(
- new ByteArrayInputStream(bbuffer)));
-
- try {
- fr.read(buffer, 0, -1);
- fail("Test 1: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- fr.read(buffer, -1, 1);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- fr.read(buffer, 10, 1);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.FilterReader#ready()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies ready().",
- method = "ready",
- args = {}
- )
- public void test_ready() throws IOException {
- fr.ready();
- assertTrue("ready() has not been called.", called);
- }
-
- /**
- * @tests java.io.FilterReader#reset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies reset().",
- method = "reset",
- args = {}
- )
- public void test_reset() throws IOException {
- fr.reset();
- assertTrue("reset() has not been called.", called);
- }
-
- /**
- * @tests java.io.FilterReader#skip()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies skip(long).",
- method = "skip",
- args = {long.class}
- )
- public void test_skip() throws IOException {
- fr.skip(10);
- assertTrue("skip(long) has not been called.", called);
- }
-
- /**
- * This method is called before a test is executed. It creates a
- * FilterReader instance.
- */
- protected void setUp() {
-
- fr = new MyFilterReader(new MockReader());
- called = false;
- }
-
- /**
- * This method is called after a test is executed. It closes the
- * FilterReader instance.
- */
- protected void tearDown() {
-
- try {
- fr.close();
- } catch (Exception e) {
- System.out.println("Exception during FilterReaderTest tear down.");
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/FilterWriterTest.java b/luni/src/test/java/tests/api/java/io/FilterWriterTest.java
deleted file mode 100644
index 6fcb57d..0000000
--- a/luni/src/test/java/tests/api/java/io/FilterWriterTest.java
+++ /dev/null
@@ -1,228 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import tests.api.java.io.FilterReaderTest.MyFilterReader;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.FilterWriter;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(FilterWriter.class)
-public class FilterWriterTest extends junit.framework.TestCase {
-
- private boolean called;
- private FilterWriter fw;
-
- static class MyFilterWriter extends java.io.FilterWriter {
- public MyFilterWriter(java.io.Writer writer) {
- super(writer);
- }
- }
-
- class MockWriter extends java.io.Writer {
- public MockWriter() {
- }
-
- public void close() throws IOException {
- called = true;
- }
-
- public void flush() throws IOException {
- called = true;
- }
-
- public void write(char[] buffer, int offset, int count) throws IOException {
- called = true;
- }
-
- public void write(int oneChar) throws IOException {
- called = true;
- }
-
- public void write(String str, int offset, int count) throws IOException {
- called = true;
- }
-
- public long skip(long count) throws IOException {
- called = true;
- return 0;
- }
- }
-
- /**
- * @tests java.io.FilterWriter#FilterReader(java.io.Reader)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies constructor FilterWriter(java.io.Writer).",
- method = "FilterWriter",
- args = {java.io.Writer.class}
- )
- public void test_ConstructorLjava_io_Writer() {
-
- FilterWriter myWriter = null;
-
- called = true;
-
- try {
- myWriter = new MyFilterWriter(null);
- fail("NullPointerException expected.");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.FilterWriter#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies close().",
- method = "close",
- args = {}
- )
- public void test_close() throws IOException {
- fw.close();
- assertTrue("close() has not been called.", called);
- }
-
- /**
- * @tests java.io.FilterWriter#flush()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies flush().",
- method = "flush",
- args = {}
- )
- public void test_flush() throws IOException {
- fw.flush();
- assertTrue("flush() has not been called.", called);
- }
-
- /**
- * @tests java.io.FilterWriter#write(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies write(int).",
- method = "write",
- args = {int.class}
- )
- public void test_writeI() throws IOException {
- fw.write(0);
- assertTrue("write(int) has not been called.", called);
- }
-
- /**
- * @tests java.io.FilterWriter#write(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies write(char[], int, int).",
- method = "write",
- args = {char[].class, int.class, int.class}
- )
- public void test_write$CII() throws IOException {
- char[] buffer = new char[5];
- fw.write(buffer, 0, 5);
- assertTrue("write(char[], int, int) has not been called.", called);
- }
-
- /**
- * @tests java.io.FilterReader#read(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies write(char[], int, int).",
- method = "write",
- args = {char[].class, int.class, int.class}
- )
- public void test_write$CII_Exception() throws IOException {
- char[] buffer = new char[10];
-
- fw = new MyFilterWriter(new OutputStreamWriter(
- new ByteArrayOutputStream()));
-
- try {
- fw.write(buffer, 0, -1);
- fail("Test 1: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- fw.write(buffer, -1, 1);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- fw.write(buffer, 10, 1);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.FilterWriter#write(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies write(String, int, int).",
- method = "write",
- args = {java.lang.String.class, int.class, int.class}
- )
- public void test_writeLjava_lang_StringII() throws IOException {
- fw.write("Hello world", 0, 5);
- assertTrue("write(String, int, int) has not been called.", called);
- }
-
- /**
- * This method is called before a test is executed. It creates a
- * FilterWriter instance.
- */
- protected void setUp() {
-
- fw = new MyFilterWriter(new MockWriter());
- called = false;
- }
-
- /**
- * This method is called after a test is executed. It closes the
- * FilterWriter instance.
- */
- protected void tearDown() {
-
- try {
- fw.close();
- } catch (Exception e) {
- System.out.println("Exception during FilterWriterTest tear down.");
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/IOExceptionTest.java b/luni/src/test/java/tests/api/java/io/IOExceptionTest.java
deleted file mode 100644
index 919c2b9..0000000
--- a/luni/src/test/java/tests/api/java/io/IOExceptionTest.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.IOException;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(IOException.class)
-public class IOExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.io.IOException#IOException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IOException",
- args = {}
- )
- public void test_Constructor() {
- try {
- if (true) // Needed to avoid unreachable code compilation error.
- throw new IOException();
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- assertNull("Test 2: Null expected for exceptions constructed without a message.",
- e.getMessage());
- }
- }
-
- /**
- * @tests java.io.IOException#IOException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IOException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- try {
- if (true) // Needed to avoid unreachable code compilation error.
- throw new IOException("Something went wrong.");
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- assertEquals("Test 2: Incorrect message;",
- "Something went wrong.", e.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/InputStreamReaderTest.java b/luni/src/test/java/tests/api/java/io/InputStreamReaderTest.java
deleted file mode 100644
index e3d10a4..0000000
--- a/luni/src/test/java/tests/api/java/io/InputStreamReaderTest.java
+++ /dev/null
@@ -1,698 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
-import java.io.UnsupportedEncodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CodingErrorAction;
-import java.nio.charset.MalformedInputException;
-import java.util.Arrays;
-
-import tests.support.Support_ASimpleInputStream;
-
-import junit.framework.TestCase;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-/**
- *
- */
-@TestTargetClass(InputStreamReader.class)
-public class InputStreamReaderTest extends TestCase {
-
- private final String source = "This is a test message with Unicode character. \u4e2d\u56fd is China's name in Chinese";
-
- private InputStream in;
-
- private InputStreamReader reader;
-
- private InputStreamReader is;
-
- private InputStream fis;
-
- public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\n";
-
- static class LimitedByteArrayInputStream extends ByteArrayInputStream {
-
- // A ByteArrayInputStream that only returns a single byte per read
- byte[] bytes;
-
- int count;
-
- public LimitedByteArrayInputStream(int type) {
- super(new byte[0]);
- switch (type) {
- case 0:
- bytes = new byte[] { 0x61, 0x72 };
- break;
- case 1:
- bytes = new byte[] { (byte) 0xff, (byte) 0xfe, 0x61, 0x72 };
- break;
- case 2:
- bytes = new byte[] { '\u001b', '$', 'B', '6', 'e', 'B', 'h',
- '\u001b', '(', 'B' };
- break;
- }
- count = bytes.length;
- }
-
- public int read() {
- if (count == 0)
- return -1;
- count--;
- return bytes[bytes.length - count];
- }
-
- public int read(byte[] buffer, int offset, int length) {
- if (count == 0)
- return -1;
- if (length == 0)
- return 0;
- buffer[offset] = bytes[bytes.length - count];
- count--;
- return 1;
- }
-
- public int available() {
- return count;
- }
- }
-
- /*
- * @see TestCase#setUp()
- */
- protected void setUp() throws Exception {
- super.setUp();
-
- try {
- in = new ByteArrayInputStream(source.getBytes("UTF-8"));
- reader = new InputStreamReader(in, "UTF-8");
-
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- OutputStreamWriter osw = new OutputStreamWriter(bos);
- char[] buf = new char[fileString.length()];
- fileString.getChars(0, fileString.length(), buf, 0);
- osw.write(buf);
- osw.close();
- fis = new ByteArrayInputStream(bos.toByteArray());
- is = new InputStreamReader(fis);
- } catch (Exception e) {
- fail("Exception during setUp : " + e.getMessage());
- }
- }
-
- /*
- * @see TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- try {
- in.close();
- is.close();
- fis.close();
- } catch (IOException e) {
- }
-
- super.tearDown();
- }
-
- /*
- * Class under test for int read()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException checking missed.",
- method = "read",
- args = {}
- )
- public void testRead() throws IOException {
- assertEquals('T', (char) reader.read());
- assertEquals('h', (char) reader.read());
- assertEquals('i', (char) reader.read());
- assertEquals('s', (char) reader.read());
- assertEquals(' ', (char) reader.read());
- reader.read(new char[source.length() - 5], 0, source.length() - 5);
- assertEquals(-1, reader.read());
- }
-
- /*
- * Class under test for int read()
- * Regression for Harmony-411
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException checking missed.",
- method = "read",
- args = {}
- )
-
- public void testRead1() throws IOException {
- // if the decoder is constructed by InputStreamReader itself, the decoder's
- // default error action is REPLACE
- InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(
- new byte[] { -32, -96 }), "UTF-8");
- assertEquals("read() return incorrect value", 65533, isr.read());
-
- InputStreamReader isr2 = new InputStreamReader(new ByteArrayInputStream(
- new byte[] { -32, -96 }), Charset.forName("UTF-8"));
- assertEquals("read() return incorrect value", 65533, isr2.read());
-
- // if the decoder is passed in, keep its status intacted
- CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
- decoder.onMalformedInput(CodingErrorAction.REPORT);
- InputStreamReader isr3 = new InputStreamReader(new ByteArrayInputStream(
- new byte[] { -32, -96 }), decoder);
- try{
- isr3.read();
- fail("Should throw MalformedInputException");
- }catch(MalformedInputException e){
- //expected
- }
-
- CharsetDecoder decoder2 = Charset.forName("UTF-8").newDecoder();
- decoder2.onMalformedInput(CodingErrorAction.IGNORE);
- InputStreamReader isr4 = new InputStreamReader(new ByteArrayInputStream(
- new byte[] { -32, -96 }), decoder2);
- assertEquals("read() return incorrect value", -1, isr4.read());
-
- CharsetDecoder decoder3 = Charset.forName("UTF-8").newDecoder();
- decoder3.onMalformedInput(CodingErrorAction.REPLACE);
- InputStreamReader isr5 = new InputStreamReader(new ByteArrayInputStream(
- new byte[] { -32, -96 }), decoder3);
- assertEquals("read() return incorrect value", 65533, isr5.read());
- }
-
- /*
- * Class under test for int read(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException checking missed.",
- method = "read",
- args = {char[].class, int.class, int.class}
- )
- public void testReadcharArrayintint() throws IOException {
- try {
- reader.read(new char[3], -1, 0);
- fail("Should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- try {
- reader.read(new char[3], 0, -1);
- fail("Should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- try {
- reader.read(new char[3], 4, 0);
- fail("Should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- try {
- reader.read(new char[3], 3, 1);
- fail("Should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- try {
- reader.read(new char[3], 1, 3);
- fail("Should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- try {
- reader.read(new char[3], 0, 4);
- fail("Should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- reader.read(null, 0, 0);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- //expected
- }
-
- assertEquals(0, reader.read(new char[3], 3, 0));
- char[] chars = new char[source.length()];
- assertEquals(0, reader.read(chars, 0, 0));
- assertEquals(0, chars[0]);
- assertEquals(3, reader.read(chars, 0, 3));
- assertEquals(5, reader.read(chars, 3, 5));
- assertEquals(source.length() - 8, reader.read(chars, 8,
- chars.length - 8));
- assertTrue(Arrays.equals(chars, source.toCharArray()));
- assertEquals(-1, reader.read(chars, 0, chars.length));
- assertTrue(Arrays.equals(chars, source.toCharArray()));
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException checking missed.",
- method = "read",
- args = {char[].class, int.class, int.class}
- )
- public void testReadcharArrayintint2() throws IOException {
- char[] chars = new char[source.length()];
- assertEquals(source.length() - 3, reader.read(chars, 0,
- chars.length - 3));
- assertEquals(3, reader.read(chars, 0, 10));
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException checking missed.",
- method = "ready",
- args = {}
- )
- public void testReady() throws IOException {
- assertTrue(reader.ready());
- reader.read(new char[source.length()]);
- assertFalse(reader.ready());
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException checking missed.",
- method = "read",
- args = {}
- )
- public void testSpecialCharsetReading() throws Exception {
- reader.close();
- in = this.getClass().getClassLoader().getResourceAsStream(
- "tests/api/java/io/testfile-utf8.txt");
- reader = new InputStreamReader(in, "utf-8");
- int c;
- StringBuffer sb = new StringBuffer();
- while ((c = reader.read()) != -1) {
- sb.append((char) c);
- }
- // delete BOM
- assertEquals(source, sb.deleteCharAt(0).toString());
-
- sb.setLength(0);
- reader.close();
- in = this.getClass().getClassLoader().getResourceAsStream(
- "tests/api/java/io/testfile.txt");
- reader = new InputStreamReader(in, "GB2312");
-
- while ((c = reader.read()) != -1) {
- sb.append((char) c);
- }
- assertEquals(source, sb.toString());
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException checking.",
- method = "read",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException checking.",
- method = "ready",
- args = {}
- )
- })
- public void testAfterClose() throws IOException {
- reader.close();
- in = new BufferedInputStream(this.getClass().getClassLoader()
- .getResourceAsStream("tests/api/java/io/testfile-utf8.txt"));
- reader = new InputStreamReader(in, "utf-8");
- in.close();
- try {
- int count = reader.read(new char[1]);
- fail("count:" + count);
- } catch (IOException e) {
- }
- try {
- reader.read();
- fail();
- } catch (IOException e) {
- }
-
- assertFalse(reader.ready());
- Charset cs = Charset.forName("utf-8");
- assertEquals(cs, Charset.forName(reader.getEncoding()));
- reader.close();
- }
-
- /*
- * Class under test for void InputStreamReader(InputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InputStreamReader",
- args = {java.io.InputStream.class}
- )
- public void testInputStreamReaderInputStream() throws IOException {
- try {
- reader = new InputStreamReader(null);
- fail();
- } catch (NullPointerException e) {
- }
- InputStreamReader reader2 = new InputStreamReader(in);
- reader2.close();
- }
-
- /*
- * Class under test for void InputStreamReader(InputStream, String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InputStreamReader",
- args = {java.io.InputStream.class, java.lang.String.class}
- )
- public void testInputStreamReaderInputStreamString() throws IOException {
- try {
- reader = new InputStreamReader(null, "utf-8");
- fail();
- } catch (NullPointerException e) {
- }
- try {
- reader = new InputStreamReader(in, (String) null);
- fail();
- } catch (NullPointerException e) {
- }
- try {
- reader = new InputStreamReader(in, "");
- fail();
- } catch (UnsupportedEncodingException e) {
- }
- try {
- reader = new InputStreamReader(in, "badname");
- fail();
- } catch (UnsupportedEncodingException e) {
- }
- InputStreamReader reader2 = new InputStreamReader(in, "utf-8");
- assertEquals(Charset.forName(reader2.getEncoding()), Charset
- .forName("utf-8"));
- reader2.close();
- reader2 = new InputStreamReader(in, "utf8");
- assertEquals(Charset.forName(reader2.getEncoding()), Charset
- .forName("utf-8"));
- reader2.close();
- }
-
- /*
- * Class under test for void InputStreamReader(InputStream, CharsetDecoder)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InputStreamReader",
- args = {java.io.InputStream.class, java.nio.charset.CharsetDecoder.class}
- )
- public void testInputStreamReaderInputStreamCharsetDecoder()
- throws Exception {
- CharsetDecoder decoder = Charset.forName("utf-8").newDecoder();
- try {
- reader = new InputStreamReader(null, decoder);
- fail();
- } catch (NullPointerException e) {
- }
- try {
- reader = new InputStreamReader(in, (CharsetDecoder) null);
- fail();
- } catch (NullPointerException e) {
- }
- InputStreamReader reader2 = new InputStreamReader(in, decoder);
- assertEquals(Charset.forName(reader2.getEncoding()), decoder.charset());
- reader2.close();
- }
-
- /*
- * Class under test for void InputStreamReader(InputStream, Charset)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InputStreamReader",
- args = {java.io.InputStream.class, java.nio.charset.Charset.class}
- )
- public void testInputStreamReaderInputStreamCharset() throws IOException {
- Charset cs = Charset.forName("utf-8");
- try {
- reader = new InputStreamReader(null, cs);
- fail();
- } catch (NullPointerException e) {
- }
- try {
- reader = new InputStreamReader(in, (Charset) null);
- fail();
- } catch (NullPointerException e) {
- }
- InputStreamReader reader2 = new InputStreamReader(in, cs);
- assertEquals(Charset.forName(reader2.getEncoding()), cs);
- reader2.close();
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {char[].class, int.class, int.class}
- )
- public void testInputStreamReaderSuccessiveReads() throws IOException {
- byte[] data = new byte[8192 * 2];
- Arrays.fill(data, (byte) 116); // 116 = ISO-8859-1 value for 't'
- ByteArrayInputStream bis = new ByteArrayInputStream(data);
- InputStreamReader isr = new InputStreamReader(bis, "ISO-8859-1");
-
- // One less than the InputStreamReader.BUFFER_SIZE
- char[] buf = new char[8191];
- int bytesRead = isr.read(buf, 0, buf.length);
- if (bytesRead == -1) {
- throw new RuntimeException();
- }
- bytesRead = isr.read(buf, 0, buf.length);
- if (bytesRead == -1) {
- throw new RuntimeException();
- }
- }
-
- /**
- * @tests java.io.InputStreamReader#InputStreamReader(java.io.InputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "See setUp.",
- method = "InputStreamReader",
- args = {java.io.InputStream.class}
- )
- public void test_ConstructorLjava_io_InputStream() {
- // Test for method java.io.InputStreamReader(java.io.InputStream)
- assertTrue("Used to test other methods", true);
- }
-
- /**
- * @tests java.io.InputStreamReader#InputStreamReader(java.io.InputStream,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies InputStreamReader(java.io.InputStream) constructor.",
- method = "InputStreamReader",
- args = {java.io.InputStream.class}
- )
- public void test_ConstructorLjava_io_InputStreamLjava_lang_String() {
- // Test for method java.io.InputStreamReader(java.io.InputStream,
- // java.lang.String)
- try {
- is = new InputStreamReader(fis, "8859_1");
- } catch (UnsupportedEncodingException e) {
- fail("Unable to create input stream : " + e.getMessage());
- }
-
- try {
- is = new InputStreamReader(fis, "Bogus");
- } catch (UnsupportedEncodingException e) {
- return;
- }
- fail("Failed to throw Unsupported Encoding exception");
- }
-
- /**
- * @tests java.io.InputStreamReader#close()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "close",
- args = {}
- )
- public void test_close() {
- // Test for method void java.io.InputStreamReader.close()
- try {
- is.close();
- } catch (IOException e) {
- fail("Failed to close reader : " + e.getMessage());
- }
- try {
- is.read();
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Exception means read failed due to close
- }
-
- is = new InputStreamReader(new Support_ASimpleInputStream(true));
- try {
- is.read();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "close",
- args = {}
- )
- public void testClose() throws IOException {
- reader.close();
- try {
- reader.ready();
- fail("Should throw IOException");
- } catch (IOException e) {
- }
- reader.close();
- }
-
- /**
- * @tests java.io.InputStreamReader#getEncoding()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies getEncoding() method.",
- method = "getEncoding",
- args = {}
- )
- public void test_getEncoding() {
- // Test for method java.lang.String
- // java.io.InputStreamReader.getEncoding()
- try {
- is = new InputStreamReader(fis, "8859_1");
- } catch (UnsupportedEncodingException e) {
- assertEquals("Returned incorrect encoding",
- "8859_1", is.getEncoding());
- }
- }
-
- /**
- * @tests java.io.InputStreamReader#read()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {}
- )
- public void test_read() throws IOException{
- // Test for method int java.io.InputStreamReader.read()
- try {
- int c = is.read();
- assertTrue("returned incorrect char", (char) c == fileString
- .charAt(0));
- InputStreamReader reader = new InputStreamReader(
- new ByteArrayInputStream(new byte[] { (byte) 0xe8,
- (byte) 0x9d, (byte) 0xa5 }), "UTF8");
- assertTrue("wrong double byte char", reader.read() == '\u8765');
- } catch (IOException e) {
- fail("Exception during read test : " + e.getMessage());
- }
-
- // Regression for HARMONY-166
- InputStream in;
- InputStreamReader reader;
-
- in = new LimitedByteArrayInputStream(0);
- reader = new InputStreamReader(in, "UTF-16BE");
- assertEquals("Incorrect byte UTF-16BE", '\u6172', reader.read());
-
- in = new LimitedByteArrayInputStream(0);
- reader = new InputStreamReader(in, "UTF-16LE");
- assertEquals("Incorrect byte UTF-16BE", '\u7261', reader.read());
-
- in = new LimitedByteArrayInputStream(1);
- reader = new InputStreamReader(in, "UTF-16");
- assertEquals("Incorrect byte UTF-16BE", '\u7261', reader.read());
-
- in = new LimitedByteArrayInputStream(2);
- reader = new InputStreamReader(in, "ISO2022JP");
- assertEquals("Incorrect byte ISO2022JP 1", '\u4e5d', reader.read());
- assertEquals("Incorrect byte ISO2022JP 2", '\u7b2c', reader.read());
- }
-
- /**
- * @tests java.io.InputStreamReader#read(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {char[].class, int.class, int.class}
- )
- public void test_read$CII() {
- // Test for method int java.io.InputStreamReader.read(char [], int, int)
- try {
- char[] rbuf = new char[100];
- char[] sbuf = new char[100];
- fileString.getChars(0, 100, sbuf, 0);
- is.read(rbuf, 0, 100);
- for (int i = 0; i < rbuf.length; i++)
- assertTrue("returned incorrect chars", rbuf[i] == sbuf[i]);
- } catch (IOException e) {
- fail("Exception during read test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.InputStreamReader#ready()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "[No verification for empty buffer]",
- method = "ready",
- args = {}
- )
- public void test_ready() {
- // Test for method boolean java.io.InputStreamReader.ready()
- try {
- assertTrue("Ready test failed", is.ready());
- is.read();
- assertTrue("More chars, but not ready", is.ready());
- } catch (IOException e) {
- fail("Exception during ready test : " + e.getMessage());
- }
- }
-
-
-}
diff --git a/luni/src/test/java/tests/api/java/io/InputStreamTest.java b/luni/src/test/java/tests/api/java/io/InputStreamTest.java
deleted file mode 100644
index 0a87df4..0000000
--- a/luni/src/test/java/tests/api/java/io/InputStreamTest.java
+++ /dev/null
@@ -1,402 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.InputStream;
-import java.io.IOException;
-import java.io.ObjectInput;
-
-@TestTargetClass(InputStream.class)
-public class InputStreamTest extends junit.framework.TestCase {
-
- public static final String testString = "Lorem ipsum dolor sit amet,\n" +
- "consectetur adipisicing elit,\nsed do eiusmod tempor incididunt ut" +
- "labore et dolore magna aliqua.\n";
-
- private InputStream is;
-
- class MockInputStream extends java.io.InputStream {
-
- private byte[] input;
- private int position;
-
- public MockInputStream() {
- super();
- input = testString.getBytes();
- position = 0;
- }
-
- public int read() throws IOException {
- int result = -1;
- if (position < input.length) {
- result = input[position];
- position++;
- }
- return result;
- }
- }
-
- /**
- * @tests java.io.InputStream#InputStream()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies constructor InputStream(). Since this constructor does nothing, this test is intentionally kept basic.",
- method = "InputStream",
- args = {}
- )
- public void test_Constructor() {
- try {
- InputStream myIS = new MockInputStream();
- myIS.close();
- } catch (Exception e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.InputStream#available()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies that available() returns 0.",
- method = "available",
- args = {}
- )
- public void test_available() throws IOException {
- assertEquals(is.available(), 0);
- }
-
- /**
- * @tests java.io.InputStream#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies close(). Since this method does nothing, this test is intentionally kept basic.",
- method = "close",
- args = {}
- )
- public void test_close() {
- try {
- is.close();
- } catch (Exception e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.InputStream#mark(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies mark(int). Since this method does nothing, this test is intentionally kept basic.",
- method = "mark",
- args = {int.class}
- )
- public void test_markI() {
- try {
- is.mark(10);
- } catch (Exception e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.InputStream#markSupported()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies that markSupported() returns false.",
- method = "markSupported",
- args = {}
- )
- public void test_markSupported() throws IOException {
- assertFalse("markSupported() has returned the wrong default value.",
- is.markSupported());
- }
-
- /**
- * @tests java.io.InputStream#read(byte[])
- */
- @TestTargets (
- { @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies read(byte[]).",
- method = "read",
- args = {byte[].class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies ObjectInput.read(byte[]) since " +
- "ObjectInputStream inherits the implementation " +
- "of read(byte[]) from InputStream.",
- clazz = ObjectInput.class,
- method = "read",
- args = {byte[].class}
- )
- }
-
- )
- public void test_read$B() throws IOException {
- byte[] b = new byte[10];
- byte[] ref = testString.getBytes();
- boolean equal = true;
- int bytesRead = 0;
- int i;
-
- // Test 1: This read operation should complete without an error.
- assertEquals("Test 1: Incorrect count of bytes read.",
- is.read(b), 10);
-
- for (i = 0; i < 10; i++) {
- equal &= (b[i] == ref[i]);
- }
- assertTrue("Test 1: Wrong bytes read.", equal);
-
- // Test 2: Test that the correct number of bytes read is returned
- // if the source has less bytes available than fit in the buffer.
- b = new byte[ref.length];
- bytesRead = is.read(b);
- assertEquals("Test 2: Incorrect count of bytes read.",
- bytesRead, ref.length - 10);
-
- for (i = 0; i < bytesRead; i++) {
- equal &= (b[i] == ref[i + 10]);
- }
- assertTrue("Test 2: Wrong bytes read.", equal);
-
- // Test 3: Since we have now reached the end of the source,
- // the next call of read(byte[]) should return -1.
- bytesRead = is.read(b);
- assertEquals("Test 3:", bytesRead, -1);
- }
-
- /**
- * @tests java.io.InputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies argument checking of read(byte[], int, int).",
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII_Exception() throws IOException {
- byte[] b = new byte[10];
- int bytesRead = 0;
-
- // Test 1: Invalid offset.
- try {
- bytesRead = is.read(b, -1, 5);
- fail("Test 1: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- // Test 2: Invalid length.
- try {
- bytesRead = is.read(b, 5, -1);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- // Test 3: Invalid offset and length combination (sum is larger
- // than the length of b).
- try {
- bytesRead = is.read(b, 6, 5);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- // Test 4: Border case.
- try {
- bytesRead = is.read(b, 6, 4);
- } catch (IndexOutOfBoundsException e) {
- fail("Test 4: Unexpected IndexOutOfBoundsException.");
- }
- assertEquals("Test 4:", bytesRead, 4);
-
- // Test 5: Border case.
- try {
- bytesRead = is.read(b, 6, 0);
- } catch (Exception e) {
- fail("Test 5: Unexpected Exception " + e.getMessage());
- }
- assertEquals("Test 5:", bytesRead, 0);
- }
-
- /**
- * @tests java.io.InputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies read(byte[], int, int).",
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII() throws IOException {
- byte[] b = new byte[10];
- byte[] ref = testString.getBytes();
- boolean equal = true;
- int bytesRead = 0;
- int i;
-
- // Test 1: This read operation should complete without an error.
- assertEquals("Test 1: Incorrect count of bytes read.",
- is.read(b, 0, 5), 5);
-
- for (i = 0; i < 5; i++) {
- equal &= (b[i] == ref[i]);
- }
- assertTrue("Test 1: Wrong bytes read.", equal);
-
- // Test 2: Read operation with offset.
- assertEquals("Test 2: Incorrect count of bytes read.",
- is.read(b, 5, 3), 3);
-
- for (i = 5; i < 8; i++) {
- equal &= (b[i] == ref[i]);
- }
- assertTrue("Test 2: Wrong bytes read.", equal);
-
- // Test 3: Test that the correct number of bytes read is returned
- // if the source has less bytes available than fit in the buffer.
- b = new byte[ref.length];
- bytesRead = is.read(b, 2, b.length - 2);
-
- // 8 bytes have been read during tests 1 and 2.
- assertEquals("Test 3: Incorrect count of bytes read.",
- bytesRead, ref.length - 8);
-
- // The first two bytes of b should be 0 because of the offset.
- assertEquals("Test 3:", b[0], 0);
- assertEquals("Test 3:", b[1], 0);
- for (i = 0; i < bytesRead; i++) {
- equal &= (b[i + 2] == ref[i + 8]);
- }
- assertTrue("Test 2: Wrong bytes read.", equal);
-
- // Test 4: Since we have now reached the end of the source,
- // the next call of read(byte[], int, int) should return -1.
- assertEquals("Test 4:", is.read(b, 0, 2), -1);
- }
-
- /**
- * @tests java.io.InputStream#reset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies that reset() throws an IOException.",
- method = "reset",
- args = {}
- )
- public void test_reset() {
- try {
- is.reset();
- fail("IOException expected.");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.InputStream#skip(long)
- */
- @TestTargets (
- { @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies skip(long).",
- method = "skip",
- args = {long.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies ObjectInput.skip(long) since " +
- "ObjectInputStream inherits the implementation " +
- "of skip(long) from InputStream.",
- clazz = ObjectInput.class,
- method = "skip",
- args = {long.class}
- )
- }
- )
- public void test_skipL() throws IOException {
- byte[] b = new byte[12];
- byte[] ref = testString.getBytes();
- int i;
- boolean equal = true;
-
- // Test 1: Check that skip(long) just returns 0 if called with a
- // negative number.
- assertEquals("Test 1:", is.skip(-42), 0);
- assertEquals("Test 1: Incorrect count of bytes read.",
- is.read(b), 12);
- for (i = 0; i < 12; i++) {
- equal &= (b[i] == ref[i]);
- }
- assertTrue("Test 1: Wrong bytes read.", equal);
-
- // Test 2: Check if the number of bytes skipped matches the requested
- // number of bytes to skip.
- assertEquals("Test 2: Incorrect count of bytes skipped.",
- is.skip(17), 17);
-
- // Test 3: Check that bytes have actually been skipped
- is.read(b, 0, 10);
- for (i = 0; i < 10; i++) {
- equal &= (b[i] == ref[i + 29]);
- }
- assertTrue("Test 3: Wrong bytes read.", equal);
-
- // Test 4: Test that the correct number of bytes skipped is returned
- // if the source has less bytes available than fit in the buffer.
- assertEquals("Test 4: Incorrect count of bytes skipped.",
- is.skip(ref.length), ref.length - 39);
-
- // Test 5: Since we have now reached the end of the source,
- // the next call of read(byte[]) should return -1 and calling
- // skip(long) should return 0.
- assertEquals("Test 5:", is.read(b), -1);
- assertEquals("Test 5:", is.skip(10), 0);
- }
-
- /**
- * This method is called before a test is executed. It creates a
- * MockInputStream instance.
- */
- protected void setUp() {
- is = new MockInputStream();
- }
-
- /**
- * This method is called after a test is executed. It closes the
- * MockInputStream instance.
- */
- protected void tearDown() {
- try {
- is.close();
- } catch (Exception e) {
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/InterruptedIOExceptionTest.java b/luni/src/test/java/tests/api/java/io/InterruptedIOExceptionTest.java
deleted file mode 100644
index 3a277c2..0000000
--- a/luni/src/test/java/tests/api/java/io/InterruptedIOExceptionTest.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.InterruptedIOException;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(InterruptedIOException.class)
-public class InterruptedIOExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.io.InterruptedIOException#InterruptedIOException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InterruptedIOException",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.io.InterruptedIOException()
- try {
- throw new InterruptedIOException();
- } catch (InterruptedIOException e) {
- return;
- } catch (Exception e) {
- fail("Exception during InterruptedIOException test"
- + e.toString());
- }
- fail("Failed to generate exception");
- }
-
- /**
- * @tests java.io.InterruptedIOException#InterruptedIOException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InterruptedIOException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.io.InterruptedIOException(java.lang.String)
- try {
- throw new InterruptedIOException("Some error message");
- } catch (InterruptedIOException e) {
- return;
- } catch (Exception e) {
- fail("Exception during InterruptedIOException test"
- + e.toString());
- }
- fail("Failed to generate exception");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/InvalidClassExceptionTest.java b/luni/src/test/java/tests/api/java/io/InvalidClassExceptionTest.java
deleted file mode 100644
index 5b90633..0000000
--- a/luni/src/test/java/tests/api/java/io/InvalidClassExceptionTest.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import java.io.InvalidClassException;
-
-@TestTargetClass(InvalidClassException.class)
-public class InvalidClassExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.io.InvalidClassException#InvalidClassException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InvalidClassException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- final String message = "A message";
- try {
- if (true)
- throw new java.io.InvalidClassException(message);
- } catch (InvalidClassException e) {
- // correct
- assertTrue("Incorrect message read", e.getMessage().equals(message));
- return;
- }
- fail("Failed to throw exception");
- }
-
- /**
- * @tests java.io.InvalidClassException#InvalidClassException(java.lang.String,
- * java.lang.String)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InvalidClassException",
- args = {java.lang.String.class, java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
- })
- public void test_ConstructorLjava_lang_StringLjava_lang_String() {
- // Test for method java.io.InvalidClassException(java.lang.String,
- // java.lang.String)
- final String message = "A message";
- final String className = "Object";
- try {
- if (true)
- throw new java.io.InvalidClassException(className, message);
- } catch (InvalidClassException e) {
- // correct
- String returnedMessage = e.getMessage();
- assertTrue("Incorrect message read: " + e.getMessage(),
- returnedMessage.indexOf(className) >= 0
- && returnedMessage.indexOf(message) >= 0);
- return;
- }
- fail("Failed to throw exception");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/InvalidObjectExceptionTest.java b/luni/src/test/java/tests/api/java/io/InvalidObjectExceptionTest.java
deleted file mode 100644
index 9270d63..0000000
--- a/luni/src/test/java/tests/api/java/io/InvalidObjectExceptionTest.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.InvalidObjectException;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(java.io.InvalidObjectException.class)
-public class InvalidObjectExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.io.InvalidObjectException#InvalidObjectException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies the InvalidObjectException(java.lang.String) constructor.",
- method = "InvalidObjectException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.io.InvalidObjectException(java.lang.String)
- try {
- if (true) throw new InvalidObjectException("This object is not valid.");
- fail("Exception not thrown.");
- } catch (InvalidObjectException e) {
- assertEquals("The exception message is not equal to the one " +
- "passed to the constructor.",
- "This object is not valid.", e.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/LineNumberInputStreamTest.java b/luni/src/test/java/tests/api/java/io/LineNumberInputStreamTest.java
deleted file mode 100644
index 491def9..0000000
--- a/luni/src/test/java/tests/api/java/io/LineNumberInputStreamTest.java
+++ /dev/null
@@ -1,308 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.LineNumberInputStream;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@SuppressWarnings("deprecation")
-@TestTargetClass(
- value = LineNumberInputStream.class,
- untestedMethods = {
- @TestTargetNew(
- method = "LineNumberInputStream",
- args = {java.io.InputStream.class},
- level = TestLevel.NOT_NECESSARY,
- notes = "Simply calls super(in). If this fails, " +
- "none of the other tests would work."
- )
- }
-)
-public class LineNumberInputStreamTest extends junit.framework.TestCase {
-
- final String text = "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40\n41\n42\n43\n44\n45\n46\n47\n48\n49\n50\n51\n52\n53\n54\n55\n56\n57\n58\n59\n60\n61\n62\n63\n64\n65\n66\n67\n68\n69\n70\n71\n72\n73\n74\n75\n76\n77\n78\n79\n80\n81\n82\n83\n84\n85\n86\n87\n88\n89\n90\n91\n92\n93\n94\n95\n96\n97\n98\n99\n100\n101\n102\n103\n104\n105\n106\n107\n108\n109\n110\n111\n112\n113\n114\n115\n116\n117\n118\n119\n120\n121\n122\n123\n124\n125\n126\n127\n128\n129\n130\n131\n132\n133\n134\n135\n136\n137\n138\n139\n140\n141\n142\n143\n144\n145\n146\n147\n148\n149\n150\n151\n152\n153\n154\n155\n156\n157\n158\n159\n160\n161\n162\n163\n164\n165\n166\n167\n168\n169\n170\n171\n172\n173\n174\n175\n176\n177\n178\n179\n180\n181\n182\n183\n184\n185\n186\n187\n188\n189\n190\n191\n192\n193\n194\n195\n196\n197\n198\n199\n200\n201\n202\n203\n204\n205\n206\n207\n208\n209\n210\n211\n212\n213\n214\n215\n216\n217\n218\n219\n220\n221\n222\n223\n224\n225\n226\n227\n228\n229\n230\n231\n232\n233\n234\n235\n236\n237\n238\n239\n240\n241\n242\n243\n244\n245\n246\n247\n248\n249\n250\n251\n252\n253\n254\n255\n256\n257\n258\n259\n260\n261\n262\n263\n264\n265\n266\n267\n268\n269\n270\n271\n272\n273\n274\n275\n276\n277\n278\n279\n280\n281\n282\n283\n284\n285\n286\n287\n288\n289\n290\n291\n292\n293\n294\n295\n296\n297\n298\n299\n300\n301\n302\n303\n304\n305\n306\n307\n308\n309\n310\n311\n312\n313\n314\n315\n316\n317\n318\n319\n320\n321\n322\n323\n324\n325\n326\n327\n328\n329\n330\n331\n332\n333\n334\n335\n336\n337\n338\n339\n340\n341\n342\n343\n344\n345\n346\n347\n348\n349\n350\n351\n352\n353\n354\n355\n356\n357\n358\n359\n360\n361\n362\n363\n364\n365\n366\n367\n368\n369\n370\n371\n372\n373\n374\n375\n376\n377\n378\n379\n380\n381\n382\n383\n384\n385\n386\n387\n388\n389\n390\n391\n392\n393\n394\n395\n396\n397\n398\n399\n400\n401\n402\n403\n404\n405\n406\n407\n408\n409\n410\n411\n412\n413\n414\n415\n416\n417\n418\n419\n420\n421\n422\n423\n424\n425\n426\n427\n428\n429\n430\n431\n432\n433\n434\n435\n436\n437\n438\n439\n440\n441\n442\n443\n444\n445\n446\n447\n448\n449\n450\n451\n452\n453\n454\n455\n456\n457\n458\n459\n460\n461\n462\n463\n464\n465\n466\n467\n468\n469\n470\n471\n472\n473\n474\n475\n476\n477\n478\n479\n480\n481\n482\n483\n484\n485\n486\n487\n488\n489\n490\n491\n492\n493\n494\n495\n496\n497\n498\n499\n500\n501";
-
- String dosText = "0\r\n1\r\n2";
-
- LineNumberInputStream lnis;
-
- LineNumberInputStream lnis2;
-
- /**
- * @tests java.io.LineNumberInputStream#available()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "available",
- args = {}
- )
- public void test_available() throws IOException {
- assertEquals("Test 1: Returned incorrect number of available bytes;",
- text.length() / 2, lnis.available());
-
- lnis.close();
- try {
- lnis.available();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.LineNumberInputStream#getLineNumber()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLineNumber",
- args = {}
- )
- public void test_getLineNumber() {
- // Test for method int java.io.LineNumberInputStream.getLineNumber()
- assertEquals("New stream returned line number other than zero", 0, lnis
- .getLineNumber());
- try {
- lnis.read();
- lnis.read();
- } catch (IOException e) {
- fail("Exception during getLineNumber test : " + e.getMessage());
- }
- assertEquals("stream returned incorrect line number after read", 1, lnis
- .getLineNumber());
- lnis.setLineNumber(89);
- assertEquals("stream returned incorrect line number after set", 89, lnis
- .getLineNumber());
- }
-
- /**
- * @tests java.io.LineNumberInputStream#mark(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "mark",
- args = {int.class}
- )
- public void test_markI() {
- // Test for method void java.io.LineNumberInputStream.mark(int)
- try {
- lnis.mark(40);
- lnis.skip(4);
- lnis.reset();
- assertEquals("Failed to mark", 0, lnis.getLineNumber());
- assertEquals("Failed to mark", '0', lnis.read());
- } catch (IOException e) {
- fail("Exception during mark test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.LineNumberInputStream#read()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "read",
- args = {}
- )
- public void test_read() throws IOException {
- assertEquals("Test 1: Failed to read correct byte;",
- '0', lnis.read());
- assertEquals("Test 2: Failed to read correct byte on dos text;",
- '0', lnis2.read());
- assertEquals("Test 3: Failed to read correct byte on dos text;",
- '\n', lnis2.read());
- assertEquals("Test 4: Failed to read correct byte on dos text;",
- '1', lnis2.read());
- assertEquals("Test 5: Failed to read correct byte on dos text;",
- '\n', lnis2.read());
- assertEquals("Test 6: Failed to read correct byte on dos text;",
- '2', lnis2.read());
-
- lnis.close();
- try {
- lnis.read();
- fail("Test 7: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.LineNumberInputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII() throws IOException {
- byte[] buf = new byte[100];
- lnis.read(buf, 0, 100);
- assertTrue("Test 1: Incorrect bytes read.",
- new String(buf, 0, 100).equals(text.substring(0, 100)));
-
- lnis.close();
- try {
- lnis.read(buf, 0, 100);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.LineNumberInputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII_Exception() throws IOException {
- byte[] buf = new byte[10];
-
- try {
- lnis.read(buf, -1, 1);
- fail("IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- lnis.read(buf, 0, -1);
- fail("IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- lnis.read(buf, 10, 1);
- fail("IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.LineNumberInputStream#reset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "IOException checking missed.",
- method = "reset",
- args = {}
- )
- public void test_reset() throws IOException {
- lnis.mark(40);
- lnis.skip(4);
- lnis.reset();
- assertEquals("Test 1: Failed to reset", 0, lnis.getLineNumber());
- assertEquals("Test 2: Failed to reset", '0', lnis.read());
- lnis.reset();
-
- try {
- lnis.mark(5);
- lnis.skip(100);
- lnis.reset();
- fail("Test 3: Failed to invalidate mark.");
- } catch (IOException e) {
- // Correct; mark has been invalidated.
- }
-
- lnis.mark(5);
- lnis.close();
- try {
- lnis.reset();
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.LineNumberInputStream#setLineNumber(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setLineNumber",
- args = {int.class}
- )
- public void test_setLineNumberI() {
- lnis.setLineNumber(42);
- assertEquals("Test 1: Failed to set line number;",
- 42, lnis.getLineNumber());
- // Repeat the test with a different number to make sure that the
- // line number is really set.
- lnis.setLineNumber(89);
- assertEquals("Test 2: Failed to set line number;",
- 89, lnis.getLineNumber());
- }
-
- /**
- * @tests java.io.LineNumberInputStream#skip(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "skip",
- args = {long.class}
- )
- public void test_skipJ() throws IOException {
- long skipped = lnis.skip(4);
- assertEquals("Test 1: Incorrect number of characters skipped;",
- 4, skipped);
- assertEquals("Test 2: Skip failed to increment line number;",
- 2, lnis.getLineNumber());
-
- lnis.close();
- try {
- lnis.skip(4);
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- protected void setUp() {
- /*
- * In order for IOException to be thrown in reset(),the inputStream to
- * the constructor cannot be a byteArrayInputstream because the reset()
- * in byteArrayInputStream does not throw IOException. When
- * BufferedInputStream is used, the size of the buffer must be smaller
- * than the readlimit in mark inorder for IOException to be thrown
- */
- BufferedInputStream buftemp = new BufferedInputStream(
- new ByteArrayInputStream(text.getBytes()), 4);
- lnis = new LineNumberInputStream(buftemp);
- lnis2 = new LineNumberInputStream(new ByteArrayInputStream(dosText
- .getBytes()));
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/LineNumberReaderTest.java b/luni/src/test/java/tests/api/java/io/LineNumberReaderTest.java
deleted file mode 100644
index 3e1ca4a..0000000
--- a/luni/src/test/java/tests/api/java/io/LineNumberReaderTest.java
+++ /dev/null
@@ -1,310 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.IOException;
-import java.io.LineNumberReader;
-import java.io.StringReader;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(LineNumberReader.class)
-public class LineNumberReaderTest extends junit.framework.TestCase {
-
- String text = "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31\n32\n33\n34\n35\n36\n37\n38\n39\n40\n41\n42\n43\n44\n45\n46\n47\n48\n49\n50\n51\n52\n53\n54\n55\n56\n57\n58\n59\n60\n61\n62\n63\n64\n65\n66\n67\n68\n69\n70\n71\n72\n73\n74\n75\n76\n77\n78\n79\n80\n81\n82\n83\n84\n85\n86\n87\n88\n89\n90\n91\n92\n93\n94\n95\n96\n97\n98\n99\n100\n101\n102\n103\n104\n105\n106\n107\n108\n109\n110\n111\n112\n113\n114\n115\n116\n117\n118\n119\n120\n121\n122\n123\n124\n125\n126\n127\n128\n129\n130\n131\n132\n133\n134\n135\n136\n137\n138\n139\n140\n141\n142\n143\n144\n145\n146\n147\n148\n149\n150\n151\n152\n153\n154\n155\n156\n157\n158\n159\n160\n161\n162\n163\n164\n165\n166\n167\n168\n169\n170\n171\n172\n173\n174\n175\n176\n177\n178\n179\n180\n181\n182\n183\n184\n185\n186\n187\n188\n189\n190\n191\n192\n193\n194\n195\n196\n197\n198\n199\n200\n201\n202\n203\n204\n205\n206\n207\n208\n209\n210\n211\n212\n213\n214\n215\n216\n217\n218\n219\n220\n221\n222\n223\n224\n225\n226\n227\n228\n229\n230\n231\n232\n233\n234\n235\n236\n237\n238\n239\n240\n241\n242\n243\n244\n245\n246\n247\n248\n249\n250\n251\n252\n253\n254\n255\n256\n257\n258\n259\n260\n261\n262\n263\n264\n265\n266\n267\n268\n269\n270\n271\n272\n273\n274\n275\n276\n277\n278\n279\n280\n281\n282\n283\n284\n285\n286\n287\n288\n289\n290\n291\n292\n293\n294\n295\n296\n297\n298\n299\n300\n301\n302\n303\n304\n305\n306\n307\n308\n309\n310\n311\n312\n313\n314\n315\n316\n317\n318\n319\n320\n321\n322\n323\n324\n325\n326\n327\n328\n329\n330\n331\n332\n333\n334\n335\n336\n337\n338\n339\n340\n341\n342\n343\n344\n345\n346\n347\n348\n349\n350\n351\n352\n353\n354\n355\n356\n357\n358\n359\n360\n361\n362\n363\n364\n365\n366\n367\n368\n369\n370\n371\n372\n373\n374\n375\n376\n377\n378\n379\n380\n381\n382\n383\n384\n385\n386\n387\n388\n389\n390\n391\n392\n393\n394\n395\n396\n397\n398\n399\n400\n401\n402\n403\n404\n405\n406\n407\n408\n409\n410\n411\n412\n413\n414\n415\n416\n417\n418\n419\n420\n421\n422\n423\n424\n425\n426\n427\n428\n429\n430\n431\n432\n433\n434\n435\n436\n437\n438\n439\n440\n441\n442\n443\n444\n445\n446\n447\n448\n449\n450\n451\n452\n453\n454\n455\n456\n457\n458\n459\n460\n461\n462\n463\n464\n465\n466\n467\n468\n469\n470\n471\n472\n473\n474\n475\n476\n477\n478\n479\n480\n481\n482\n483\n484\n485\n486\n487\n488\n489\n490\n491\n492\n493\n494\n495\n496\n497\n498\n499\n500\n";
-
- LineNumberReader lnr;
-
- /**
- * @tests java.io.LineNumberReader#LineNumberReader(java.io.Reader)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "LineNumberReader",
- args = {java.io.Reader.class, int.class}
- )
- public void test_ConstructorLjava_io_Reader() {
- // Test for method java.io.LineNumberReader(java.io.Reader)
- lnr = new LineNumberReader(new StringReader(text), 4092);
- assertEquals("Failed to create reader", 0, lnr.getLineNumber());
- }
-
- /**
- * @tests java.io.LineNumberReader#LineNumberReader(java.io.Reader, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "LineNumberReader",
- args = {java.io.Reader.class}
- )
- public void test_ConstructorLjava_io_ReaderI() {
- // Test for method java.io.LineNumberReader(java.io.Reader, int)
- lnr = new LineNumberReader(new StringReader(text));
- assertEquals("Failed to create reader", 0, lnr.getLineNumber());
- }
-
- /**
- * @tests java.io.LineNumberReader#getLineNumber()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLineNumber",
- args = {}
- )
- public void test_getLineNumber() {
- // Test for method int java.io.LineNumberReader.getLineNumber()
- lnr = new LineNumberReader(new StringReader(text));
- assertEquals("Returned incorrect line number--expected 0, got ", 0, lnr
- .getLineNumber());
- try {
- lnr.readLine();
- lnr.readLine();
- } catch (IOException e) {
- fail("Exception during getLineNumberTest: " + e.toString());
- }
- assertTrue("Returned incorrect line number--expected 2, got: "
- + lnr.getLineNumber(), lnr.getLineNumber() == 2);
- }
-
- /**
- * @tests java.io.LineNumberReader#mark(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "mark",
- args = {int.class}
- )
- public void test_markI() throws IOException {
- lnr = new LineNumberReader(new StringReader(text));
- String line;
- lnr.skip(80);
- lnr.mark(100);
- line = lnr.readLine();
- lnr.reset();
- assertTrue("Test 1: Failed to return to marked position.",
- line.equals(lnr.readLine()));
-
- lnr.close();
- try {
- lnr.mark(42);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- // The spec does not say the mark has to be invalidated
- }
-
- /**
- * @tests java.io.LineNumberReader#read()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "read",
- args = {}
- )
- public void test_read() throws IOException {
- lnr = new LineNumberReader(new StringReader(text));
-
- int c = lnr.read();
- assertEquals("Test 1: Read returned incorrect character;",
- '0', c);
- lnr.read();
- assertEquals("Test 2: Read failed to increase the line number;",
- 1, lnr.getLineNumber());
-
- lnr.close();
- try {
- lnr.read();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.LineNumberReader#read(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "read",
- args = {char[].class, int.class, int.class}
- )
- public void test_read$CII() throws IOException {
- lnr = new LineNumberReader(new StringReader(text));
- char[] c = new char[100];
- lnr.read(c, 0, 4);
- assertTrue("Test 1: Read returned incorrect characters.", "0\n1\n"
- .equals(new String(c, 0, 4)));
- assertEquals("Test 2: Read failed to inc lineNumber",
- 2, lnr.getLineNumber());
-
- lnr.close();
- try {
- lnr.read(c, 0, 4);
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.LineNumberReader#read(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "read",
- args = {char[].class, int.class, int.class}
- )
- public void test_read$CII_Exception() throws IOException {
- lnr = new LineNumberReader(new StringReader(text));
- char[] c = new char[10];
-
- try {
- lnr.read(c, -1, 1);
- fail("IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- lnr.read(c, 0, -1);
- fail("IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- lnr.read(c, 10, 1);
- fail("IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.LineNumberReader#readLine()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "readLine",
- args = {}
- )
- public void test_readLine() throws IOException {
- lnr = new LineNumberReader(new StringReader(text));
- assertEquals("Returned incorrect line number", 0, lnr.getLineNumber());
- String line = null;
- lnr.readLine();
- line = lnr.readLine();
- assertEquals("Test 1: Returned incorrect string;", "1", line);
- assertTrue("Test 2: Returned incorrect line number:" + lnr.getLineNumber(),
- lnr.getLineNumber() == 2);
-
- lnr.close();
- try {
- lnr.readLine();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.LineNumberReader#reset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "reset",
- args = {}
- )
- public void test_reset() throws IOException {
- lnr = new LineNumberReader(new StringReader(text));
- assertEquals("Test 1: Returned incorrect line number;",
- 0, lnr.getLineNumber());
- String line = null;
- lnr.mark(100);
- lnr.readLine();
- lnr.reset();
- line = lnr.readLine();
- assertEquals("Test 2: Failed to reset reader", "0", line);
-
- lnr.mark(100);
- lnr.close();
- try {
- lnr.reset();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.LineNumberReader#setLineNumber(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setLineNumber",
- args = {int.class}
- )
- public void test_setLineNumberI() {
- // Test for method void java.io.LineNumberReader.setLineNumber(int)
- lnr = new LineNumberReader(new StringReader(text));
- lnr.setLineNumber(1001);
- assertEquals("set incorrect line number", 1001, lnr.getLineNumber());
- }
-
- /**
- * @tests java.io.LineNumberReader#skip(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "skip",
- args = {long.class}
- )
- public void test_skipJ() throws IOException {
- lnr = new LineNumberReader(new StringReader(text));
- char[] c = new char[100];
- long skipped = lnr.skip(80);
- assertEquals("Test 1: Incorrect number of characters skipped;",
- 80, skipped);
- lnr.read(c, 0, 100);
- assertTrue("Test 2: Failed to skip to correct position.",
- text.substring(80, 180).equals(new String(c, 0, c.length)));
-
- try {
- lnr.skip(-1);
- fail("Test 3: IllegalArgumentException expected.");
- } catch (IllegalArgumentException e) {
- // Expected.
- }
-
- lnr.close();
- try {
- lnr.skip(1);
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/NotActiveExceptionTest.java b/luni/src/test/java/tests/api/java/io/NotActiveExceptionTest.java
deleted file mode 100644
index 66b20b1..0000000
--- a/luni/src/test/java/tests/api/java/io/NotActiveExceptionTest.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.NotActiveException;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(NotActiveException.class)
-public class NotActiveExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.io.NotActiveException#NotActiveException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "NotActiveException",
- args = {}
- )
- public void test_Constructor() {
- try {
- if (true) // To avoid unreachable code compilation error.
- throw new NotActiveException();
- fail("Test 1: NotActiveException expected.");
- } catch (NotActiveException e) {
- assertNull("Test 2: Null expected for exceptions constructed without a message.",
- e.getMessage());
- }
- }
-
- /**
- * @tests java.io.NotActiveException#NotActiveException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "NotActiveException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- try {
- if (true) // To avoid unreachable code compilation error.
- throw new NotActiveException("Something went wrong.");
- fail("Test 1: NotActiveException expected.");
- } catch (NotActiveException e) {
- assertEquals("Test 2: Incorrect message;",
- "Something went wrong.", e.getMessage());
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/io/NotSerializableExceptionTest.java b/luni/src/test/java/tests/api/java/io/NotSerializableExceptionTest.java
deleted file mode 100644
index 371064f..0000000
--- a/luni/src/test/java/tests/api/java/io/NotSerializableExceptionTest.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.NotSerializableException;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(NotSerializableException.class)
-public class NotSerializableExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.io.NotSerializableException#NotSerializableException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "NotSerializableException",
- args = {}
- )
- public void test_Constructor() {
- try {
- if (true) // To avoid unreachable code compilation error.
- throw new NotSerializableException();
- fail("Test 1: NotSerializableException expected.");
- } catch (NotSerializableException e) {
- assertNull("Test 2: Null expected for exceptions constructed without a message.",
- e.getMessage());
- }
- }
-
- /**
- * @tests java.io.NotSerializableException#NotSerializableException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "NotSerializableException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- try {
- if (true) // To avoid unreachable code compilation error.
- throw new NotSerializableException("Something went wrong.");
- fail("Test 1: NotSerializableException expected.");
- } catch (NotSerializableException e) {
- assertEquals("Test 2: Incorrect message;",
- "Something went wrong.", e.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/ObjectInputOutputStreamTest.java b/luni/src/test/java/tests/api/java/io/ObjectInputOutputStreamTest.java
deleted file mode 100644
index e9cf18b..0000000
--- a/luni/src/test/java/tests/api/java/io/ObjectInputOutputStreamTest.java
+++ /dev/null
@@ -1,468 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.ByteArrayInputStream;
-import java.io.EOFException;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-
-import tests.support.Support_OutputStream;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-@TestTargetClass(ObjectOutputStream.class)
-public class ObjectInputOutputStreamTest extends junit.framework.TestCase {
-
- private ObjectOutputStream os;
-
- private ObjectInputStream is;
-
- private Support_OutputStream sos;
-
- String unihw = "\u0048\u0065\u006C\u006C\u006F\u0020\u0057\u006F\u0072\u006C\u0064";
-
- /**
- * @tests java.io.ObjectInputStream#readBoolean()
- * @tests java.io.ObjectOutputStream#writeBoolean(boolean)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing. IOException can " +
- "not be checked since is never thrown (primitive data " +
- "is written into a self-expanding buffer).",
- method = "writeBoolean",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readBoolean",
- args = {},
- clazz = ObjectInputStream.class
- )
- })
- public void test_read_writeBoolean() throws IOException {
- os.writeBoolean(true);
-
- os.close();
- openObjectInputStream();
- assertTrue("Test 1: Incorrect boolean written or read.",
- is.readBoolean());
-
- try {
- is.readBoolean();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- is.close();
- try {
- is.readBoolean();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ObjectInputStream#readByte()
- * @tests java.io.ObjectOutputStream#writeByte(int)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing. IOException can " +
- "not be checked since is never thrown (primitive data " +
- "is written into a self-expanding buffer).",
- method = "writeByte",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readByte",
- args = {},
- clazz = ObjectInputStream.class
- )
- })
- public void test_read_writeByte() throws IOException {
- os.writeByte((byte) 127);
-
- os.close();
- openObjectInputStream();
- assertEquals("Test 1: Incorrect byte written or read;",
- (byte) 127, is.readByte());
-
- try {
- is.readByte();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- is.close();
- try {
- is.readByte();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ObjectInputStream#readChar()
- * @tests java.io.ObjectOutputStream#writeChar(int)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing. IOException can " +
- "not be checked since is never thrown (primitive data " +
- "is written into a self-expanding buffer).",
- method = "writeChar",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readChar",
- args = {},
- clazz = ObjectInputStream.class
- )
- })
- public void test_read_writeChar() throws IOException {
- os.writeChar('b');
-
- os.close();
- openObjectInputStream();
- assertEquals("Test 1: Incorrect char written or read;",
- 'b', is.readChar());
-
- try {
- is.readChar();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- is.close();
- try {
- is.readChar();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ObjectInputStream#readDouble()
- * @tests java.io.ObjectOutputStream#writeDouble(double)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing. IOException can " +
- "not be checked since is never thrown (primitive data " +
- "is written into a self-expanding buffer).",
- method = "writeDouble",
- args = {double.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readDouble",
- args = {},
- clazz = ObjectInputStream.class
- )
- })
- public void test_read_writeDouble() throws IOException {
- os.writeDouble(2345.76834720202);
-
- os.close();
- openObjectInputStream();
- assertEquals("Test 1: Incorrect double written or read;",
- 2345.76834720202, is.readDouble());
-
- try {
- is.readDouble();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- is.close();
- try {
- is.readDouble();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ObjectInputStream#readFloat()
- * @tests java.io.ObjectOutputStream#writeFloat(float)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing. IOException can " +
- "not be checked since is never thrown (primitive data " +
- "is written into a self-expanding buffer).",
- method = "writeFloat",
- args = {float.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readFloat",
- args = {},
- clazz = ObjectInputStream.class
- )
- })
- public void test_read_writeFloat() throws IOException {
- os.writeFloat(29.08764f);
-
- os.close();
- openObjectInputStream();
- assertEquals("Test 1: Incorrect float written or read;",
- 29.08764f, is.readFloat());
-
- try {
- is.readFloat();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- is.close();
- try {
- is.readFloat();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ObjectInputStream#readInt()
- * @tests java.io.ObjectOutputStream#writeInt(int)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing. IOException can " +
- "not be checked since is never thrown (primitive data " +
- "is written into a self-expanding buffer).",
- method = "writeInt",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readInt",
- args = {},
- clazz = ObjectInputStream.class
- )
- })
- public void test_read_writeInt() throws IOException {
- os.writeInt(768347202);
-
- os.close();
- openObjectInputStream();
- assertEquals("Test 1: Incorrect int written or read;",
- 768347202, is.readInt());
-
- try {
- is.readInt();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- is.close();
- try {
- is.readInt();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ObjectInputStream#readLong()
- * @tests java.io.ObjectOutputStream#writeLong(long)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing. IOException can " +
- "not be checked since is never thrown (primitive data " +
- "is written into a self-expanding buffer).",
- method = "writeLong",
- args = {long.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readLong",
- args = {},
- clazz = ObjectInputStream.class
- )
- })
- public void test_read_writeLong() throws IOException {
- os.writeLong(9875645283333L);
-
- os.close();
- openObjectInputStream();
- assertEquals("Test 1: Incorrect long written or read;",
- 9875645283333L, is.readLong());
-
- try {
- is.readLong();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- is.close();
- try {
- is.readLong();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ObjectInputStream#readShort()
- * @tests java.io.ObjectOutputStream#writeShort(short)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing. IOException can " +
- "not be checked since is never thrown (primitive data " +
- "is written into a self-expanding buffer).",
- method = "writeShort",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readShort",
- args = {},
- clazz = ObjectInputStream.class
- )
- })
- public void test_read_writeShort() throws IOException {
- os.writeShort(9875);
-
- os.close();
- openObjectInputStream();
- assertEquals("Test 1: Incorrect short written or read;",
- 9875, is.readShort());
-
- try {
- is.readShort();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- is.close();
- try {
- is.readShort();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
-
- /**
- * @tests java.io.ObjectInputStream#readUTF()
- * @tests java.io.ObjectOutputStream#writeUTF(java.lang.String)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing. IOException can " +
- "not be checked since is never thrown (primitive data " +
- "is written into a self-expanding buffer).",
- method = "writeUTF",
- args = {String.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readUTF",
- args = {},
- clazz = ObjectInputStream.class
- )
- })
- public void test_read_writeUTF() throws IOException {
- os.writeUTF(unihw);
-
- os.close();
- openObjectInputStream();
- assertTrue("Test 1: Incorrect UTF-8 string written or read.",
- is.readUTF().equals(unihw));
-
- try {
- is.readUTF();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- is.close();
- try {
- is.readUTF();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- private void openObjectInputStream() throws IOException {
- is = new ObjectInputStream(
- new ByteArrayInputStream(sos.toByteArray()));
- }
-
- protected void setUp() throws IOException {
- sos = new Support_OutputStream(256);
- os = new ObjectOutputStream(sos);
- }
-
- protected void tearDown() {
- try {
- os.close();
- } catch (Exception e) {
- }
- try {
- is.close();
- } catch (Exception e) {
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/ObjectInputStreamGetFieldTest.java b/luni/src/test/java/tests/api/java/io/ObjectInputStreamGetFieldTest.java
deleted file mode 100644
index 1690ff4..0000000
--- a/luni/src/test/java/tests/api/java/io/ObjectInputStreamGetFieldTest.java
+++ /dev/null
@@ -1,400 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.ObjectInputStream;
-
-import tests.support.Support_GetPutFields;
-import tests.support.Support_GetPutFieldsDefaulted;
-
-
-/**
- * Tests the methods of {@code ObjectInputStream.GetField}. Three things make
- * this class somewhat difficult to test:
- * <ol>
- * <li>It is a completely abstract class; none of the methods is implemented in
- * {@code ObjectInputStream.GetField}.</li>
- * <li>There is no public class that implements
- * {@code ObjectInputStream.GetField}. The only way to get an implementation is
- * by calling {@code ObjectInputStream.getFields()}.</li>
- * <li>Invoking {@code ObjectOutputStream.getFields()} only works from within
- * the private {@code readObject(ObjectInputStream)} method of a class that
- * implements {@code Serializable}; an exception is thrown otherwise.</li>
- * </ol>
- * <p>
- * Given these restrictions, an indirect approach is used to test
- * {@code ObjectInputStream.GetField}: Three serializable helper classes in
- * package {@code tests.support} ({@code Support_GetPutFields},
- * {@code Support_GetPutFieldsDeprecated} and
- * {@code Support_GetPutFieldsDefaulted}) implement
- * {@code readObject(ObjectInputStream)} to read data from an input stream.
- * This input stream in turn reads from one of the corresponding files
- * ({@code testFields.ser}, {@code testFieldsDeprecated.ser} and
- * {@code testFieldsDefaulted.ser}) that have been created with
- * {@code tests.util.FieldTestFileGenerator} on a reference platform.
- * </p>
- * <p>
- * The test method in this class expects to find the reference files as a
- * resource stored at {@code tests/api/java/io}.
- * </p>
- */
-@TestTargetClass(ObjectInputStream.GetField.class)
-public class ObjectInputStreamGetFieldTest extends junit.framework.TestCase {
-
- private ObjectInputStream ois = null;
-
- private final String FILENAME =
- "tests/api/java/io/testFields.ser";
- private final String DEFAULTED_FILENAME =
- "tests/api/java/io/testFieldsDefaulted.ser";
-
- public boolean booleanValue;
- public byte byteValue;
- public char charValue;
- public int intValue;
-
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the get(String, X) methods with valid arguments.",
- method = "get",
- args = {java.lang.String.class, boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the get(String, X) methods with valid arguments.",
- method = "get",
- args = {java.lang.String.class, byte.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the get(String, X) methods with valid arguments.",
- method = "get",
- args = {java.lang.String.class, char.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the get(String, X) methods with valid arguments.",
- method = "get",
- args = {java.lang.String.class, double.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the get(String, X) methods with valid arguments.",
- method = "get",
- args = {java.lang.String.class, float.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the get(String, X) methods with valid arguments.",
- method = "get",
- args = {java.lang.String.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the get(String, X) methods with valid arguments.",
- method = "get",
- args = {java.lang.String.class, long.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the get(String, X) methods with valid arguments.",
- method = "get",
- args = {java.lang.String.class, java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the get(String, X) methods with valid arguments.",
- method = "get",
- args = {java.lang.String.class, short.class}
- )
- })
- public void test_get() throws Exception {
-
- initOis(FILENAME);
- Support_GetPutFields object = (Support_GetPutFields) ois.readObject();
- Support_GetPutFields newObject = new Support_GetPutFields();
- newObject.initTestValues();
-
- assertTrue("Test 1: The object read from the reference file does " +
- "not match a locally created instance of the same class.",
- object.equals(newObject));
-
- initOis(DEFAULTED_FILENAME);
- Support_GetPutFieldsDefaulted defaulted =
- (Support_GetPutFieldsDefaulted) ois.readObject();
- Support_GetPutFieldsDefaulted newDefaulted =
- new Support_GetPutFieldsDefaulted();
- newDefaulted.initTestValues();
-
- assertTrue("Test 2: The object read from the reference file does " +
- "not match a locally created instance of the same class.",
- defaulted.equals(newDefaulted));
-
- // Executing the same procedure against the file created with the
- // deprecated ObjectOutputStream.PutFields.write(ObjectOutput) method
- // is not possible since there is no corresponding read(ObjectInput)
- // method. When trying to do it as in tests 1 and 2, a
- // NullPointerException is thrown.
- }
-
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies defaulted(String).",
- method = "defaulted",
- args = {java.lang.String.class}
- )
- public void test_defaultedLjava_lang_String() throws Exception {
-
- initOis(FILENAME);
- Support_GetPutFields object = (Support_GetPutFields) ois.readObject();
- ObjectInputStream.GetField fields = object.getField;
-
- try {
- fields.defaulted("noField");
- fail("IllegalArgumentException expected.");
- } catch (IllegalArgumentException e) {}
-
- assertFalse("The field longValue should not be defaulted.",
- fields.defaulted("longValue"));
-
- // Now the same with defaulted fields.
- initOis(DEFAULTED_FILENAME);
- Support_GetPutFieldsDefaulted defaultedObject =
- (Support_GetPutFieldsDefaulted) ois.readObject();
- fields = defaultedObject.getField;
-
- assertTrue("The field longValue should be defaulted.",
- fields.defaulted("longValue"));
-
- }
-
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the get(String, X) methods with invalid arguments.",
- method = "get",
- args = {java.lang.String.class, boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the get(String, X) methods with invalid arguments.",
- method = "get",
- args = {java.lang.String.class, byte.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the get(String, X) methods with invalid arguments.",
- method = "get",
- args = {java.lang.String.class, char.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the get(String, X) methods with invalid arguments.",
- method = "get",
- args = {java.lang.String.class, double.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the get(String, X) methods with invalid arguments.",
- method = "get",
- args = {java.lang.String.class, float.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the get(String, X) methods with invalid arguments.",
- method = "get",
- args = {java.lang.String.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the get(String, X) methods with invalid arguments.",
- method = "get",
- args = {java.lang.String.class, long.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the get(String, X) methods with invalid arguments.",
- method = "get",
- args = {java.lang.String.class, java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the get(String, X) methods with invalid arguments.",
- method = "get",
- args = {java.lang.String.class, short.class}
- )
- })
- public void test_getException() throws Exception {
-
- initOis(FILENAME);
- Support_GetPutFields object = (Support_GetPutFields) ois.readObject();
- ObjectInputStream.GetField fields = object.getField;
-
- // Methods called with invalid field name.
- try {
- fields.get("noValue", false);
- fail("IllegalArgumentException expected for not existing name " +
- "argument in get(String, boolean).");
- } catch (IllegalArgumentException e) {}
-
- try {
- fields.get("noValue", (byte) 0);
- fail("IllegalArgumentException expected for not existing name " +
- "argument in get(String, byte).");
- } catch (IllegalArgumentException e) {}
-
- try {
- fields.get("noValue", (char) 0);
- fail("IllegalArgumentException expected for not existing name " +
- "argument in get(String, char).");
- } catch (IllegalArgumentException e) {}
-
- try {
- fields.get("noValue", 0.0);
- fail("IllegalArgumentException expected for not existing name " +
- "argument in get(String, double).");
- } catch (IllegalArgumentException e) {}
-
- try {
- fields.get("noValue", 0.0f);
- fail("IllegalArgumentException expected for not existing name " +
- "argument in get(String, float).");
- } catch (IllegalArgumentException e) {}
-
- try {
- fields.get("noValue", (long) 0);
- fail("IllegalArgumentException expected for not existing name " +
- "argument in get(String, long).");
- } catch (IllegalArgumentException e) {}
-
- try {
- fields.get("noValue", 0);
- fail("IllegalArgumentException expected for not existing name " +
- "argument in get(String, int).");
- } catch (IllegalArgumentException e) {}
-
- try {
- fields.get("noValue", new Object());
- fail("IllegalArgumentException expected for not existing name " +
- "argument in get(String, Object).");
- } catch (IllegalArgumentException e) {}
-
- try {
- fields.get("noValue", (short) 0);
- fail("IllegalArgumentException expected for not existing name " +
- "argument in get(String, short).");
- } catch (IllegalArgumentException e) {}
-
- // Methods called with correct field name but non-matching type.
- try {
- fields.get("byteValue", false);
- fail("IllegalArgumentException expected for non-matching name " +
- "and type arguments in get(String, boolean).");
- } catch (IllegalArgumentException e) {}
-
- try {
- fields.get("booleanValue", (byte) 0);
- fail("IllegalArgumentException expected for non-matching name " +
- "and type arguments in get(String, byte).");
- } catch (IllegalArgumentException e) {}
-
- try {
- fields.get("intValue", (char) 0);
- fail("IllegalArgumentException expected for non-matching name " +
- "and type arguments in get(String, char).");
- } catch (IllegalArgumentException e) {}
-
- try {
- fields.get("floatValue", 0.0);
- fail("IllegalArgumentException expected for non-matching name " +
- "and type arguments in get(String, double).");
- } catch (IllegalArgumentException e) {}
-
- try {
- fields.get("doubleValue", 0.0f);
- fail("IllegalArgumentException expected for non-matching name " +
- "and type arguments in get(String, float).");
- } catch (IllegalArgumentException e) {}
-
- try {
- fields.get("intValue", (long) 0);
- fail("IllegalArgumentException expected for non-matching name " +
- "and type arguments in get(String, long).");
- } catch (IllegalArgumentException e) {}
-
- try {
- fields.get("shortValue", 0);
- fail("IllegalArgumentException expected for non-matching name " +
- "and type arguments in get(String, int).");
- } catch (IllegalArgumentException e) {}
-
- try {
- fields.get("booleanValue", new Object());
- fail("IllegalArgumentException expected for non-matching name " +
- "and type arguments in get(String, Object).");
- } catch (IllegalArgumentException e) {}
-
- try {
- fields.get("longValue", (short) 0);
- fail("IllegalArgumentException expected for non-matching name " +
- "and type arguments in get(String, short).");
- } catch (IllegalArgumentException e) {}
- }
-
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies that getObjectStreamClass() does not return null.",
- method = "getObjectStreamClass",
- args = {}
- )
- public void test_getObjectStreamClass() throws Exception {
-
- initOis(FILENAME);
- Support_GetPutFields object = (Support_GetPutFields) ois.readObject();
- assertNotNull("Return value of getObjectStreamClass() should not be null.",
- object.getField.getObjectStreamClass());
- }
-
-
- private void initOis(String fileName) throws Exception {
- if (ois != null) {
- ois.close();
- }
- ois = new ObjectInputStream(
- ClassLoader.getSystemResourceAsStream(fileName));
- }
-
- protected void tearDown() throws Exception {
-
- if (ois != null) {
- ois.close();
- }
- super.tearDown();
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/io/ObjectInputStreamTest.java b/luni/src/test/java/tests/api/java/io/ObjectInputStreamTest.java
deleted file mode 100644
index 2258507..0000000
--- a/luni/src/test/java/tests/api/java/io/ObjectInputStreamTest.java
+++ /dev/null
@@ -1,1497 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.EOFException;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.NotActiveException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.ObjectStreamClass;
-import java.io.OptionalDataException;
-import java.io.OutputStream;
-import java.io.Serializable;
-import java.io.StreamCorruptedException;
-import java.util.Arrays;
-import java.util.Hashtable;
-import java.util.Vector;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-import tests.support.Support_ASimpleInputStream;
-import tests.support.Support_IOTestSecurityManager;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-@TestTargetClass(ObjectInputStream.class)
-public class ObjectInputStreamTest extends junit.framework.TestCase implements
- Serializable {
-
- static final long serialVersionUID = 1L;
-
- ObjectInputStream ois;
-
- ObjectOutputStream oos;
-
- ByteArrayOutputStream bao;
-
- boolean readStreamHeaderCalled;
-
- private final String testString = "Lorem ipsum...";
-
- private final int testLength = testString.length();
-
- /**
- * @tests java.io.ObjectInputStream#ObjectInputStream()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies the protected ObjectInputStream() constructor.",
- method = "ObjectInputStream",
- args = {}
- )
- public void test_Constructor() throws IOException {
- SecurityManager sm = System.getSecurityManager();
- System.setSecurityManager(new Support_IOTestSecurityManager());
-
- try {
- ois = new BasicObjectInputStream();
- fail("SecurityException expected.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(sm);
- }
- }
-
- /**
- * @tests java.io.ObjectInputStream#ObjectInputStream(java.io.InputStream)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "ObjectInputStream",
- args = {java.io.InputStream.class}
- )
- public void test_ConstructorLjava_io_InputStream() throws IOException {
- // Test for method java.io.ObjectInputStream(java.io.InputStream)
- oos.writeDouble(Double.MAX_VALUE);
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- ois.close();
- oos.close();
-
- try {
- ois = new ObjectInputStream(new ByteArrayInputStream(new byte[90]));
- fail("StreamCorruptedException expected");
- } catch (StreamCorruptedException e) {}
- }
-
- /**
- * @tests java.io.ObjectInputStream#ObjectInputStream(java.io.InputStream)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks IOException.",
- method = "ObjectInputStream",
- args = {java.io.InputStream.class}
- )
- public void test_ConstructorLjava_io_InputStream_IOException() throws IOException {
- oos.writeObject(testString);
- oos.close();
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- sis.throwExceptionOnNextUse = true;
- try {
- ois = new ObjectInputStream(sis);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies that object can be serialized and deserialized correctly with reading descriptor from serialization stream.",
- method = "readClassDescriptor",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies that object can be serialized and deserialized correctly with reading descriptor from serialization stream.",
- method = "readObject",
- args = {}
- )
- })
- public void test_ClassDescriptor() throws IOException,
- ClassNotFoundException {
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStreamWithWriteDesc oos = new ObjectOutputStreamWithWriteDesc(
- baos);
- oos.writeObject(String.class);
- oos.close();
- Class<?> cls = TestClassForSerialization.class;
- ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
- ObjectInputStreamWithReadDesc ois = new ObjectInputStreamWithReadDesc(
- bais, cls);
- Object obj = ois.readObject();
- ois.close();
- assertEquals(cls, obj);
- }
-
- /**
- * @tests java.io.ObjectInputStream#available()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "available",
- args = {}
- )
- public void test_available() throws IOException {
- // Test for method int java.io.ObjectInputStream.available()
- oos.writeBytes(testString);
- oos.close();
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- ois = new ObjectInputStream(sis);
- assertEquals("Test 1: Incorrect number of bytes;", testLength, ois.available());
- ois.close();
- }
-
- /**
- * @tests java.io.ObjectInputStream#available()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks IOException.",
- method = "available",
- args = {}
- )
- public void test_available_IOException() throws IOException {
- oos.writeObject(testString);
- oos.close();
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- ois = new ObjectInputStream(sis);
- sis.throwExceptionOnNextUse = true;
- try {
- ois.available();
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- ois.close();
- }
-
- /**
- * @tests java.io.ObjectInputStream#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "close",
- args = {}
- )
- public void test_close() throws Exception {
- // Test for method void java.io.ObjectInputStream.close()
- oos.writeObject(testString);
- oos.close();
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- ois = new ObjectInputStream(sis);
- sis.throwExceptionOnNextUse = true;
- try {
- ois.close();
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- ois.close();
- }
-
- /**
- * @tests java.io.ObjectInputStream#defaultReadObject()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "defaultReadObject",
- args = {}
- )
- public void test_defaultReadObject() throws Exception {
- // Test for method void java.io.ObjectInputStream.defaultReadObject()
- // SM. This method may as well be private, as if called directly it
- // throws an exception.
- String s = testString;
- oos.writeObject(s);
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- try {
- ois.defaultReadObject();
- fail("NotActiveException expected");
- } catch (NotActiveException e) {
- // Desired behavior
- } finally {
- ois.close();
- }
- }
-
- /**
- * @tests java.io.ObjectInputStream#enableResolveObject(boolean)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies enableResolveObject(boolean).",
- method = "enableResolveObject",
- args = {boolean.class}
- )
- public void test_enableResolveObjectB() throws IOException {
- // Start testing without a SecurityManager.
- BasicObjectInputStream bois = new BasicObjectInputStream();
- assertFalse("Test 1: Object resolving must be disabled by default.",
- bois.enableResolveObject(true));
-
- assertTrue("Test 2: enableResolveObject did not return the previous value.",
- bois.enableResolveObject(false));
- }
-
- /**
- * @tests java.io.ObjectInputStream#read()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "read",
- args = {}
- )
- public void test_read() throws IOException {
- // Test for method int java.io.ObjectInputStream.read()
- oos.write('T');
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- assertEquals("Read incorrect byte value", 'T', ois.read());
- ois.close();
- }
-
- /**
- * @tests java.io.ObjectInputStream#read()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks IOException.",
- method = "read",
- args = {}
- )
- public void test_read_IOException() throws IOException {
- oos.writeObject(testString);
- oos.close();
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- ois = new ObjectInputStream(sis);
- sis.throwExceptionOnNextUse = true;
- try {
- ois.read();
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- ois.close();
- }
-
- /**
- * @tests java.io.ObjectInputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII() throws IOException {
- // Test for method int java.io.ObjectInputStream.read(byte [], int, int)
- byte[] buf = new byte[testLength];
- oos.writeBytes(testString);
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- ois.read(buf, 0, testLength);
- ois.close();
- assertEquals("Read incorrect bytes", testString, new String(buf));
- }
-
- /**
- * @tests java.io.ObjectInputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks Exceptions.",
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII_Exception() throws IOException {
- byte[] buf = new byte[testLength];
- oos.writeObject(testString);
- oos.close();
-
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- try {
- ois.read(buf, 0, -1);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- ois.read(buf, -1,1);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- ois.read(buf, testLength, 1);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- ois.close();
-
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- ois = new ObjectInputStream(sis);
- sis.throwExceptionOnNextUse = true;
- try {
- ois.read(buf, 0, testLength);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- ois.close();
- }
-
- /**
- * @tests java.io.ObjectInputStream#readFields()
- * @tests java.io.ObjectOutputStream#writeFields()
- */
- @TestTargets({
- @TestTargetNew(
- method = "readFields",
- args = {},
- level = TestLevel.COMPLETE
- ),
- @TestTargetNew(
- method = "writeFields",
- args = {},
- clazz = ObjectOutputStream.class,
- level = TestLevel.COMPLETE
- )
- })
- public void test_readFields() throws Exception {
- // Test for method java.io.ObjectInputStream$GetField
- // java.io.ObjectInputStream.readFields()
-
- SerializableTestHelper sth;
-
- /*
- * "SerializableTestHelper" is an object created for these tests with
- * two fields (Strings) and simple implementations of readObject and
- * writeObject which simply read and write the first field but not the
- * second
- */
-
- oos.writeObject(new SerializableTestHelper("Gabba", "Jabba"));
- oos.flush();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- sth = (SerializableTestHelper) (ois.readObject());
- assertEquals("readFields / writeFields failed--first field not set",
- "Gabba", sth.getText1());
- assertNull(
- "readFields / writeFields failed--second field should not have been set",
- sth.getText2());
- }
-
- /**
- * @tests java.io.ObjectInputStream#readFully(byte[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "readFully",
- args = {byte[].class}
- )
- public void test_readFully$B() throws IOException {
- byte[] buf = new byte[testLength];
- oos.writeBytes(testString);
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- ois.readFully(buf);
- assertEquals("Test 1: Incorrect bytes read;",
- testString, new String(buf));
- ois.close();
-
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- ois.read();
- try {
- ois.readFully(buf);
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ObjectInputStream#readFully(byte[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks IOException.",
- method = "readFully",
- args = {byte[].class}
- )
- public void test_readFully$B_Exception() throws IOException {
- byte[] buf = new byte[testLength];
- oos.writeObject(testString);
- oos.close();
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- ois = new ObjectInputStream(sis);
- sis.throwExceptionOnNextUse = true;
- try {
- ois.readFully(buf);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- ois.close();
- }
-
- /**
- * @tests java.io.ObjectInputStream#readFully(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "readFully",
- args = {byte[].class, int.class, int.class}
- )
- public void test_readFully$BII() throws IOException {
- // Test for method void java.io.ObjectInputStream.readFully(byte [],
- // int, int)
- byte[] buf = new byte[testLength];
- oos.writeBytes(testString);
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- ois.readFully(buf, 0, testLength);
- assertEquals("Read incorrect bytes", testString, new String(buf));
- ois.close();
-
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- ois.read();
- try {
- ois.readFully(buf);
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ObjectInputStream#readFully(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks Exceptions.",
- method = "readFully",
- args = {byte[].class, int.class, int.class}
- )
- public void test_readFully$BII_Exception() throws IOException {
- byte[] buf = new byte[testLength];
- oos.writeObject(testString);
- oos.close();
-
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- try {
- ois.readFully(buf, 0, -1);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- ois.readFully(buf, -1,1);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- ois.readFully(buf, testLength, 1);
- fail("IndexOutOfBoundsException was not thrown.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- ois.close();
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- ois = new ObjectInputStream(sis);
- sis.throwExceptionOnNextUse = true;
- try {
- ois.readFully(buf, 0, 1);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- ois.close();
- }
-
- /**
- * @tests java.io.ObjectInputStream#readLine()
- */
- @SuppressWarnings("deprecation")
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "readLine",
- args = {}
- )
- public void test_readLine() throws IOException {
- String line;
- oos.writeBytes("Lorem\nipsum\rdolor sit amet...");
- oos.close();
-
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- line = ois.readLine();
- assertTrue("Test 1: Incorrect line written or read: " + line,
- line.equals("Lorem"));
- line = ois.readLine();
- assertTrue("Test 2: Incorrect line written or read: " + line,
- line.equals("ipsum"));
- line = ois.readLine();
- assertTrue("Test 3: Incorrect line written or read: " + line,
- line.equals("dolor sit amet..."));
- ois.close();
- }
-
- /**
- * @tests java.io.ObjectInputStream#readLine()
- */
- @SuppressWarnings("deprecation")
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks IOException.",
- method = "readLine",
- args = {}
- )
- public void test_readLine_IOException() throws IOException {
- oos.writeObject(testString);
- oos.close();
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- ois = new ObjectInputStream(sis);
- sis.throwExceptionOnNextUse = true;
- try {
- ois.readLine();
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- ois.close();
- }
-
- /**
- * @tests java.io.ObjectInputStream#readObject()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "readObject",
- args = {}
- )
- public void test_readObject() throws Exception {
- // Test for method java.lang.Object
- // java.io.ObjectInputStream.readObject()
- String s = testString;
- oos.writeObject(s);
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- assertEquals("Read incorrect Object value", s, ois.readObject());
- ois.close();
-
- // Regression for HARMONY-91
- // dynamically create serialization byte array for the next hierarchy:
- // - class A implements Serializable
- // - class C extends A
-
- byte[] cName = C.class.getName().getBytes();
- byte[] aName = A.class.getName().getBytes();
-
- ByteArrayOutputStream out = new ByteArrayOutputStream();
-
- byte[] begStream = new byte[] { (byte) 0xac, (byte) 0xed, // STREAM_MAGIC
- (byte) 0x00, (byte) 0x05, // STREAM_VERSION
- (byte) 0x73, // TC_OBJECT
- (byte) 0x72, // TC_CLASSDESC
- (byte) 0x00, // only first byte for C class name length
- };
-
- out.write(begStream, 0, begStream.length);
- out.write(cName.length); // second byte for C class name length
- out.write(cName, 0, cName.length); // C class name
-
- byte[] midStream = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00,
- (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
- (byte) 0x21, // serialVersionUID = 33L
- (byte) 0x02, // flags
- (byte) 0x00, (byte) 0x00, // fields : none
- (byte) 0x78, // TC_ENDBLOCKDATA
- (byte) 0x72, // Super class for C: TC_CLASSDESC for A class
- (byte) 0x00, // only first byte for A class name length
- };
-
- out.write(midStream, 0, midStream.length);
- out.write(aName.length); // second byte for A class name length
- out.write(aName, 0, aName.length); // A class name
-
- byte[] endStream = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00,
- (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
- (byte) 0x0b, // serialVersionUID = 11L
- (byte) 0x02, // flags
- (byte) 0x00, (byte) 0x01, // fields
-
- (byte) 0x4c, // field description: type L (object)
- (byte) 0x00, (byte) 0x04, // length
- // field = 'name'
- (byte) 0x6e, (byte) 0x61, (byte) 0x6d, (byte) 0x65,
-
- (byte) 0x74, // className1: TC_STRING
- (byte) 0x00, (byte) 0x12, // length
- //
- (byte) 0x4c, (byte) 0x6a, (byte) 0x61, (byte) 0x76,
- (byte) 0x61, (byte) 0x2f, (byte) 0x6c, (byte) 0x61,
- (byte) 0x6e, (byte) 0x67, (byte) 0x2f, (byte) 0x53,
- (byte) 0x74, (byte) 0x72, (byte) 0x69, (byte) 0x6e,
- (byte) 0x67, (byte) 0x3b,
-
- (byte) 0x78, // TC_ENDBLOCKDATA
- (byte) 0x70, // NULL super class for A class
-
- // classdata
- (byte) 0x74, // TC_STRING
- (byte) 0x00, (byte) 0x04, // length
- (byte) 0x6e, (byte) 0x61, (byte) 0x6d, (byte) 0x65, // value
- };
-
- out.write(endStream, 0, endStream.length);
- out.flush();
-
- // read created serial. form
- ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
- out.toByteArray()));
- Object o = ois.readObject();
- assertEquals(C.class, o.getClass());
-
- // Regression for HARMONY-846
- assertNull(new ObjectInputStream() {}.readObject());
- }
-
- private void fillStreamHeader(byte[] buffer) {
- short magic = java.io.ObjectStreamConstants.STREAM_MAGIC;
- short version = java.io.ObjectStreamConstants.STREAM_VERSION;
-
- if (buffer.length < 4) {
- throw new IllegalArgumentException("The buffer's minimal length must be 4.");
- }
-
- // Initialize the buffer with the correct header for object streams
- buffer[0] = (byte) (magic >> 8);
- buffer[1] = (byte) magic;
- buffer[2] = (byte) (version >> 8);
- buffer[3] = (byte) (version);
- }
-
- /**
- * @tests java.io.ObjectInputStream#readObjectOverride()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies readObjectOverride().",
- method = "readObjectOverride",
- args = {}
- )
- public void test_readObjectOverride() throws Exception {
- byte[] buffer = new byte[4];
-
- // Initialize the buffer with the correct header for object streams
- fillStreamHeader(buffer);
-
- // Test 1: Check that readObjectOverride() returns null if there
- // is no input stream.
- BasicObjectInputStream bois = new BasicObjectInputStream();
- assertNull("Test 1:", bois.readObjectOverride());
-
- // Test 2: Check that readObjectOverride() throws an IOException
- // if there is an input stream.
- bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer));
- try {
- bois.readObjectOverride();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {}
-
- bois.close();
- }
-
- /**
- * @tests java.io.ObjectInputStream#readObject()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "readObject",
- args = {}
- )
- public void test_readObjectMissingClasses() throws Exception {
- SerializationTest.verifySelf(new A1(), new SerializableAssert() {
- public void assertDeserialized(Serializable initial,
- Serializable deserialized) {
- assertEquals(5, ((A1) deserialized).b1.i);
- }
- });
- }
-
- /**
- * @tests java.io.ObjectInputStream#readObject()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "readObject",
- args = {}
- )
- public void test_readObjectCorrupt() {
- byte[] bytes = { 00, 00, 00, 0x64, 0x43, 0x48, (byte) 0xFD, 0x71, 00,
- 00, 0x0B, (byte) 0xB8, 0x4D, 0x65 };
- ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
- boolean exception = false;
- try {
- ObjectInputStream in = new ObjectInputStream(bin);
- in.readObject();
- fail("Unexpected read of corrupted stream");
- } catch (StreamCorruptedException e) {
- exception = true;
- } catch (IOException e) {
- fail("Unexpected: " + e);
- } catch (ClassNotFoundException e) {
- fail("Unexpected: " + e);
- }
- assertTrue("Expected StreamCorruptedException", exception);
- }
-
- /**
- * @tests java.io.ObjectInputStream#readStreamHeader()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies readStreamHeader().",
- method = "readStreamHeader",
- args = {}
- )
- public void test_readStreamHeader() throws IOException {
- String testString = "Lorem ipsum";
- BasicObjectInputStream bois;
- short magic = java.io.ObjectStreamConstants.STREAM_MAGIC;
- short version = java.io.ObjectStreamConstants.STREAM_VERSION;
- byte[] buffer = new byte[20];
-
- // Initialize the buffer with the correct header for object streams
- fillStreamHeader(buffer);
- System.arraycopy(testString.getBytes(), 0, buffer, 4, testString.length());
-
- // Test 1: readStreamHeader should not throw a StreamCorruptedException.
- // It should get called by the ObjectInputStream constructor.
- try {
- readStreamHeaderCalled = false;
- bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer));
- bois.close();
- } catch (StreamCorruptedException e) {
- fail("Test 1: Unexpected StreamCorruptedException.");
- }
- assertTrue("Test 1: readStreamHeader() has not been called.",
- readStreamHeaderCalled);
-
- // Test 2: Make the stream magic number invalid and check that
- // readStreamHeader() throws an exception.
- buffer[0] = (byte)magic;
- buffer[1] = (byte)(magic >> 8);
- try {
- readStreamHeaderCalled = false;
- bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer));
- fail("Test 2: StreamCorruptedException expected.");
- bois.close();
- } catch (StreamCorruptedException e) {
- }
- assertTrue("Test 2: readStreamHeader() has not been called.",
- readStreamHeaderCalled);
-
- // Test 3: Make the stream version invalid and check that
- // readStreamHeader() throws an exception.
- buffer[0] = (byte)(magic >> 8);
- buffer[1] = (byte)magic;
- buffer[2] = (byte)(version);
- buffer[3] = (byte)(version >> 8);
- try {
- readStreamHeaderCalled = false;
- bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer));
- fail("Test 3: StreamCorruptedException expected.");
- bois.close();
- } catch (StreamCorruptedException e) {
- }
- assertTrue("Test 3: readStreamHeader() has not been called.",
- readStreamHeaderCalled);
- }
-
- /**
- * @tests java.io.ObjectInputStream#readUnsignedByte()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "readUnsignedByte",
- args = {}
- )
- public void test_readUnsignedByte() throws IOException {
- oos.writeByte(-1);
- oos.close();
-
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- assertEquals("Test 1: Incorrect unsigned byte written or read.",
- 255, ois.readUnsignedByte());
-
- try {
- ois.readUnsignedByte();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- ois.close();
- try {
- ois.readUnsignedByte();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ObjectInputStream#readUnsignedShort()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "readUnsignedShort",
- args = {}
- )
- public void test_readUnsignedShort() throws IOException {
- // Test for method int java.io.ObjectInputStream.readUnsignedShort()
- oos.writeShort(-1);
- oos.close();
-
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- assertEquals("Test 1: Incorrect unsigned short written or read.",
- 65535, ois.readUnsignedShort());
-
- try {
- ois.readUnsignedShort();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- ois.close();
- try {
- ois.readUnsignedShort();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ObjectInputStream#resolveProxyClass(String[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies resolveProxyClass(String[]).",
- method = "resolveProxyClass",
- args = {java.lang.String[].class}
- )
- public void test_resolveProxyClass() throws IOException {
- BasicObjectInputStream bois;
- byte[] buffer = new byte[10];
-
- // Initialize the buffer with the header for object streams
- fillStreamHeader(buffer);
- bois = new BasicObjectInputStream(new ByteArrayInputStream(buffer));
-
- // Test 1: Check that a NullPointerException is thrown
- // if null is passed to the method.
- try {
- bois.resolveProxyClass(null);
- fail("Test 1: NullPointerException expected.");
- }
- catch (NullPointerException npe) {
- }
- catch (ClassNotFoundException cnfe) {
- fail("Test 1: Unexpected ClassNotFoundException.");
- }
-
- // Test 2: Check that visible interfaces are found.
- try {
- String[] interfaces = { "java.io.Closeable",
- "java.lang.Cloneable" };
- bois.resolveProxyClass(interfaces);
- }
- catch (ClassNotFoundException cnfe) {
- fail("Test 2: Unexpected ClassNotFoundException.");
- }
-
- // Test 3: Check that a ClassNotFoundException is thrown if the
- // array of interfaces is not valid.
- try {
- String[] interfaces = { "java.io.Closeable",
- "java.io.Closeable" };
- bois.resolveProxyClass(interfaces);
- fail ("Test 3: ClassNotFoundException expected.");
- }
- catch (ClassNotFoundException cnfe) {
- }
-
- bois.close();
- }
-
- /**
- * @tests java.io.ObjectInputStream#skipBytes(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "skipBytes",
- args = {int.class}
- )
- public void test_skipBytesI() throws IOException {
- // Test for method int java.io.ObjectInputStream.skipBytes(int)
- byte[] buf = new byte[testLength];
- oos.writeBytes(testString);
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- ois.skipBytes(5);
- ois.read(buf, 0, 5);
- ois.close();
- assertEquals("Skipped incorrect bytes", testString.substring(5, 10),
- new String(buf, 0, 5));
-
- // Regression for HARMONY-844
- try {
- new ObjectInputStream() {}.skipBytes(0);
- fail("NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ObjectInputStream#skipBytes(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks IOException.",
- method = "skipBytes",
- args = {int.class}
- )
- public void test_skipBytesI_IOException() throws IOException {
- oos.writeObject(testString);
- oos.close();
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream(bao.toByteArray());
- ois = new ObjectInputStream(sis);
- sis.throwExceptionOnNextUse = true;
- try {
- ois.skipBytes(5);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sis.throwExceptionOnNextUse = false;
- ois.close();
- }
-
- // Regression Test for JIRA 2192
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "readObject",
- args = {}
- )
- public void test_readObject_withPrimitiveClass() throws Exception {
- // Make sure that system properties are set correctly
- String dir = System.getProperty("java.io.tmpdir");
- if (dir == null)
- throw new Exception("System property java.io.tmpdir not defined.");
- File file = new File(dir, "test.ser");
- file.deleteOnExit();
- Test test = new Test();
- ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
- file));
- out.writeObject(test);
- out.close();
-
- ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
- Test another = (Test) in.readObject();
- in.close();
- assertEquals(test, another);
- }
-
- public static class A implements Serializable {
-
- private static final long serialVersionUID = 11L;
-
- public String name = "name";
- }
-
- public static class B extends A {}
-
- public static class C extends B {
-
- private static final long serialVersionUID = 33L;
- }
-
- public static class A1 implements Serializable {
-
- static final long serialVersionUID = 5942584913446079661L;
-
- B1 b1 = new B1();
-
- B1 b2 = b1;
-
- Vector v = new Vector();
- }
-
- public static class B1 implements Serializable {
-
- int i = 5;
-
- Hashtable h = new Hashtable();
- }
-
- public class SerializableTestHelper implements Serializable {
-
- public String aField1;
-
- public String aField2;
-
- SerializableTestHelper() {
- aField1 = null;
- aField2 = null;
- }
-
- SerializableTestHelper(String s, String t) {
- aField1 = s;
- aField2 = t;
- }
-
- private void readObject(ObjectInputStream ois) throws Exception {
- // note aField2 is not read
- ObjectInputStream.GetField fields = ois.readFields();
- aField1 = (String) fields.get("aField1", "Zap");
- }
-
- private void writeObject(ObjectOutputStream oos) throws IOException {
- // note aField2 is not written
- ObjectOutputStream.PutField fields = oos.putFields();
- fields.put("aField1", aField1);
- oos.writeFields();
- }
-
- public String getText1() {
- return aField1;
- }
-
- public void setText1(String s) {
- aField1 = s;
- }
-
- public String getText2() {
- return aField2;
- }
-
- public void setText2(String s) {
- aField2 = s;
- }
- }
-
-
- class BasicObjectInputStream extends ObjectInputStream {
- public BasicObjectInputStream() throws IOException, SecurityException {
- super();
- }
-
- public BasicObjectInputStream(InputStream input)
- throws StreamCorruptedException, IOException {
- super(input);
- }
-
- public boolean enableResolveObject(boolean enable)
- throws SecurityException {
- return super.enableResolveObject(enable);
- }
-
- public Object readObjectOverride() throws OptionalDataException,
- ClassNotFoundException, IOException {
- return super.readObjectOverride();
- }
-
- public void readStreamHeader() throws IOException,
- StreamCorruptedException {
- readStreamHeaderCalled = true;
- super.readStreamHeader();
- }
-
- public Class<?> resolveProxyClass(String[] interfaceNames)
- throws IOException, ClassNotFoundException {
- return super.resolveProxyClass(interfaceNames);
- }
- }
-
- //Regression Test for JIRA-2249
- public static class ObjectOutputStreamWithWriteDesc extends
- ObjectOutputStream {
- public ObjectOutputStreamWithWriteDesc(OutputStream os)
- throws IOException {
- super(os);
- }
-
- public void writeClassDescriptor(ObjectStreamClass desc)
- throws IOException {
- }
- }
-
- public static class ObjectInputStreamWithReadDesc extends
- ObjectInputStream {
- private Class returnClass;
-
- public ObjectInputStreamWithReadDesc(InputStream is, Class returnClass)
- throws IOException {
- super(is);
- this.returnClass = returnClass;
- }
-
- public ObjectStreamClass readClassDescriptor() throws IOException,
- ClassNotFoundException {
- return ObjectStreamClass.lookup(returnClass);
-
- }
- }
-
- static class TestClassForSerialization implements Serializable {
- private static final long serialVersionUID = 1L;
- }
-
-
- // Regression Test for JIRA-2340
- public static class ObjectOutputStreamWithWriteDesc1 extends
- ObjectOutputStream {
- public ObjectOutputStreamWithWriteDesc1(OutputStream os)
- throws IOException {
- super(os);
- }
-
- public void writeClassDescriptor(ObjectStreamClass desc)
- throws IOException {
- super.writeClassDescriptor(desc);
- }
- }
-
- public static class ObjectInputStreamWithReadDesc1 extends
- ObjectInputStream {
-
- public ObjectInputStreamWithReadDesc1(InputStream is)
- throws IOException {
- super(is);
- }
-
- public ObjectStreamClass readClassDescriptor() throws IOException,
- ClassNotFoundException {
- return super.readClassDescriptor();
- }
- }
-
- // Regression test for Harmony-1921
- public static class ObjectInputStreamWithResolve extends ObjectInputStream {
- public ObjectInputStreamWithResolve(InputStream in) throws IOException {
- super(in);
- }
-
- protected Class<?> resolveClass(ObjectStreamClass desc)
- throws IOException, ClassNotFoundException {
- if (desc.getName().equals(
- "org.apache.harmony.luni.tests.pkg1.TestClass")) {
- return org.apache.harmony.luni.tests.pkg2.TestClass.class;
- }
- return super.resolveClass(desc);
- }
- }
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "No IOException testing since this seems not to be thrown.",
- method = "resolveClass",
- args = {java.io.ObjectStreamClass.class}
- )
- public void test_resolveClass() throws Exception {
- org.apache.harmony.luni.tests.pkg1.TestClass to1 = new org.apache.harmony.luni.tests.pkg1.TestClass();
- to1.i = 555;
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStream oos = new ObjectOutputStream(baos);
- oos.writeObject(to1);
- oos.flush();
- byte[] bytes = baos.toByteArray();
- ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
- ObjectInputStream ois = new ObjectInputStreamWithResolve(bais);
- org.apache.harmony.luni.tests.pkg2.TestClass to2 = (org.apache.harmony.luni.tests.pkg2.TestClass) ois
- .readObject();
-
- if (to2.i != to1.i) {
- fail("Wrong object read. Expected val: " + to1.i + ", got: " + to2.i);
- }
- }
-
- static class ObjectInputStreamWithResolveObject extends ObjectInputStream {
-
- public static Integer intObj = Integer.valueOf(1000);
-
- public ObjectInputStreamWithResolveObject(InputStream in) throws IOException {
- super(in);
- enableResolveObject(true);
- }
-
- protected Object resolveObject(Object obj) throws IOException {
- if(obj instanceof Integer){
- obj = intObj;
- }
- return super.resolveObject(obj);
- }
- }
-
- /**
- * @tests java.io.ObjectInputStream#resolveObject(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "resolveObject",
- args = {java.lang.Object.class}
- )
- public void test_resolveObjectLjava_lang_Object() throws Exception {
- // Write an Integer object into memory
- Integer original = new Integer(10);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStream oos = new ObjectOutputStream(baos);
- oos.writeObject(original);
- oos.flush();
- oos.close();
-
- // Read the object from memory
- byte[] bytes = baos.toByteArray();
- ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
- ObjectInputStreamWithResolveObject ois =
- new ObjectInputStreamWithResolveObject(bais);
- Integer actual = (Integer) ois.readObject();
- ois.close();
-
- // object should be resolved from 10 to 1000
- assertEquals(ObjectInputStreamWithResolveObject.intObj, actual);
- }
-
- /**
- * @tests java.io.ObjectInputStream#readClassDescriptor()
- * @tests java.io.ObjectOutputStream#writeClassDescriptor(ObjectStreamClass)
- */
- @TestTargets(
- {
- @TestTargetNew(
- method = "readClassDescriptor",
- args = {},
- level = TestLevel.PARTIAL_COMPLETE
- ),
- @TestTargetNew(
- method = "writeClassDescriptor",
- args = {ObjectStreamClass.class},
- clazz = ObjectOutputStream.class,
- level = TestLevel.COMPLETE
- )
- }
- )
- public void test_readClassDescriptor() throws IOException,
- ClassNotFoundException {
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStreamWithWriteDesc1 oos = new ObjectOutputStreamWithWriteDesc1(
- baos);
- ObjectStreamClass desc = ObjectStreamClass
- .lookup(TestClassForSerialization.class);
- oos.writeClassDescriptor(desc);
- oos.close();
-
- byte[] bytes = baos.toByteArray();
- ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
- ObjectInputStreamWithReadDesc1 ois = new ObjectInputStreamWithReadDesc1(
- bais);
- Object obj = ois.readClassDescriptor();
- ois.close();
- assertEquals(desc.getClass(), obj.getClass());
-
- //eof
- bais = new ByteArrayInputStream(bytes);
- ExceptionalBufferedInputStream bis = new ExceptionalBufferedInputStream(
- bais);
- ois = new ObjectInputStreamWithReadDesc1(bis);
-
- bis.setEOF(true);
-
- try {
- obj = ois.readClassDescriptor();
- } catch (IOException e) {
- //e.printStackTrace();
- } finally {
- ois.close();
- }
-
- //throw exception
- bais = new ByteArrayInputStream(bytes);
- bis = new ExceptionalBufferedInputStream(bais);
- ois = new ObjectInputStreamWithReadDesc1(bis);
-
- bis.setException(new IOException());
-
- try {
- obj = ois.readClassDescriptor();
- } catch (IOException e) {
- //e.printStackTrace();
- } finally {
- ois.close();
- }
-
- //corrupt
- bais = new ByteArrayInputStream(bytes);
- bis = new ExceptionalBufferedInputStream(bais);
- ois = new ObjectInputStreamWithReadDesc1(bis);
-
- bis.setCorrupt(true);
-
- try {
- obj = ois.readClassDescriptor();
- } catch (IOException e) {
- //e.printStackTrace();
- } finally {
- ois.close();
- }
-
- }
-
- static class ExceptionalBufferedInputStream extends BufferedInputStream {
- private boolean eof = false;
- private IOException exception = null;
- private boolean corrupt = false;
-
- public ExceptionalBufferedInputStream(InputStream in) {
- super(in);
- }
-
- public int read() throws IOException {
- if (exception != null) {
- throw exception;
- }
-
- if (eof) {
- return -1;
- }
-
- if (corrupt) {
- return 0;
- }
- return super.read();
- }
-
- public void setEOF(boolean eof) {
- this.eof = eof;
- }
-
- public void setException(IOException exception) {
- this.exception = exception;
- }
-
- public void setCorrupt(boolean corrupt) {
- this.corrupt = corrupt;
- }
- }
-
- // Regression Test for Harmony-2402
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "registerValidation",
- args = {java.io.ObjectInputValidation.class, int.class}
- )
- public void test_registerValidation() throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- new ObjectOutputStream(baos);
- ObjectInputStream ois = new ObjectInputStream(
- new ByteArrayInputStream(baos.toByteArray()));
-
- try {
- ois.registerValidation(null, 256);
- fail("NotActiveException should be thrown");
- } catch (NotActiveException nae) {
- // expected
- }
- }
-
- protected void setUp() throws Exception {
- super.setUp();
- oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
- }
-}
-
-
-class Test implements Serializable {
- private static final long serialVersionUID = 1L;
-
- Class<?> classes[] = new Class[] { byte.class, short.class, int.class,
- long.class, boolean.class, char.class, float.class, double.class };
-
- public boolean equals(Object o) {
- if (!(o instanceof Test)) {
- return false;
- }
- return Arrays.equals(classes, ((Test) o).classes);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/ObjectInputValidationTest.java b/luni/src/test/java/tests/api/java/io/ObjectInputValidationTest.java
deleted file mode 100644
index ebab187..0000000
--- a/luni/src/test/java/tests/api/java/io/ObjectInputValidationTest.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package tests.api.java.io;
-
-import junit.framework.TestCase;
-
-import java.io.ObjectInputValidation;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(
- value = ObjectInputValidation.class,
- untestedMethods = {
- @TestTargetNew(
- method = "validateObject",
- level = TestLevel.NOT_FEASIBLE,
- notes = "There are no classes in the current core " +
- "libraries that implement this method."
- )
- }
-)
-public class ObjectInputValidationTest extends TestCase {
-
-}
diff --git a/luni/src/test/java/tests/api/java/io/ObjectOutputStreamPutFieldTest.java b/luni/src/test/java/tests/api/java/io/ObjectOutputStreamPutFieldTest.java
deleted file mode 100644
index 05da8c3..0000000
--- a/luni/src/test/java/tests/api/java/io/ObjectOutputStreamPutFieldTest.java
+++ /dev/null
@@ -1,209 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
-import java.util.Arrays;
-
-import tests.support.Support_GetPutFields;
-import tests.support.Support_GetPutFieldsDeprecated;
-
-/**
- * Tests the methods of {@code ObjectOutputStream.PutField}. Three things make
- * this class somewhat difficult to test:
- * <ol>
- * <li>It is a completely abstract class; none of the methods is implemented in
- * {@code ObjectOutputStream.PutField}.</li>
- * <li>There is no public class that implements
- * {@code ObjectOutputStream.PutField}. The only way to get an implementation
- * is by calling {@code ObjectOutputStream.putFields()}.</li>
- * <li>Invoking the methods of {@code ObjectOutputStream.PutField} only works
- * from within the private {@code writeObject(ObjectOutputStream)} method of a
- * class that implements {@code Serializable}; an exception is thrown
- * otherwise.</li>
- * </ol>
- * <p>
- * Given these restrictions, an indirect approach is used to test
- * {@code ObjectOutputStream.PutField}: The serializable helper class
- * {@code tests.support.Support_GetPutFields} implements
- * {@code writeObject(ObjectOutputStream)} and uses all {@code putX} methods in
- * {@code PutField} to write data to the output stream. A second helper class,
- * {@code tests.support.Support_GetPutFieldsDeprecated}, also uses the
- * deprecated {@code ObjectOutputStream.PutField.write(ObjectOutput)}.
- * {@code tests.util.FieldTestFileGenerator} can then be used on a reference
- * platform to write these two classes to the file {@code testFields.ser} and
- * {@code testFieldsDeprecated.ser} respectively.
- * </p>
- * <p>
- * The test methods in this class expect to find {@code testFields.ser} and
- * {@code testFieldsDeprecated.ser} as a resource stored at
- * {@code tests/api/java/io}. The contents of these files is compared to what
- * is written when {@code Support_GetPutFields.writeObject(ObjectOutputStream)}
- * and {@code Support_GetPutFieldsDeprecated.writeObject(ObjectOutputStream)} is
- * called by the test methods.
- * </p>
- */
-@TestTargetClass(ObjectOutputStream.PutField.class)
-public class ObjectOutputStreamPutFieldTest extends junit.framework.TestCase {
-
- private final String FILENAME =
- "tests/api/java/io/testFields.ser";
- private final String DEPRECATED_FILENAME =
- "tests/api/java/io/testFieldsDeprecated.ser";
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies that content is written correctly to a stream.",
- method = "put",
- args = {java.lang.String.class, boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies that content is written correctly to a stream.",
- method = "put",
- args = {java.lang.String.class, byte.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies that content is written correctly to a stream.",
- method = "put",
- args = {java.lang.String.class, char.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies that content is written correctly to a stream.",
- method = "put",
- args = {java.lang.String.class, double.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies that content is written correctly to a stream.",
- method = "put",
- args = {java.lang.String.class, float.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies that content is written correctly to a stream.",
- method = "put",
- args = {java.lang.String.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies that content is written correctly to a stream.",
- method = "put",
- args = {java.lang.String.class, long.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies that content is written correctly to a stream.",
- method = "put",
- args = {java.lang.String.class, java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies that content is written correctly to a stream.",
- method = "put",
- args = {java.lang.String.class, short.class}
- )
- })
- public void test_put() throws Exception {
- Support_GetPutFields toSerialize = new Support_GetPutFields();
- byte[] content;
- byte[] refContent;
- ObjectOutputStream oos = null;
- ByteArrayOutputStream baos;
-
- toSerialize.initTestValues();
-
- try {
- refContent = getRefContent(FILENAME);
-
- baos = new ByteArrayOutputStream(refContent.length);
- oos = new ObjectOutputStream(baos);
-
- oos.writeObject(toSerialize);
- content = baos.toByteArray();
- assertTrue("Serialization is not equal to reference platform.",
- Arrays.equals(content, refContent));
- }
- finally {
- if (oos != null) oos.close();
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies the deprecated write(ObjectOutput) method.",
- method = "write",
- args = {java.io.ObjectOutput.class}
- )
- public void test_writeLjava_io_ObjectOutputStream() throws Exception {
- Support_GetPutFieldsDeprecated toSerialize = new Support_GetPutFieldsDeprecated();
- byte[] content;
- byte[] refContent;
- ObjectOutputStream oos = null;
- ByteArrayOutputStream baos;
-
- toSerialize.initTestValues();
-
- try {
- refContent = getRefContent(DEPRECATED_FILENAME);
-
- baos = new ByteArrayOutputStream(refContent.length);
- oos = new ObjectOutputStream(baos);
-
- oos.writeObject(toSerialize);
- content = baos.toByteArray();
- assertTrue("Serialization is not equal to reference platform.",
- Arrays.equals(content, refContent));
- }
- finally {
- if (oos != null) oos.close();
- }
- }
-
- private byte[] getRefContent(String path) throws Exception {
- int bytesRead;
- byte[] refContent;
- byte[] streamContent = new byte[2000];
- InputStream refStream = null;
-
- try {
- refStream = ClassLoader.getSystemResourceAsStream(path);
- bytesRead = refStream.read(streamContent);
- assertTrue("Test case implementation error: The byte array to " +
- "store the reference file is too small.",
- (refStream.read() == -1));
- refContent = new byte[bytesRead];
- System.arraycopy(streamContent, 0, refContent, 0, bytesRead);
- }
- finally {
- if (refStream != null) refStream.close();
- }
- return refContent;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/ObjectOutputStreamTest.java b/luni/src/test/java/tests/api/java/io/ObjectOutputStreamTest.java
deleted file mode 100644
index e8042ca..0000000
--- a/luni/src/test/java/tests/api/java/io/ObjectOutputStreamTest.java
+++ /dev/null
@@ -1,1626 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.Externalizable;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.NotActiveException;
-import java.io.NotSerializableException;
-import java.io.ObjectInput;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
-import java.io.ObjectStreamClass;
-import java.io.ObjectStreamException;
-import java.io.ObjectStreamField;
-import java.io.OutputStream;
-import java.io.Serializable;
-import java.io.SerializablePermission;
-import java.io.WriteAbortedException;
-import java.security.Permission;
-import java.util.Arrays;
-
-import tests.support.Support_ASimpleOutputStream;
-import tests.support.Support_IOTestSecurityManager;
-import tests.support.Support_OutputStream;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-@TestTargetClass(
- value = ObjectOutputStream.class,
- untestedMethods = {
- @TestTargetNew(
- method = "annotateClass",
- args = {Class.class},
- level = TestLevel.NOT_NECESSARY,
- notes = "According to specification, the implementation " +
- "does nothing."
- ),
- @TestTargetNew(
- method = "annotateProxyClass",
- args = {Class.class},
- level = TestLevel.NOT_NECESSARY,
- notes = "According to specification, the implementation " +
- "does nothing."
- )
- }
-)
-public class ObjectOutputStreamTest extends junit.framework.TestCase implements
- Serializable {
-
- static final long serialVersionUID = 1L;
-
- java.io.File f;
-
- public class SerializableTestHelper implements Serializable {
- public String aField1;
-
- public String aField2;
-
- SerializableTestHelper() {
- aField1 = null;
- aField2 = null;
- }
-
- SerializableTestHelper(String s, String t) {
- aField1 = s;
- aField2 = t;
- }
-
- private void readObject(ObjectInputStream ois) throws IOException {
- // note aField2 is not read
- try {
- ObjectInputStream.GetField fields = ois.readFields();
- aField1 = (String) fields.get("aField1", "Zap");
- } catch (Exception e) {
- }
- }
-
- private void writeObject(ObjectOutputStream oos) throws IOException {
- // note aField2 is not written
- ObjectOutputStream.PutField fields = oos.putFields();
- fields.put("aField1", aField1);
- oos.writeFields();
- }
-
- public String getText1() {
- return aField1;
- }
-
- public void setText1(String s) {
- aField1 = s;
- }
-
- public String getText2() {
- return aField2;
- }
-
- public void setText2(String s) {
- aField2 = s;
- }
- }
-
- private static class SpecTestSuperClass implements Runnable, Serializable {
- static final long serialVersionUID = 1L;
- protected java.lang.String instVar;
-
- public void run() {
- }
- }
-
- private static class SpecTest extends SpecTestSuperClass implements
- Cloneable, Serializable {
- static final long serialVersionUID = 1L;
-
- public java.lang.String instVar1;
-
- public static java.lang.String staticVar1;
-
- public static java.lang.String staticVar2;
- {
- instVar1 = "NonStaticInitialValue";
- }
- static {
- staticVar1 = "StaticInitialValue";
- staticVar1 = new String(staticVar1);
- }
-
- public Object method(Object objParam, Object objParam2) {
- return new Object();
- }
-
- public boolean method(boolean bParam, Object objParam) {
- return true;
- }
-
- public boolean method(boolean bParam, Object objParam, Object objParam2) {
- return true;
- }
-
- }
-
- private static class SpecTestSubclass extends SpecTest implements
- Serializable {
- static final long serialVersionUID = 1L;
- public transient java.lang.String transientInstVar = "transientValue";
- }
-
- private static class ReadWriteObject implements java.io.Serializable {
- static final long serialVersionUID = 1L;
-
- public boolean calledWriteObject = false;
-
- public boolean calledReadObject = false;
-
- public ReadWriteObject() {
- super();
- }
-
- private void readObject(java.io.ObjectInputStream in)
- throws java.io.IOException, ClassNotFoundException {
- calledReadObject = true;
- in.readObject();
- }
-
- private void writeObject(java.io.ObjectOutputStream out)
- throws java.io.IOException {
- calledWriteObject = true;
- out.writeObject(FOO);
- }
- }
-
- private static class PublicReadWriteObject implements java.io.Serializable {
- public boolean calledWriteObject = false;
-
- public boolean calledReadObject = false;
-
- public PublicReadWriteObject() {
- super();
- }
-
- public void readObject(java.io.ObjectInputStream in)
- throws java.io.IOException, ClassNotFoundException {
- calledReadObject = true;
- in.readObject();
- }
-
- public void writeObject(java.io.ObjectOutputStream out)
- throws java.io.IOException {
- calledWriteObject = true;
- out.writeObject(FOO);
- }
- }
-
- private static class FieldOrder implements Serializable {
- String aaa1NonPrimitive = "aaa1";
-
- int bbb1PrimitiveInt = 5;
-
- boolean aaa2PrimitiveBoolean = true;
-
- String bbb2NonPrimitive = "bbb2";
- }
-
- private static class JustReadObject implements java.io.Serializable {
- public boolean calledReadObject = false;
-
- public JustReadObject() {
- super();
- }
-
- private void readObject(java.io.ObjectInputStream in)
- throws java.io.IOException, ClassNotFoundException {
- calledReadObject = true;
- in.defaultReadObject();
- }
- }
-
- private static class JustWriteObject implements java.io.Serializable {
- static final long serialVersionUID = 1L;
- public boolean calledWriteObject = false;
-
- public JustWriteObject() {
- super();
- }
-
- private void writeObject(java.io.ObjectOutputStream out)
- throws java.io.IOException, ClassNotFoundException {
- calledWriteObject = true;
- out.defaultWriteObject();
- }
- }
-
- private static class ClassBasedReplacementWhenDumping implements
- java.io.Serializable {
- public boolean calledReplacement = false;
-
- public ClassBasedReplacementWhenDumping() {
- super();
- }
-
- private Object writeReplace() {
- calledReplacement = true;
- return FOO; // Replacement is a String
- }
- }
-
- private static class MultipleClassBasedReplacementWhenDumping implements
- java.io.Serializable {
- private static class C1 implements java.io.Serializable {
- private Object writeReplace() {
- return new C2();
- }
- }
-
- private static class C2 implements java.io.Serializable {
- private Object writeReplace() {
- return new C3();
- }
- }
-
- private static class C3 implements java.io.Serializable {
- private Object writeReplace() {
- return FOO;
- }
- }
-
- public MultipleClassBasedReplacementWhenDumping() {
- super();
- }
-
- private Object writeReplace() {
- return new C1();
- }
- }
-
- private static class ClassBasedReplacementWhenLoading implements
- java.io.Serializable {
- public ClassBasedReplacementWhenLoading() {
- super();
- }
-
- private Object readResolve() {
- return FOO; // Replacement is a String
- }
- }
-
- private static class ClassBasedReplacementWhenLoadingViolatesFieldType
- implements java.io.Serializable {
- public ClassBasedReplacementWhenLoading classBasedReplacementWhenLoading = new ClassBasedReplacementWhenLoading();
-
- public ClassBasedReplacementWhenLoadingViolatesFieldType() {
- super();
- }
- }
-
- private static class MyExceptionWhenDumping implements java.io.Serializable {
- private static class MyException extends java.io.IOException {
- };
-
- public boolean anInstanceVar = false;
-
- public MyExceptionWhenDumping() {
- super();
- }
-
- private void readObject(java.io.ObjectInputStream in)
- throws java.io.IOException, ClassNotFoundException {
- in.defaultReadObject();
- }
-
- private void writeObject(java.io.ObjectOutputStream out)
- throws java.io.IOException, ClassNotFoundException {
- throw new MyException();
- }
- }
-
- private static class NonSerializableExceptionWhenDumping implements
- java.io.Serializable {
- public Object anInstanceVar = new Object();
-
- public NonSerializableExceptionWhenDumping() {
- super();
- }
- }
-
- private static class MyUnserializableExceptionWhenDumping implements
- java.io.Serializable {
- private static class MyException extends java.io.IOException {
- private Object notSerializable = new Object();
- };
-
- public boolean anInstanceVar = false;
-
- public MyUnserializableExceptionWhenDumping() {
- super();
- }
-
- private void readObject(java.io.ObjectInputStream in)
- throws java.io.IOException, ClassNotFoundException {
- in.defaultReadObject();
- }
-
- private void writeObject(java.io.ObjectOutputStream out)
- throws java.io.IOException, ClassNotFoundException {
- throw new MyException();
- }
- }
-
- private static class WithUnmatchingSerialPersistentFields implements
- java.io.Serializable {
- private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
- "value", String.class) };
-
- public int anInstanceVar = 5;
-
- public WithUnmatchingSerialPersistentFields() {
- super();
- }
- }
-
- private static class WithMatchingSerialPersistentFields implements
- java.io.Serializable {
- private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
- "anInstanceVar", String.class) };
-
- public String anInstanceVar = FOO + FOO;
-
- public WithMatchingSerialPersistentFields() {
- super();
- }
- }
-
- private static class SerialPersistentFields implements java.io.Serializable {
- private static final String SIMULATED_FIELD_NAME = "text";
-
- private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
- SIMULATED_FIELD_NAME, String.class) };
-
- public int anInstanceVar = 5;
-
- public SerialPersistentFields() {
- super();
- }
-
- private void readObject(java.io.ObjectInputStream in)
- throws java.io.IOException, ClassNotFoundException {
- ObjectInputStream.GetField fields = in.readFields();
- anInstanceVar = Integer.parseInt((String) fields.get(
- SIMULATED_FIELD_NAME, "-5"));
- }
-
- private void writeObject(java.io.ObjectOutputStream out)
- throws java.io.IOException, ClassNotFoundException {
- ObjectOutputStream.PutField fields = out.putFields();
- fields.put(SIMULATED_FIELD_NAME, Integer.toString(anInstanceVar));
- out.writeFields();
- }
- }
-
- private static class WriteFieldsWithoutFetchingPutFields implements
- java.io.Serializable {
- private static final String SIMULATED_FIELD_NAME = "text";
-
- private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
- SIMULATED_FIELD_NAME, String.class) };
-
- public int anInstanceVar = 5;
-
- public WriteFieldsWithoutFetchingPutFields() {
- super();
- }
-
- private void readObject(java.io.ObjectInputStream in)
- throws java.io.IOException, ClassNotFoundException {
- in.readFields();
- }
-
- private void writeObject(java.io.ObjectOutputStream out)
- throws java.io.IOException, ClassNotFoundException {
- out.writeFields();
- }
- }
-
- private static class SerialPersistentFieldsWithoutField implements
- java.io.Serializable {
- public int anInstanceVar = 5;
-
- public SerialPersistentFieldsWithoutField() {
- super();
- }
-
- private void readObject(java.io.ObjectInputStream in)
- throws java.io.IOException, ClassNotFoundException {
- in.readFields();
- }
-
- private void writeObject(java.io.ObjectOutputStream out)
- throws java.io.IOException, ClassNotFoundException {
- out.putFields();
- out.writeFields();
- }
- }
-
- private static class NotSerializable {
- private int foo;
-
- public NotSerializable() {
- }
-
- protected Object writeReplace() throws ObjectStreamException {
- return new Integer(42);
- }
- }
-
- private static class WriteReplaceObject implements Serializable {
- private Object replaceObject;
-
- private static enum Color {
- red, blue, green
- };
-
- public WriteReplaceObject(Object o) {
- replaceObject = o;
- }
-
- protected Object writeReplace() throws ObjectStreamException {
- return replaceObject;
- }
- }
-
- private static class ExternalizableWithReplace implements Externalizable {
- private int foo;
-
- public ExternalizableWithReplace() {
- }
-
- protected Object writeReplace() throws ObjectStreamException {
- return new Integer(42);
- }
-
- public void writeExternal(ObjectOutput out) {
- }
-
- public void readExternal(ObjectInput in) {
- }
- }
-
- private static class ObjectOutputStreamWithReplace extends ObjectOutputStream {
- public ObjectOutputStreamWithReplace(OutputStream out) throws IOException {
- super(out);
- enableReplaceObject(true);
- }
-
- protected Object replaceObject(Object obj) throws IOException {
- if (obj instanceof NotSerializable) {
- return new Long(10);
- } else if (obj instanceof Integer) {
- return new Long(((Integer) obj).longValue());
- } else {
- return obj;
- }
- }
- }
-
- private static class ObjectOutputStreamWithReplace2 extends
- ObjectOutputStream {
- public ObjectOutputStreamWithReplace2(OutputStream out)
- throws IOException {
- super(out);
- enableReplaceObject(true);
- }
-
- protected Object replaceObject(Object obj) throws IOException {
- return new Long(10);
- }
- }
-
- private static class BasicObjectOutputStream extends ObjectOutputStream {
- public boolean writeStreamHeaderCalled;
-
- public BasicObjectOutputStream() throws IOException, SecurityException {
- super();
- writeStreamHeaderCalled = false;
- }
-
- public BasicObjectOutputStream(OutputStream output) throws IOException {
- super(output);
- }
-
- public void drain() throws IOException {
- super.drain();
- }
-
- public boolean enableReplaceObject(boolean enable)
- throws SecurityException {
- return super.enableReplaceObject(enable);
- }
-
- public void writeObjectOverride(Object object) throws IOException {
- super.writeObjectOverride(object);
- }
-
- public void writeStreamHeader() throws IOException {
- super.writeStreamHeader();
- writeStreamHeaderCalled = true;
- }
-}
-
- private static class NoFlushTestOutputStream extends ByteArrayOutputStream {
- public boolean flushCalled;
-
- public NoFlushTestOutputStream() {
- super();
- flushCalled = false;
- }
-
- public void flush() throws IOException {
- super.flush();
- flushCalled = true;
- }
- }
-
- protected static final String MODE_XLOAD = "xload";
-
- protected static final String MODE_XDUMP = "xdump";
-
- static final String FOO = "foo";
-
- static final String MSG_WITE_FAILED = "Failed to write: ";
-
- private static final boolean DEBUG = false;
-
- protected static boolean xload = false;
-
- protected static boolean xdump = false;
-
- protected static String xFileName = null;
-
- protected ObjectInputStream ois;
-
- protected ObjectOutputStream oos;
-
- protected ObjectOutputStream oos_ioe;
-
- protected Support_OutputStream sos;
-
- protected ByteArrayOutputStream bao;
-
- static final int INIT_INT_VALUE = 7;
-
- static final String INIT_STR_VALUE = "a string that is blortz";
-
- /**
- * @tests java.io.ObjectInputStream#ObjectOutputStream()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies the protected ObjectOutputStream() constructor.",
- method = "ObjectOutputStream",
- args = {}
- )
- public void test_Constructor() throws IOException {
- SecurityManager sm = System.getSecurityManager();
- System.setSecurityManager(new Support_IOTestSecurityManager());
-
- try {
- oos = new BasicObjectOutputStream();
- fail("SecurityException expected.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(sm);
- }
- }
-
- /**
- * @tests java.io.ObjectOutputStream#ObjectOutputStream(java.io.OutputStream)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks valid construction, NullPointerException and IOException.",
- method = "ObjectOutputStream",
- args = {java.io.OutputStream.class}
- )
- public void test_ConstructorLjava_io_OutputStream() throws IOException {
- oos.close();
- oos = new ObjectOutputStream(new ByteArrayOutputStream());
- oos.close();
-
- try {
- oos = new ObjectOutputStream(null);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
-
- Support_ASimpleOutputStream sos = new Support_ASimpleOutputStream(true);
- try {
- oos = new ObjectOutputStream(sos);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ObjectOutputStream#ObjectOutputStream(java.io.OutputStream)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks SecurityException.",
- method = "ObjectOutputStream",
- args = {java.io.OutputStream.class}
- )
- public void test_ConstructorLjava_io_OutputStream_subtest0() throws IOException {
-
- // custom security manager
- SecurityManager sm = new SecurityManager() {
-
- final SerializablePermission forbidenPermission =
- new SerializablePermission("enableSubclassImplementation");
-
- public void checkPermission(Permission perm) {
- if (forbidenPermission.equals(perm)) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- // should not cause SecurityException
- new ObjectOutputStream(out);
- // should not cause SecurityException
- class SubTest1 extends ObjectOutputStream {
- SubTest1(OutputStream out) throws IOException {
- super(out);
- }
- }
-
- // should not cause SecurityException
- new SubTest1(out);
- class SubTest2 extends ObjectOutputStream {
- SubTest2(OutputStream out) throws IOException {
- super(out);
- }
-
- public void writeUnshared(Object obj) throws IOException {
- }
- }
-
- try {
- new SubTest2(out);
- fail("should throw SecurityException 1");
- } catch (SecurityException e) {
- }
- class SubTest3 extends ObjectOutputStream {
- SubTest3(OutputStream out) throws IOException {
- super(out);
- }
-
- public PutField putFields() throws IOException {
- return null;
- }
- }
-
- try {
- new SubTest3(out);
- fail("should throw SecurityException 2");
- } catch (SecurityException e) {
- }
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.io.ObjectOutputStream#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "close",
- args = {}
- )
- public void test_close() throws IOException {
- int outputSize = bao.size();
- // Writing of a primitive type should be buffered.
- oos.writeInt(42);
- assertTrue("Test 1: Primitive data unexpectedly written to the target stream.",
- bao.size() == outputSize);
- // Closing should write the buffered data to the target stream.
- oos.close();
- assertTrue("Test 2: Primitive data has not been written to the the target stream.",
- bao.size() > outputSize);
-
- try {
- oos_ioe.close();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ObjectOutputStream#drain()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "drain",
- args = {}
- )
- public void test_drain() throws IOException {
- NoFlushTestOutputStream target = new NoFlushTestOutputStream();
- BasicObjectOutputStream boos = new BasicObjectOutputStream(target);
- int initialSize = target.size();
- boolean written = false;
-
- boos.writeBytes("Lorem ipsum");
- // If there is no buffer then the bytes have already been written.
- written = (target.size() > initialSize);
-
- boos.drain();
- assertTrue("Content has not been written to the target.",
- written || (target.size() > initialSize));
- assertFalse("flush() has been called on the target.",
- target.flushCalled);
- }
-
- /**
- * @tests java.io.ObjectOutputStream#defaultWriteObject()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException can not be tested because this method" +
- "always throws a NotActiveException if called directly.",
- method = "defaultWriteObject",
- args = {}
- )
- public void test_defaultWriteObject() throws IOException {
- try {
- oos.defaultWriteObject();
- fail("Test 1: NotActiveException expected.");
- } catch (NotActiveException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ObjectOutputStream#enableReplaceObject(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "enableReplaceObject",
- args = {boolean.class}
- )
- public void test_enableReplaceObjectB() throws IOException {
- // Start testing without a SecurityManager.
- BasicObjectOutputStream boos = new BasicObjectOutputStream();
- assertFalse("Test 1: Object resolving must be disabled by default.",
- boos.enableReplaceObject(true));
-
- assertTrue("Test 2: enableReplaceObject did not return the previous value.",
- boos.enableReplaceObject(false));
-
- // Test 3: Check that a security exception is thrown.
- SecurityManager sm = System.getSecurityManager();
- System.setSecurityManager(new Support_IOTestSecurityManager());
- try {
- boos.enableReplaceObject(true);
- fail("Test 3: SecurityException expected.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(sm);
- }
- }
-
- /**
- * @tests java.io.ObjectOutputStream#flush()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "flush",
- args = {}
- )
- public void test_flush() throws Exception {
- // Test for method void java.io.ObjectOutputStream.flush()
- int size = bao.size();
- oos.writeByte(127);
- assertTrue("Test 1: Data already flushed.", bao.size() == size);
- oos.flush();
- assertTrue("Test 2: Failed to flush data.", bao.size() > size);
-
- try {
- oos_ioe.flush();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ObjectOutputStream#putFields()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException can not be tested because this method" +
- "always throws a NotActiveException if called directly.",
- method = "putFields",
- args = {}
- )
- public void test_putFields() throws Exception {
- /*
- * "SerializableTestHelper" is an object created for these tests with
- * two fields (Strings) and simple implementations of readObject and
- * writeObject which simply read and write the first field but not the
- * second one.
- */
- SerializableTestHelper sth;
-
- try {
- oos.putFields();
- fail("Test 1: NotActiveException expected.");
- } catch (NotActiveException e) {
- // Expected.
- }
-
- oos.writeObject(new SerializableTestHelper("Gabba", "Jabba"));
- oos.flush();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- sth = (SerializableTestHelper) (ois.readObject());
- assertEquals("Test 2: readFields or writeFields failed; first field not set.",
- "Gabba", sth.getText1());
- assertNull("Test 3: readFields or writeFields failed; second field should not have been set.",
- sth.getText2());
- }
-
- /**
- * @tests java.io.ObjectOutputStream#reset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "reset",
- args = {}
- )
- public void test_reset() throws Exception {
- String o = "HelloWorld";
- sos = new Support_OutputStream(200);
- oos.close();
- oos = new ObjectOutputStream(sos);
- oos.writeObject(o);
- oos.writeObject(o);
- oos.reset();
- oos.writeObject(o);
-
- sos.setThrowsException(true);
- try {
- oos.reset();
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- sos.setThrowsException(false);
-
- ois = new ObjectInputStream(new ByteArrayInputStream(sos.toByteArray()));
- assertEquals("Test 2: Incorrect object read.", o, ois.readObject());
- assertEquals("Test 3: Incorrect object read.", o, ois.readObject());
- assertEquals("Test 4: Incorrect object read.", o, ois.readObject());
- ois.close();
- }
-
- private static class ExternalTest implements Externalizable {
- public String value;
-
- public ExternalTest() {
- }
-
- public void setValue(String val) {
- value = val;
- }
-
- public String getValue() {
- return value;
- }
-
- public void writeExternal(ObjectOutput output) {
- try {
- output.writeUTF(value);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- public void readExternal(ObjectInput input) {
- try {
- value = input.readUTF();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- /**
- * @tests java.io.ObjectOutputStream#useProtocolVersion(int)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException seems to be never thrown, therefore there is no such test.",
- method = "useProtocolVersion",
- args = {int.class}
- )
- public void test_useProtocolVersionI() throws Exception {
-
- oos.useProtocolVersion(ObjectOutputStream.PROTOCOL_VERSION_1);
- ExternalTest t1 = new ExternalTest();
- t1.setValue("hello1");
- oos.writeObject(t1);
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- ExternalTest t2 = (ExternalTest) ois.readObject();
- ois.close();
- assertTrue(
- "Cannot read/write PROTOCAL_VERSION_1 Externalizable objects: "
- + t2.getValue(), t1.getValue().equals(t2.getValue()));
- }
-
- /**
- * @tests java.io.ObjectOutputStream#write(byte[])
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing. IOException can " +
- "not be checked since is never thrown (primitive data " +
- "is written into a self-expanding buffer).",
- method = "write",
- args = {byte[].class}
- )
- public void test_write$B() throws Exception {
- // Test for method void java.io.ObjectOutputStream.write(byte [])
- byte[] buf = new byte[10];
- oos.write("HelloWorld".getBytes());
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- ois.read(buf, 0, 10);
- ois.close();
- assertEquals("Read incorrect bytes", "HelloWorld", new String(buf, 0,
- 10));
- }
-
- /**
- * @tests java.io.ObjectOutputStream#write(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing. IOException can " +
- "not be checked since is never thrown (primitive data " +
- "is written into a self-expanding buffer).",
- method = "write",
- args = {byte[].class, int.class, int.class}
- )
- public void test_write$BII() throws Exception {
- // Test for method void java.io.ObjectOutputStream.write(byte [], int,
- // int)
- byte[] buf = new byte[10];
- oos.write("HelloWorld".getBytes(), 0, 10);
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- ois.read(buf, 0, 10);
- ois.close();
- assertEquals("Read incorrect bytes", "HelloWorld", new String(buf, 0,
- 10));
-
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- try {
- ois.read(buf, 0, -1);
- fail("IndexOutOfBoundsException not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- ois.read(buf, -1, 1);
- fail("IndexOutOfBoundsException not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- ois.read(buf, 10, 1);
- fail("IndexOutOfBoundsException not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- ois.close();
-
- }
-
- /**
- * @tests java.io.ObjectOutputStream#write(int)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing. IOException can " +
- "not be checked since is never thrown (primitive data " +
- "is written into a self-expanding buffer).",
- method = "write",
- args = {int.class}
- )
- public void test_writeI() throws Exception {
- // Test for method void java.io.ObjectOutputStream.write(int)
- oos.write('T');
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- assertEquals("Read incorrect byte", 'T', ois.read());
- ois.close();
- }
-
- /**
- * @tests java.io.ObjectOutputStream#writeBytes(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing. IOException can " +
- "not be checked since is never thrown (primitive data " +
- "is written into a self-expanding buffer).",
- method = "writeBytes",
- args = {java.lang.String.class}
- )
- public void test_writeBytesLjava_lang_String() throws Exception {
- // Test for method void
- // java.io.ObjectOutputStream.writeBytes(java.lang.String)
- byte[] buf = new byte[10];
- oos.writeBytes("HelloWorld");
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- ois.readFully(buf);
- ois.close();
- assertEquals("Wrote incorrect bytes value", "HelloWorld", new String(
- buf, 0, 10));
- }
-
- /**
- * @tests java.io.ObjectOutputStream#writeChars(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing. IOException can " +
- "not be checked since is never thrown (primitive data " +
- "is written into a self-expanding buffer).",
- method = "writeChars",
- args = {java.lang.String.class}
- )
- public void test_writeCharsLjava_lang_String() throws Exception {
- // Test for method void
- // java.io.ObjectOutputStream.writeChars(java.lang.String)
- int avail = 0;
- char[] buf = new char[10];
- oos.writeChars("HelloWorld");
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- // Number of prim data bytes in stream / 2 to give char index
- avail = ois.available() / 2;
- for (int i = 0; i < avail; ++i)
- buf[i] = ois.readChar();
- ois.close();
- assertEquals("Wrote incorrect chars", "HelloWorld", new String(buf, 0,
- 10));
- }
-
- /**
- * @tests java.io.ObjectOutputStream#writeObject(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "writeObject",
- args = {java.lang.Object.class}
- )
- public void test_writeObjectLjava_lang_Object() throws Exception {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- SerialPersistentFieldsWithoutField spf = new SerialPersistentFieldsWithoutField();
- final int CONST = -500;
- spf.anInstanceVar = CONST;
- objToSave = spf;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue(
- "serialPersistentFields do not work properly in this implementation",
- ((SerialPersistentFieldsWithoutField) objLoaded).anInstanceVar != CONST);
-
- }
-
- /**
- * @tests java.io.ObjectOutputStream#writeObject(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "writeObject",
- args = {java.lang.Object.class}
- )
- public void test_writeObject_NotSerializable() throws Exception {
- ObjectOutput out = null;
- try {
- out = new ObjectOutputStream(new ByteArrayOutputStream());
- out.writeObject(new NotSerializable());
- fail("Expected NotSerializableException");
- } catch (NotSerializableException e) {}
- out.writeObject(new ExternalizableWithReplace());
- }
-
- /**
- * @tests java.io.ObjectOutputStream#writeObjectOverride(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies that writeObjectOverride() throws an IOException.",
- method = "writeObjectOverride",
- args = {java.lang.Object.class}
- )
- public void test_writeObjectOverrideLjava_lang_Object() throws IOException {
- BasicObjectOutputStream boos =
- new BasicObjectOutputStream(new ByteArrayOutputStream());
-
- try {
- boos.writeObjectOverride(new Object());
- fail("IOException expected.");
- }
- catch (IOException e) {
- }
- finally {
- boos.close();
- }
- }
-
- /**
- * @tests java.io.ObjectOutputStream#writeStreamHeader()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies writeStreamHeader().",
- method = "writeStreamHeader",
- args = {}
- )
- public void test_writeStreamHeader() throws IOException {
- BasicObjectOutputStream boos;
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- short s;
- byte[] buffer;
-
- // Test 1: Make sure that writeStreamHeader() has been called.
- boos = new BasicObjectOutputStream(baos);
- try {
- assertTrue("Test 1: writeStreamHeader() has not been called.",
- boos.writeStreamHeaderCalled);
-
- // Test 2: Check that at least four bytes have been written.
- buffer = baos.toByteArray();
- assertTrue("Test 2: At least four bytes should have been written",
- buffer.length >= 4);
-
- // Test 3: Check the magic number.
- s = buffer[0];
- s <<= 8;
- s += ((short) buffer[1] & 0x00ff);
- assertEquals("Test 3: Invalid magic number written.",
- java.io.ObjectStreamConstants.STREAM_MAGIC, s);
-
- // Test 4: Check the stream version number.
- s = buffer[2];
- s <<= 8;
- s += ((short) buffer[3] & 0x00ff);
- assertEquals("Invalid stream version number written.",
- java.io.ObjectStreamConstants.STREAM_VERSION, s);
- }
- finally {
- boos.close();
- }
- }
-
- /**
- * @tests java.io.ObjectOutputStream#writeUTF(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "IOException checking missed.",
- method = "writeUTF",
- args = {java.lang.String.class}
- )
- public void test_writeUTFLjava_lang_String() throws Exception {
- // Test for method void
- // java.io.ObjectOutputStream.writeUTF(java.lang.String)
- oos.writeUTF("HelloWorld");
- oos.close();
- ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
- assertEquals("Wrote incorrect UTF value", "HelloWorld", ois.readUTF());
- }
-
- /**
- * @tests java.io.ObjectOutputStream#writeObject(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "writeObject",
- args = {java.lang.Object.class}
- )
- public void test_writeObject_Exception() throws ClassNotFoundException, IOException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
- ObjectOutputStream oos = new ObjectOutputStream(baos);
-
- try {
- oos.writeObject(new Object());
- fail("should throw ObjectStreamException");
- } catch (ObjectStreamException e) {
- // expected
- } finally {
- oos.close();
- baos.close();
- }
-
- byte[] bytes = baos.toByteArray();
- ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
- bytes));
- try {
- ois.readObject();
- fail("should throw WriteAbortedException");
- } catch (WriteAbortedException e) {
- // expected
- } finally {
- ois.close();
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() throws Exception {
- super.setUp();
- oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
- oos_ioe = new ObjectOutputStream(sos = new Support_OutputStream());
- sos.setThrowsException(true);
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- if (oos != null) {
- try {
- oos.close();
- } catch (Exception e) {}
- }
- if (oos_ioe != null) {
- try {
- oos_ioe.close();
- } catch (Exception e) {}
- }
- if (f != null && f.exists()) {
- if (!f.delete()) {
- fail("Error cleaning up files during teardown");
- }
- }
- }
-
- protected Object reload() throws IOException, ClassNotFoundException {
-
- // Choose the load stream
- if (xload || xdump) {
- // Load from pre-existing file
- ois = new ObjectInputStream(new FileInputStream(xFileName + "-"
- + getName() + ".ser"));
- } else {
- // Just load from memory, we dumped to memory
- ois = new ObjectInputStream(new ByteArrayInputStream(bao
- .toByteArray()));
- }
-
- try {
- return ois.readObject();
- } finally {
- ois.close();
- }
- }
-
- protected void dump(Object o) throws IOException, ClassNotFoundException {
-
- // Choose the dump stream
- if (xdump) {
- oos = new ObjectOutputStream(new FileOutputStream(
- f = new java.io.File(xFileName + "-" + getName() + ".ser")));
- } else {
- oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
- }
-
- // Dump the object
- try {
- oos.writeObject(o);
- } finally {
- oos.close();
- }
- }
-
- /**
- * @tests java.io.ObjectOutputStream#writeInt(int)
- * @tests java.io.ObjectOutputStream#writeObject(java.lang.Object)
- * @tests java.io.ObjectOutputStream#writeUTF(java.lang.String)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "writeInt",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "writeObject",
- args = {java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "writeUTF",
- args = {java.lang.String.class}
- )
- })
- public void testMixPrimitivesAndObjects() throws Exception {
- int i = 7;
- String s1 = "string 1";
- String s2 = "string 2";
- byte[] bytes = { 1, 2, 3 };
- try {
- oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
- oos.writeInt(i);
- oos.writeObject(s1);
- oos.writeUTF(s2);
- oos.writeObject(bytes);
- oos.close();
-
- ois = new ObjectInputStream(new ByteArrayInputStream(bao
- .toByteArray()));
-
- int j = ois.readInt();
- assertTrue("Wrong int :" + j, i == j);
-
- String l1 = (String) ois.readObject();
- assertTrue("Wrong obj String :" + l1, s1.equals(l1));
-
- String l2 = ois.readUTF();
- assertTrue("Wrong UTF String :" + l2, s2.equals(l2));
-
- byte[] bytes2 = (byte[]) ois.readObject();
- assertTrue("Wrong byte[]", Arrays.equals(bytes, bytes2));
- } finally {
- try {
- if (oos != null)
- oos.close();
- if (ois != null)
- ois.close();
- } catch (IOException e) {}
- }
- }
-
- /**
- * @tests java.io.ObjectOutputStream#writeUnshared(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "writeUnshared",
- args = {java.lang.Object.class}
- )
- public void test_writeUnshared() throws Exception {
- //Regression for HARMONY-187
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStream oos = new ObjectOutputStream(baos);
-
- Object o = "foobar";
- oos.writeObject(o);
- oos.writeUnshared(o);
- oos.writeObject(o);
- oos.flush();
-
- ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream (baos.toByteArray()));
-
- Object[] oa = new Object[3];
- for (int i = 0; i < oa.length; i++) {
- oa[i] = ois.readObject();
- }
-
- oos.close();
- ois.close();
-
- // All three conditions must be met
- assertNotSame("oa[0] != oa[1]", oa[0], oa[1]);
- assertNotSame("oa[1] != oa[2]", oa[1], oa[2]);
- assertSame("oa[0] == oa[2]", oa[0], oa[2]);
- }
-
- /**
- * @tests java.io.ObjectOutputStream#writeUnshared(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "writeUnshared",
- args = {java.lang.Object.class}
- )
- public void test_writeUnshared2() throws Exception {
- //Regression for HARMONY-187
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStream oos = new ObjectOutputStream(baos);
-
- Object o = new Object[1];
- oos.writeObject(o);
- oos.writeUnshared(o);
- oos.writeObject(o);
- oos.flush();
-
- ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream (baos.toByteArray()));
-
- Object[] oa = new Object[3];
- for (int i = 0; i < oa.length; i++) {
- oa[i] = ois.readObject();
- }
-
- oos.close();
- ois.close();
-
- // All three conditions must be met
- assertNotSame("oa[0] != oa[1]", oa[0], oa[1]);
- assertNotSame("oa[1] != oa[2]", oa[1], oa[2]);
- assertSame("oa[0] == oa[2]", oa[0], oa[2]);
- }
-
- protected Object dumpAndReload(Object o) throws IOException,
- ClassNotFoundException {
- dump(o);
- return reload();
- }
-
- /**
- * @tests java.io.ObjectOutputStream#useProtocolVersion(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "IOException & IllegalStateException checking missed.",
- method = "useProtocolVersion",
- args = {int.class}
- )
- public void test_useProtocolVersionI_2() throws Exception {
- ObjectOutputStream oos = new ObjectOutputStream(
- new ByteArrayOutputStream());
-
- oos.useProtocolVersion(ObjectOutputStream.PROTOCOL_VERSION_1);
- oos.useProtocolVersion(ObjectOutputStream.PROTOCOL_VERSION_2);
- try {
- oos.useProtocolVersion(3);
- fail("Protocol 3 should not be accepted");
- } catch (IllegalArgumentException e) {
- // expected
- } finally {
- oos.close();
- }
- }
-
- /**
- * @tests java.io.ObjectOutputStream#replaceObject(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "replaceObject",
- args = {java.lang.Object.class}
- )
- public void test_replaceObject() throws Exception {
- //Regression for HARMONY-1429
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStreamWithReplace oos = new ObjectOutputStreamWithReplace(baos);
-
- oos.writeObject(new NotSerializable());
- oos.flush();
- ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream (baos.toByteArray()));
- Object obj = ois.readObject();
- oos.close();
- ois.close();
- assertTrue("replaceObject has not been called", (obj instanceof Long));
-
- //Regression for HARMONY-2239
- Object replaceObject = int.class;
- baos = new ByteArrayOutputStream();
- ObjectOutputStreamWithReplace2 oos2 = new ObjectOutputStreamWithReplace2(
- baos);
- oos2.writeObject(new WriteReplaceObject(replaceObject));
- oos2.flush();
- ois = new ObjectInputStream(
- new ByteArrayInputStream(baos.toByteArray()));
- obj = ois.readObject();
- oos.close();
- ois.close();
- assertTrue("replaceObject has not been called", (obj instanceof Long));
-
- replaceObject = ObjectStreamClass.lookup(Integer.class);
- baos = new ByteArrayOutputStream();
- oos2 = new ObjectOutputStreamWithReplace2(baos);
- oos2.writeObject(new WriteReplaceObject(replaceObject));
- oos2.flush();
- ois = new ObjectInputStream(
- new ByteArrayInputStream(baos.toByteArray()));
- obj = ois.readObject();
- oos.close();
- ois.close();
- assertTrue("replaceObject has not been called", (obj instanceof Long));
-
- replaceObject = WriteReplaceObject.Color.red;
- baos = new ByteArrayOutputStream();
- oos2 = new ObjectOutputStreamWithReplace2(baos);
- oos2.writeObject(new WriteReplaceObject(replaceObject));
- oos2.flush();
- ois = new ObjectInputStream(
- new ByteArrayInputStream(baos.toByteArray()));
- obj = ois.readObject();
- oos.close();
- ois.close();
- assertTrue("replaceObject has not been called", (obj instanceof Long));
-
- // Regression for HARMONY-3158
- Object obj1;
- Object obj2;
- Object obj3;
-
- baos = new ByteArrayOutputStream();
- oos = new ObjectOutputStreamWithReplace(baos);
-
- oos.writeObject(new Integer(99));
- oos.writeObject(Integer.class);
- oos.writeObject(ObjectStreamClass.lookup(Integer.class));
- oos.flush();
-
- ois = new ObjectInputStream(new ByteArrayInputStream (baos.toByteArray()));
- obj1 = ois.readObject();
- obj2 = ois.readObject();
- obj3 = ois.readObject();
- oos.close();
- ois.close();
-
- assertTrue("1st replaceObject worked incorrectly", obj1 instanceof Long);
- assertEquals("1st replaceObject worked incorrectly",
- 99, ((Long) obj1).longValue());
- assertEquals("2nd replaceObject worked incorrectly", Integer.class, obj2);
- assertEquals("3rd replaceObject worked incorrectly",
- ObjectStreamClass.class, obj3.getClass());
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/ObjectStreamClassTest.java b/luni/src/test/java/tests/api/java/io/ObjectStreamClassTest.java
deleted file mode 100644
index ea1b7c3..0000000
--- a/luni/src/test/java/tests/api/java/io/ObjectStreamClassTest.java
+++ /dev/null
@@ -1,245 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.ObjectStreamClass;
-import java.io.ObjectStreamField;
-import java.io.Serializable;
-
-@TestTargetClass(ObjectStreamClass.class)
-public class ObjectStreamClassTest extends junit.framework.TestCase {
-
- static class DummyClass implements Serializable {
- private static final long serialVersionUID = 999999999999999L;
-
- long bam = 999L;
-
- int ham = 9999;
-
- public static long getUID() {
- return serialVersionUID;
- }
- }
-
- /**
- * @tests java.io.ObjectStreamClass#forClass()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "forClass",
- args = {}
- )
- public void test_forClass() {
- // Test for method java.lang.Class java.io.ObjectStreamClass.forClass()
- // Need to test during serialization to be sure an instance is
- // returned
- ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
- assertTrue("forClass returned an object: " + osc.forClass(), osc
- .forClass().equals(DummyClass.class));
- }
-
- /**
- * @tests java.io.ObjectStreamClass#getField(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getField",
- args = {java.lang.String.class}
- )
- public void test_getFieldLjava_lang_String() {
- // Test for method java.io.ObjectStreamField
- // java.io.ObjectStreamClass.getField(java.lang.String)
- ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
- assertEquals("getField did not return correct field", 'J', osc.getField("bam")
- .getTypeCode());
- assertNull("getField did not null for non-existent field", osc
- .getField("wham"));
- }
-
- /**
- * @tests java.io.ObjectStreamClass#getFields()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFields",
- args = {}
- )
- public void test_getFields() {
- // Test for method java.io.ObjectStreamField []
- // java.io.ObjectStreamClass.getFields()
- ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
- ObjectStreamField[] osfArray = osc.getFields();
- assertTrue(
- "Array of fields should be of length 2 but is instead of length: "
- + osfArray.length, osfArray.length == 2);
- }
-
- /**
- * @tests java.io.ObjectStreamClass#getName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getName",
- args = {}
- )
- public void test_getName() {
- // Test for method java.lang.String java.io.ObjectStreamClass.getName()
- ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
- assertTrue("getName returned incorrect name: " + osc.getName(), osc
- .getName().equals(
- "tests.api.java.io.ObjectStreamClassTest$DummyClass"));
- }
-
- /**
- * @tests java.io.ObjectStreamClass#getSerialVersionUID()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSerialVersionUID",
- args = {}
- )
- public void test_getSerialVersionUID() {
- // Test for method long java.io.ObjectStreamClass.getSerialVersionUID()
- ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
- assertTrue("getSerialversionUID returned incorrect uid: "
- + osc.getSerialVersionUID() + " instead of "
- + DummyClass.getUID(), osc.getSerialVersionUID() == DummyClass
- .getUID());
- }
-
- /**
- * @tests java.io.ObjectStreamClass#lookup(java.lang.Class)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lookup",
- args = {java.lang.Class.class}
- )
- public void test_lookupLjava_lang_Class() {
- // Test for method java.io.ObjectStreamClass
- // java.io.ObjectStreamClass.lookup(java.lang.Class)
- ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
- assertTrue("lookup returned wrong class: " + osc.getName(), osc
- .getName().equals(
- "tests.api.java.io.ObjectStreamClassTest$DummyClass"));
- }
-
- /**
- * @tests java.io.ObjectStreamClass#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.io.ObjectStreamClass.toString()
- ObjectStreamClass osc = ObjectStreamClass.lookup(DummyClass.class);
- String oscString = osc.toString();
- // The previous test was more specific than the spec so it was replaced
- // with the test below
- assertTrue("toString returned incorrect string: " + osc.toString(),
- oscString.indexOf("serialVersionUID") >= 0
- && oscString.indexOf("999999999999999L") >= 0);
- ;
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lookup",
- args = {java.lang.Class.class}
- )
- public void testSerialization() {
- ObjectStreamClass osc = ObjectStreamClass.lookup(ObjectStreamClass.class);
- assertEquals(0, osc.getFields().length);
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-
-// BEGIN android-added
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void testFooSerialVersionUid() {
- assertEquals(-5887964677443030867L, Foo.serialVersionUID());
- }
-
- /**
- * An arbitrary class which deliberately tickles various factors affecting
- * serialVersionUID calculation.
- */
- static abstract class Foo implements Cloneable, Serializable {
-
- /** All fields except "private static|transient", which these aren't. */
- private final String name = "foo";
- static final long now;
-
- /** Presence of static initializer has an affect. */
- static {
- now = System.currentTimeMillis();
- }
-
- /** Non-private constructors. */
- Foo() {}
- protected Foo(int ignored) {}
-
- /** Non-private methods. */
- synchronized static int foo() { return 0; }
- static int bar() { return 0; }
- abstract void tee();
- protected native synchronized boolean bob();
- protected synchronized void tim() {}
-
- /** Calculates Foo's default serialVersionUID. */
- static long serialVersionUID() {
- return ObjectStreamClass.lookup(Foo.class).getSerialVersionUID();
- }
- }
-
- public static void main(String[] args) {
- System.out.println(Foo.serialVersionUID());
- }
-// END android-added
-}
diff --git a/luni/src/test/java/tests/api/java/io/ObjectStreamExceptionTest.java b/luni/src/test/java/tests/api/java/io/ObjectStreamExceptionTest.java
deleted file mode 100644
index ac5c47a..0000000
--- a/luni/src/test/java/tests/api/java/io/ObjectStreamExceptionTest.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.ObjectStreamException;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(ObjectStreamException.class)
-public class ObjectStreamExceptionTest extends junit.framework.TestCase {
-
- class MyObjectStreamException extends ObjectStreamException {
- private static final long serialVersionUID = 1L;
-
- public MyObjectStreamException() {
- super();
- }
-
- public MyObjectStreamException(String detailMessage) {
- super(detailMessage);
- }
- }
-
- /**
- * @tests java.io.ObjectStreamException#ObjectStreamException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "ObjectStreamException",
- args = {}
- )
- public void test_Constructor() {
- try {
- if (true) // To avoid unreachable code compilation error.
- throw new MyObjectStreamException();
- fail("Test 1: MyObjectStreamException expected.");
- } catch (MyObjectStreamException e) {
- assertNull("Test 2: Null expected for exceptions constructed without a message.",
- e.getMessage());
- }
- }
-
- /**
- * @tests java.io.ObjectStreamException#ObjectStreamException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "ObjectStreamException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- try {
- if (true) // To avoid unreachable code compilation error.
- throw new MyObjectStreamException("Something went wrong.");
- fail("Test 1: MyObjectStreamException expected.");
- } catch (MyObjectStreamException e) {
- assertEquals("Test 2: Incorrect message;",
- "Something went wrong.", e.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/ObjectStreamFieldTest.java b/luni/src/test/java/tests/api/java/io/ObjectStreamFieldTest.java
deleted file mode 100644
index 058524f..0000000
--- a/luni/src/test/java/tests/api/java/io/ObjectStreamFieldTest.java
+++ /dev/null
@@ -1,537 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.NotActiveException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.ObjectStreamClass;
-import java.io.ObjectStreamField;
-import java.io.Serializable;
-import java.io.StreamCorruptedException;
-import java.util.Date;
-
-@TestTargetClass(ObjectStreamField.class)
-public class ObjectStreamFieldTest extends junit.framework.TestCase {
-
- static class DummyClass implements Serializable {
- private static final long serialVersionUID = 999999999999998L;
-
- boolean bField = true;
- char cField = 'c';
- double dField = 424242.4242;
- float fField = 24.12F;
- int iField = 1965;
- long lField = 9999999L;
- short sField = 42;
-
- long bam = 999L;
-
- int ham = 9999;
-
- int sam = 8888;
-
- Object hola = new Object();
-
- public static long getUID() {
- return serialVersionUID;
- }
- }
-
- class MyObjectStreamField extends ObjectStreamField {
- public MyObjectStreamField(String name, Class<?> cl) {
- super(name, cl);
- }
-
- public void setOffset(int newValue) {
- super.setOffset(newValue);
- }
- }
-
- ObjectStreamClass osc;
-
- ObjectStreamField hamField;
-
- ObjectStreamField samField;
-
- ObjectStreamField bamField;
-
- ObjectStreamField holaField;
-
- /**
- * @tests java.io.ObjectStreamField#ObjectStreamField(java.lang.String,
- * java.lang.Class)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies ObjectStreamField(String, Class<T>)",
- method = "ObjectStreamField",
- args = {java.lang.String.class, java.lang.Class.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_Class() {
- ObjectStreamField osf = new ObjectStreamField("aField", int.class);
- assertTrue("Test 1: Name member not set correctly.",
- osf.getName().equals("aField"));
- assertTrue("Test 2: Type member not set correctly.",
- osf.getType().equals(int.class));
-
- // Repeat the tests with a different object to make sure
- // that we have not tested against default values.
- osf = new ObjectStreamField("anotherField", String.class);
- assertTrue("Test 3: Name member not set correctly.",
- osf.getName().equals("anotherField"));
- assertTrue("Test 4: Type member not set correctly.",
- osf.getType().equals(String.class));
-
- // Invalid argument tests.
- try {
- osf = new ObjectStreamField(null, boolean.class);
- fail("Test 5: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
- try {
- osf = new ObjectStreamField("thisField", null);
- fail("Test 6: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ObjectStreamField#ObjectStreamField(java.lang.String,
- * java.lang.Class)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies ObjectStreamField(String, Class<T>, boolean)",
- method = "ObjectStreamField",
- args = {java.lang.String.class, java.lang.Class.class, boolean.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_ClassB() {
- ObjectStreamField osf = new ObjectStreamField("aField", int.class, false);
- assertTrue("Test 1: Name member not set correctly.",
- osf.getName().equals("aField"));
- assertTrue("Test 2: Type member not set correctly.",
- osf.getType().equals(int.class));
- assertFalse("Test 3: Unshared member not set correctly.",
- osf.isUnshared());
-
- // Repeat the tests with a different object to make sure
- // that we have not tested against default values.
- osf = new ObjectStreamField("anotherField", String.class, true);
- assertTrue("Test 4: Name member not set correctly.",
- osf.getName().equals("anotherField"));
- assertTrue("Test 5: Type member not set correctly.",
- osf.getType().equals(String.class));
- assertTrue("Test 6: Unshared member not set correctly.",
- osf.isUnshared());
-
- // Invalid argument tests.
- try {
- osf = new ObjectStreamField(null, boolean.class);
- fail("Test 7: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
- try {
- osf = new ObjectStreamField("thisField", null);
- fail("Test 8: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.ObjectStreamField#compareTo(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.lang.Object.class}
- )
- public void test_compareToLjava_lang_Object() {
- // Test for method int
- // java.io.ObjectStreamField.compareTo(java.lang.Object)
- assertTrue("Object compared to int did not return > 0", holaField
- .compareTo(hamField) > 0);
- assertEquals("Int compared to itself did not return 0", 0, hamField
- .compareTo(hamField));
- assertTrue("(Int)ham compared to (Int)sam did not return < 0", hamField
- .compareTo(samField) < 0);
- }
-
- /**
- * @tests java.io.ObjectStreamField#getName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getName",
- args = {}
- )
- public void test_getName() {
- // Test for method java.lang.String java.io.ObjectStreamField.getName()
- assertEquals("Field did not return correct name", "hola", holaField.getName());
- }
-
- /**
- * @tests java.io.ObjectStreamField#getOffset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getOffset",
- args = {}
- )
- public void test_getOffset() {
- // Test for method int java.io.ObjectStreamField.getOffset()
- ObjectStreamField[] osfArray;
- osfArray = osc.getFields();
- int[] expectedOffsets = {0, 1, 9, 11, 19, 23, 27, 31, 39, 41, 0};
-
- assertTrue("getOffset() did not return reasonable values.", osfArray[0]
- .getOffset() != osfArray[1].getOffset());
-
- for (int i = 0; i < expectedOffsets.length; i++) {
- assertEquals(String.format("Unexpected value for osfArray[%d].getOffset(): ", i),
- expectedOffsets[i], osfArray[i].getOffset());
-
- }
- }
-
- /**
- * @tests java.io.ObjectStreamField#getType()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getType",
- args = {}
- )
- public void test_getType() {
- // Test for method java.lang.Class java.io.ObjectStreamField.getType()
- assertTrue("getType on an Object field did not answer Object",
- holaField.getType().equals(Object.class));
- }
-
- /**
- * @tests java.io.ObjectStreamField#getTypeCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTypeCode",
- args = {}
- )
- public void test_getTypeCode() {
- // Test for method char java.io.ObjectStreamField.getTypeCode()
- assertEquals("getTypeCode on an Object field did not answer 'L'",
- 'L', holaField.getTypeCode());
- assertEquals("getTypeCode on a long field did not answer 'J'", 'J', bamField
- .getTypeCode());
- }
-
- /**
- * @tests java.io.ObjectStreamField#getTypeString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTypeString",
- args = {}
- )
- public void test_getTypeString() {
- assertTrue("getTypeString returned: " + holaField.getTypeString(),
- holaField.getTypeString().indexOf("Object") >= 0);
- assertNull("Primitive types' strings should be null", hamField.getTypeString());
-
- ObjectStreamField osf = new ObjectStreamField("s", String.class, true);
- assertTrue(osf.getTypeString() == "Ljava/lang/String;");
- }
-
- /**
- * @tests java.io.ObjectStreamField#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.io.ObjectStreamField.toString()
- assertTrue("toString on a long returned: " + bamField.toString(),
- bamField.toString().indexOf("bam") >= 0);
- }
-
- /**
- * @tests java.io.ObjectStreamField#getType()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getType",
- args = {}
- )
- public void test_getType_Deserialized() throws IOException,
- ClassNotFoundException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
- ObjectOutputStream oos = new ObjectOutputStream(baos);
- oos.writeObject(new SerializableObject());
- oos.close();
- baos.close();
-
- byte[] bytes = baos.toByteArray();
- ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
- ObjectInputStream ois = new ObjectInputStream(bais);
- SerializableObject obj = (SerializableObject) ois.readObject();
-
- ObjectStreamClass oc = obj.getObjectStreamClass();
- ObjectStreamField field = oc.getField("i");
- assertEquals(Object.class, field.getType());
- }
-
- /**
- * @tests java.io.ObjectStreamField#setOffset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setOffset",
- args = {int.class}
- )
- public void test_setOffsetI() {
- MyObjectStreamField f = new MyObjectStreamField("aField", int.class);
- f.setOffset(42);
- assertEquals("Test 1: Unexpected offset value.", 42, f.getOffset());
- f.setOffset(2008);
- assertEquals("Test 2: Unexpected offset value.", 2008, f.getOffset());
- }
-
- /**
- * @tests java.io.ObjectStreamField#getType()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getType",
- args = {}
- )
- public void test_getType_MockObjectInputStream() throws IOException, ClassNotFoundException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
- ObjectOutputStream oos = new ObjectOutputStream(baos);
- oos.writeObject(new SerializableObject());
- oos.close();
- baos.close();
-
- byte[] bytes = baos.toByteArray();
- ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
- MockObjectInputStream ois = new MockObjectInputStream(bais);
- ois.readObject();
-
- ObjectStreamClass oc = ois.getObjectStreamClass();
- ObjectStreamField field = oc.getField("i");
- assertEquals(Object.class, field.getType());
- }
-
- /**
- * @tests java.io.ObjectStreamField#isPrimitive()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isPrimitive",
- args = {}
- )
- public void test_isPrimitive() {
- // Test for method int java.io.ObjectStreamField.getOffset()
- ObjectStreamField[] osfArray;
- osfArray = osc.getFields();
-
- for (int i = 0; i < (osfArray.length - 1); i++) {
- assertTrue(String.format("osfArray[%d].isPrimitive() should return true.", i),
- osfArray[i].isPrimitive());
- }
- assertFalse(String.format("osfArray[%d].isPrimitive() should return false.",
- osfArray.length - 1),
- osfArray[(osfArray.length - 1)].isPrimitive());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isUnshared",
- args = {}
- )
- public void test_isUnshared() throws Exception {
- SerializableObject2 obj = new SerializableObject2();
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
- ObjectOutputStream oos = new ObjectOutputStream(baos);
- oos.writeObject(obj);
- oos.close();
- baos.close();
- byte[] bytes = baos.toByteArray();
- ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
- ObjectInputStream ois = new ObjectInputStream(bais);
- SerializableObject2 newObj = (SerializableObject2) ois.readObject();
-
- ObjectInputStream.GetField getField = newObj.getGetField();
- ObjectStreamClass objectStreamClass = getField.getObjectStreamClass();
-
- assertTrue(objectStreamClass.getField("i").isUnshared());
- assertFalse(objectStreamClass.getField("d").isUnshared());
- assertTrue(objectStreamClass.getField("s").isUnshared());
-
- assertEquals(1000, getField.get("i", null));
- assertEquals(SerializableObject2.today, getField.get("d", null));
- assertEquals("Richard", getField.get("s", null));
-
- assertTrue(objectStreamClass.getField("s").getTypeString() == "Ljava/lang/String;");
-
- assertEquals(0, objectStreamClass.getField("d").getOffset());
- assertEquals(1, objectStreamClass.getField("i").getOffset());
- assertEquals(2, objectStreamClass.getField("s").getOffset());
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- osc = ObjectStreamClass.lookup(DummyClass.class);
- bamField = osc.getField("bam");
- samField = osc.getField("sam");
- hamField = osc.getField("ham");
- holaField = osc.getField("hola");
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
-
-class SerializableObject implements Serializable {
- public ObjectInputStream.GetField getField = null;
-
- private static final long serialVersionUID = -2953957835918368056L;
-
- public Date d;
-
- public Integer i;
-
- public Exception e;
-
- public SerializableObject() {
- d = new Date();
- i = new Integer(1);
- e = new Exception("e");
- }
-
- private void writeObject(ObjectOutputStream o) throws IOException {
- o.putFields().put("d", new Date());
- o.putFields().put("i", new Integer(11));
- o.writeFields();
- }
-
- private void readObject(ObjectInputStream in) throws NotActiveException,
- IOException, ClassNotFoundException {
- getField = in.readFields();
- d = (Date) getField.get("d", null);
- i = (Integer) getField.get("i", null);
- }
-
- public ObjectStreamClass getObjectStreamClass() {
- return getField.getObjectStreamClass();
- }
-}
-
-class MockObjectInputStream extends ObjectInputStream {
- private ObjectStreamClass temp = null;
-
- public MockObjectInputStream() throws SecurityException, IOException {
- super();
- }
-
- public MockObjectInputStream(InputStream in)
- throws StreamCorruptedException, IOException {
- super(in);
- }
-
- public ObjectStreamClass readClassDescriptor() throws IOException,
- ClassNotFoundException {
- ObjectStreamClass osc = super.readClassDescriptor();
- //To get the ObjectStreamClass of SerializableObject
- if (osc.getSerialVersionUID() == -2953957835918368056L) {
- temp = osc;
- }
- return osc;
- }
-
- public ObjectStreamClass getObjectStreamClass() {
- return temp;
- }
-}
-
-class SerializableObject2 implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("i", Integer.class, true),
- new ObjectStreamField("d", Date.class, false),
- new ObjectStreamField("s", String.class, true),
- };
-
- private ObjectInputStream.GetField getField;
-
- public static Date today = new Date(1172632429156l);
-
- public ObjectInputStream.GetField getGetField() {
- return getField;
- }
-
- private void writeObject(ObjectOutputStream o) throws IOException {
- ObjectOutputStream.PutField putField = o.putFields();
- putField.put("i", new Integer(1000));
- putField.put("d", today);
- putField.put("s", "Richard");
- o.writeFields();
- }
-
- private void readObject(ObjectInputStream in) throws NotActiveException,
- IOException, ClassNotFoundException {
- getField = in.readFields();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/OpenRandomFileTest.java b/luni/src/test/java/tests/api/java/io/OpenRandomFileTest.java
deleted file mode 100644
index af2f3ab..0000000
--- a/luni/src/test/java/tests/api/java/io/OpenRandomFileTest.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/* 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 tests.api.java.io;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.RandomAccessFile;
-
-import junit.framework.TestCase;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-/**
- * TODO Type description
- */
-@TestTargetClass(RandomAccessFile.class)
-public class OpenRandomFileTest extends TestCase {
-
- public static void main(String[] args) {
- new OpenRandomFileTest().testOpenEmptyFile();
- }
-
- public OpenRandomFileTest() {
- super();
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "RandomAccessFile",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void testOpenNonEmptyFile() {
- try {
- File file = File.createTempFile("test", "tmp");
- assertTrue(file.exists());
- file.deleteOnExit();
- FileOutputStream fos = new FileOutputStream(file);
- fos.write(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
- fos.close();
-
- String fileName = file.getCanonicalPath();
- RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
- raf.close();
- } catch (IOException ex) {
- fail(ex.getLocalizedMessage());
- }
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "RandomAccessFile",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void testOpenEmptyFile() {
- try {
- File file = File.createTempFile("test", "tmp");
- assertTrue(file.exists());
- file.deleteOnExit();
-
- String fileName = file.getCanonicalPath();
- RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
- raf.close();
- } catch (IOException ex) {
- fail(ex.getLocalizedMessage());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/OutputStreamTest.java b/luni/src/test/java/tests/api/java/io/OutputStreamTest.java
deleted file mode 100644
index 2dac610..0000000
--- a/luni/src/test/java/tests/api/java/io/OutputStreamTest.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.OutputStream;
-import java.io.IOException;
-
-@TestTargetClass(
- value = OutputStream.class,
- untestedMethods = {
- @TestTargetNew(
- method = "OutputStream",
- args = {},
- level = TestLevel.NOT_NECESSARY,
- notes = "Constructor just calls super()."
- ),
- @TestTargetNew(
- method = "close",
- args = {},
- level = TestLevel.NOT_NECESSARY,
- notes = "According to specification, the implementation " +
- "does nothing."
- ),
- @TestTargetNew(
- method = "flush",
- args = {},
- level = TestLevel.NOT_NECESSARY,
- notes = "According to specification, the implementation " +
- "does nothing."
- )
- }
-)
-public class OutputStreamTest extends junit.framework.TestCase {
-
- class BasicOutputStream extends OutputStream {
-
- private static final int BUFFER_SIZE = 20;
- private byte[] buffer;
- private int position;
-
- public BasicOutputStream() {
- buffer = new byte[BUFFER_SIZE];
- position = 0;
- }
-
- public void write(int oneByte) throws IOException {
- if (position < BUFFER_SIZE) {
- buffer[position] = (byte) (oneByte & 255);
- position++;
- } else {
- throw new IOException("Internal buffer overflow.");
- }
- }
-
- public byte[] getBuffer() {
- return buffer;
- }
- }
-
- private final byte[] shortByteArray = "Lorem ipsum...".getBytes();
- private final byte[] longByteArray = "Lorem ipsum dolor sit amet...".getBytes();
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies write(byte[]).",
- method = "write",
- args = {byte[].class}
- )
- public void test_write$B() {
- BasicOutputStream bos = new BasicOutputStream();
- boolean expected;
- byte[] buffer;
-
- try {
- bos.write(shortByteArray);
- } catch (IOException e) {
- fail("Test 1: Unexpected IOException encountered.");
- }
-
- expected = true;
- buffer = bos.getBuffer();
- for (int i = 0; i < (shortByteArray.length) && expected; i++) {
- expected = (shortByteArray[i] == buffer[i]);
- }
- assertTrue("Test 1: Test byte array has not been written correctly.",
- expected);
-
- try {
- bos.write(longByteArray);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {}
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies write(byte[], int, int).",
- method = "write",
- args = {byte[].class, int.class, int.class}
- )
- public void test_write$BII() {
- BasicOutputStream bos = new BasicOutputStream();
- boolean expected;
- byte[] buffer;
-
- try {
- bos.write(shortByteArray, 6, 5);
- } catch (IOException e) {
- fail("Test 1: Unexpected IOException encountered.");
- }
-
- expected = true;
- buffer = bos.getBuffer();
- for (int i = 6, j = 0; j < 5 && expected; i++, j++) {
- expected = (shortByteArray[i] == buffer[j]);
- }
- assertTrue("Test 1: Test byte array has not been written correctly.",
- expected);
-
- try {
- bos.write(longByteArray, 5, 20);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {}
-
- try {
- bos.write(longByteArray, -1, 10);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- } catch (IOException e) {
- fail("Test 3: Unexpected IOException encountered.");
- }
-
- try {
- bos.write(longByteArray, 10, -1);
- fail("Test 4: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- } catch (IOException e) {
- fail("Test 4: Unexpected IOException encountered.");
- }
-
- try {
- bos.write(longByteArray, 20, 10);
- fail("Test 5: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- } catch (IOException e) {
- fail("Test 5: Unexpected IOException encountered.");
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/OutputStreamWriterTest.java b/luni/src/test/java/tests/api/java/io/OutputStreamWriterTest.java
deleted file mode 100644
index 3f5fc68..0000000
--- a/luni/src/test/java/tests/api/java/io/OutputStreamWriterTest.java
+++ /dev/null
@@ -1,786 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
-import java.io.UnsupportedEncodingException;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetEncoder;
-
-import tests.support.Support_OutputStream;
-
-import junit.framework.TestCase;
-
-/**
- *
- */
-@TestTargetClass(OutputStreamWriter.class)
-public class OutputStreamWriterTest extends TestCase {
-
- private static final int UPPER = 0xd800;
-
- private static final int BUFFER_SIZE = 10000;
-
- static private final String[] MINIMAL_CHARSETS = new String[] { "US-ASCII",
- "ISO-8859-1", "UTF-16BE", "UTF-16LE", "UTF-16", "UTF-8" };
-
- OutputStreamWriter osw;
-
- InputStreamReader isr;
-
- private Support_OutputStream fos;
-
- public String testString = "This is a test message with Unicode characters. \u4e2d\u56fd is China's name in Chinese";
-
- /*
- * @see TestCase#setUp()
- */
- protected void setUp() throws Exception {
- super.setUp();
- fos = new Support_OutputStream(500);
- osw = new OutputStreamWriter(fos, "UTF-8");
- }
-
- /*
- * @see TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- try {
- if (isr != null) isr.close();
- osw.close();
- } catch (Exception e) {
- }
-
- super.tearDown();
- }
-
- /**
- * @tests java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "OutputStreamWriter",
- args = {java.io.OutputStream.class}
- )
- public void test_ConstructorLjava_io_OutputStream() throws IOException {
- OutputStreamWriter writer = null;
-
- try {
- writer = new OutputStreamWriter(null);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected
- }
-
- try {
- writer = new OutputStreamWriter(new Support_OutputStream());
- } catch (Exception e) {
- fail("Test 2: Unexpected exception: " + e.getMessage());
- }
-
- // Test that the default encoding has been used.
- assertEquals("Test 3: Incorrect default encoding used.",
- Charset.defaultCharset(),
- Charset.forName(writer.getEncoding()));
-
- if (writer != null) writer.close();
- }
-
- /**
- * @tests java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "OutputStreamWriter",
- args = {java.io.OutputStream.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_io_OutputStreamLjava_lang_String()
- throws UnsupportedEncodingException {
-
- try {
- osw = new OutputStreamWriter(null, "utf-8");
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected
- }
-
- try {
- osw = new OutputStreamWriter(fos, (String) null);
- fail("Test 2: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected
- }
-
- try {
- osw = new OutputStreamWriter(fos, "");
- fail("Test 3: UnsupportedEncodingException expected.");
- } catch (UnsupportedEncodingException e) {
- // Expected
- }
-
- try {
- osw = new OutputStreamWriter(fos, "Bogus");
- fail("Test 4: UnsupportedEncodingException expected.");
- } catch (UnsupportedEncodingException e) {
- // Expected
- }
-
- try {
- osw = new OutputStreamWriter(fos, "8859_1");
- } catch (UnsupportedEncodingException e) {
- fail("Test 5: Unexpected UnsupportedEncodingException.");
- }
-
- assertEquals("Test 6: Encoding not set correctly. ",
- Charset.forName("8859_1"),
- Charset.forName(osw.getEncoding()));
- }
-
- /**
- * @tests java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream,
- * java.nio.charset.Charset)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "OutputStreamWriter",
- args = {java.io.OutputStream.class, java.nio.charset.Charset.class}
- )
- public void test_ConstructorLjava_io_OutputStreamLjava_nio_charset_Charset()
- throws IOException {
- OutputStreamWriter writer;
- Support_OutputStream out = new Support_OutputStream();
- Charset cs = Charset.forName("ascii");
-
- try {
- writer = new OutputStreamWriter(null, cs);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected
- }
-
- try {
- writer = new OutputStreamWriter(out, (Charset) null);
- fail("Test 2: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected
- }
-
- writer = new OutputStreamWriter(out, cs);
- assertEquals("Test 3: Encoding not set correctly. ",
- cs, Charset.forName(writer.getEncoding()));
- writer.close();
- }
-
- /**
- * @tests java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream,
- * java.nio.charset.CharsetEncoder)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "OutputStreamWriter",
- args = {java.io.OutputStream.class, java.nio.charset.CharsetEncoder.class}
- )
- public void test_ConstructorLjava_io_OutputStreamLjava_nio_charset_CharsetEncoder()
- throws IOException {
- OutputStreamWriter writer;
- Support_OutputStream out = new Support_OutputStream();
- Charset cs = Charset.forName("ascii");
- CharsetEncoder enc = cs.newEncoder();
-
- try {
- writer = new OutputStreamWriter(null, enc);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected
- }
-
- try {
- writer = new OutputStreamWriter(out, (CharsetEncoder) null);
- fail("Test 2: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected
- }
-
- writer = new OutputStreamWriter(out, cs);
- assertEquals("Test 3: CharacterEncoder not set correctly. ",
- cs, Charset.forName(writer.getEncoding()));
- writer.close();
- }
-
- /**
- * @tests java.io.OutputStreamWriter#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "An issue in the API code has been identified (ticket #87). This test must be updated when the ticket is closed.",
- method = "close",
- args = {}
- )
- public void test_close() {
-
- fos.setThrowsException(true);
- try {
- osw.close();
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
-/* Test 2 does not work and has therefore been disabled (see Ticket #87).
- // Test 2: Write should not fail since the closing
- // in test 1 has not been successful.
- try {
- osw.write("Lorem ipsum...");
- } catch (IOException e) {
- fail("Test 2: Unexpected IOException.");
- }
-
- // Test 3: Close should succeed.
- fos.setThrowsException(false);
- try {
- osw.close();
- } catch (IOException e) {
- fail("Test 3: Unexpected IOException.");
- }
-*/
-
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
- try {
- OutputStreamWriter writer = new OutputStreamWriter(bout,
- "ISO2022JP");
- writer.write(new char[] { 'a' });
- writer.close();
- // The default is ASCII, there should not be any mode changes.
- String converted = new String(bout.toByteArray(), "ISO8859_1");
- assertTrue("Test 4: Invalid conversion: " + converted,
- converted.equals("a"));
-
- bout.reset();
- writer = new OutputStreamWriter(bout, "ISO2022JP");
- writer.write(new char[] { '\u3048' });
- writer.flush();
- // The byte sequence should not switch to ASCII mode until the
- // stream is closed.
- converted = new String(bout.toByteArray(), "ISO8859_1");
- assertTrue("Test 5: Invalid conversion: " + converted,
- converted.equals("\u001b$B$("));
- writer.close();
- converted = new String(bout.toByteArray(), "ISO8859_1");
- assertTrue("Test 6: Invalid conversion: " + converted,
- converted.equals("\u001b$B$(\u001b(B"));
-
- bout.reset();
- writer = new OutputStreamWriter(bout, "ISO2022JP");
- writer.write(new char[] { '\u3048' });
- writer.write(new char[] { '\u3048' });
- writer.close();
- // There should not be a mode switch between writes.
- assertEquals("Test 7: Invalid conversion. ",
- "\u001b$B$($(\u001b(B",
- new String(bout.toByteArray(), "ISO8859_1"));
- } catch (UnsupportedEncodingException e) {
- // Can't test missing converter.
- System.out.println(e);
- } catch (IOException e) {
- fail("Unexpected: " + e);
- }
- }
-
- /**
- * @tests java.io.OutputStreamWriter#flush()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "flush",
- args = {}
- )
- public void test_flush() {
- // Test for method void java.io.OutputStreamWriter.flush()
- try {
- char[] buf = new char[testString.length()];
- osw.write(testString, 0, testString.length());
- osw.flush();
- openInputStream();
- isr.read(buf, 0, buf.length);
- assertTrue("Test 1: Characters have not been flushed.",
- new String(buf, 0, buf.length).equals(testString));
- } catch (Exception e) {
- fail("Test 1: Unexpected exception: " + e.getMessage());
- }
-
- fos.setThrowsException(true);
- try {
- osw.flush();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected
- }
- fos.setThrowsException(false);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {},
- clazz = InputStreamReader.class
- )
- })
- public void test_singleCharIO() throws Exception {
- int upper;
- OutputStreamWriter writer = null;
- ByteArrayOutputStream out;
- InputStreamReader isr = null;
-
- for (int i = 0; i < MINIMAL_CHARSETS.length; ++i) {
- try {
- out = new ByteArrayOutputStream();
- writer = new OutputStreamWriter(out, MINIMAL_CHARSETS[i]);
-
- switch (i) {
- case 0:
- upper = 128;
- break;
- case 1:
- upper = 256;
- break;
- default:
- upper = UPPER;
- }
-
- for (int c = 0; c < upper; ++c) {
- writer.write(c);
- }
- writer.flush();
- byte[] result = out.toByteArray();
-
- isr = new InputStreamReader(new ByteArrayInputStream(result),
- MINIMAL_CHARSETS[i]);
- for (int expected = 0; expected < upper; ++expected) {
- assertEquals("Error when reading bytes in "
- + MINIMAL_CHARSETS[i], expected, isr.read());
- }
- } finally {
- try {
- if (isr != null) isr.close();
- } catch (Exception e) {
- }
- try {
- if (writer != null) writer.close();
- } catch (Exception e) {
- }
- }
- }
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "write",
- args = {char[].class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {},
- clazz = InputStreamReader.class
- )
- })
- public void test_write$C() throws Exception {
- int upper;
- InputStreamReader isr = null;
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- OutputStreamWriter writer = null;
-
- char[] largeBuffer = new char[BUFFER_SIZE];
- for (int i = 0; i < MINIMAL_CHARSETS.length; ++i) {
- try {
- baos = new ByteArrayOutputStream();
- writer = new OutputStreamWriter(baos, MINIMAL_CHARSETS[i]);
-
- switch (i) {
- case 0:
- upper = 128;
- break;
- case 1:
- upper = 256;
- break;
- default:
- upper = UPPER;
- }
-
- int m = 0;
- for (int c = 0; c < upper; ++c) {
- largeBuffer[m++] = (char) c;
- if (m == BUFFER_SIZE) {
- writer.write(largeBuffer);
- m = 0;
- }
- }
- writer.write(largeBuffer, 0, m);
- writer.flush();
- byte[] result = baos.toByteArray();
-
- isr = new InputStreamReader(new ByteArrayInputStream(result),
- MINIMAL_CHARSETS[i]);
- int expected = 0, read = 0, j = 0;
- while (expected < upper) {
- if (j == read) {
- read = isr.read(largeBuffer);
- j = 0;
- }
- assertEquals("Error when reading bytes in "
- + MINIMAL_CHARSETS[i], expected++, largeBuffer[j++]);
- }
- } finally {
- try {
- if (isr != null) isr.close();
- } catch (Exception e) {
- }
- try {
- if (writer != null) writer.close();
- } catch (Exception e) {
- }
- }
- }
- }
-
- /**
- * @tests java.io.OutputStreamWriter#getEncoding()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getEncoding",
- args = {}
- )
- public void test_getEncoding() throws IOException {
- OutputStreamWriter writer;
- writer = new OutputStreamWriter(new Support_OutputStream(), "utf-8");
- assertEquals("Test 1: Incorrect encoding returned.",
- Charset.forName("utf-8"),
- Charset.forName(writer.getEncoding()));
-
- writer.close();
- assertNull("Test 2: getEncoding() did not return null for a closed writer.",
- writer.getEncoding());
- }
-
- /**
- * @tests java.io.OutputStreamWriter#write(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {char[].class, int.class, int.class}
- )
- public void test_write$CII() throws IOException {
- char[] chars = testString.toCharArray();
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- Support_OutputStream out = new Support_OutputStream(500);
- OutputStreamWriter writer;
-
- writer = new OutputStreamWriter(out, "utf-8");
-
- try {
- writer.write(chars, -1, 1);
- fail("Test 1: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- writer.write(chars, 0, -1);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- writer.write(new char[0], 0, 1);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- writer.write((char[]) null, 0, 1);
- fail("Test 4: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected
- }
-
- try {
- writer.write(chars, 1, chars.length);
- fail("Test 5a: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- writer.write(chars, 0, chars.length + 1);
- fail("Test 5b: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- writer.write(chars, chars.length, 1);
- fail("Test 5c: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- writer.write(chars, chars.length + 1, 0);
- fail("Test 5d: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- out.setThrowsException(true);
- try {
- for (int i = 0; i < 200; i++) {
- writer.write(chars, 0, chars.length);
- }
- fail("Test 6: IOException expected.");
- } catch (IOException e) {
- // Expected
- }
- out.setThrowsException(false);
-
- writer.close();
- writer = new OutputStreamWriter(baos, "utf-8");
- writer.write(chars, 1, 2);
- writer.flush();
- assertEquals("Test 7: write(char[], int, int) has not produced the " +
- "expected content in the output stream.",
- "hi", baos.toString("utf-8"));
-
- writer.write(chars, 0, chars.length);
- writer.flush();
- assertEquals("Test 8: write(char[], int, int) has not produced the " +
- "expected content in the output stream.",
- "hi" + testString, baos.toString("utf-8"));
-
- writer.close();
- try {
- writer.write((char[]) null, -1, -1);
- fail("Test 9: IOException expected.");
- } catch (IOException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.io.OutputStreamWriter#write(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {int.class}
- )
- public void test_writeI() throws IOException {
- Support_OutputStream out = new Support_OutputStream(500);
- OutputStreamWriter writer;
-
- out.setThrowsException(true);
- writer = new OutputStreamWriter(out, "utf-8");
- try {
- // Since there is an internal buffer in the encoder, more than
- // one character needs to be written.
- for (int i = 0; i < 200; i++) {
- for (int j = 0; j < testString.length(); j++) {
- writer.write(testString.charAt(j));
- }
- }
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected
- }
- out.setThrowsException(false);
- writer.close();
-
- writer = new OutputStreamWriter(out, "utf-8");
- writer.write(1);
- writer.flush();
- String str = new String(out.toByteArray(), "utf-8");
- assertEquals("Test 2: ", "\u0001", str);
-
- writer.write(2);
- writer.flush();
- str = new String(out.toByteArray(), "utf-8");
- assertEquals("Test 3: ", "\u0001\u0002", str);
-
- writer.write(-1);
- writer.flush();
- str = new String(out.toByteArray(), "utf-8");
- assertEquals("Test 4: ", "\u0001\u0002\uffff", str);
-
- writer.write(0xfedcb);
- writer.flush();
- str = new String(out.toByteArray(), "utf-8");
- assertEquals("Test 5: ", "\u0001\u0002\uffff\uedcb", str);
-
- writer.close();
- try {
- writer.write(1);
- fail("Test 6: IOException expected.");
- } catch (IOException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.io.OutputStreamWriter#write(java.lang.String, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {java.lang.String.class, int.class, int.class}
- )
- public void test_writeLjava_lang_StringII() throws IOException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- Support_OutputStream out = new Support_OutputStream(500);
- OutputStreamWriter writer;
-
- writer = new OutputStreamWriter(out, "utf-8");
-
- try {
- writer.write("Lorem", -1, 0);
- fail("Test 1: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- writer.write("Lorem", 0, -1);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- writer.write("", 0, 1);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- writer.write(testString, 1, testString.length());
- fail("Test 4a: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- writer.write(testString, 0, testString.length() + 1);
- fail("Test 4b: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- writer.write(testString, testString.length(), 1);
- fail("Test 4c: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- writer.write(testString, testString.length() + 1, 0);
- fail("Test 4d: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- writer.write((String) null, 0, 1);
- fail("Test 5: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected
- }
-
- out.setThrowsException(true);
- try {
- for (int i = 0; i < 200; i++) {
- writer.write(testString, 0, testString.length());
- }
- fail("Test 6: IOException expected.");
- } catch (IOException e) {
- // Expected
- }
- out.setThrowsException(false);
-
- writer.close();
- writer = new OutputStreamWriter(baos, "utf-8");
-
- writer.write("abc", 1, 2);
- writer.flush();
- assertEquals("Test 7: write(String, int, int) has not produced the " +
- "expected content in the output stream.",
- "bc", baos.toString("utf-8"));
-
- writer.write(testString, 0, testString.length());
- writer.flush();
- assertEquals("Test 7: write(String, int, int) has not produced the " +
- "expected content in the output stream.",
- "bc" + testString, baos.toString("utf-8"));
-
- writer.close();
- try {
- writer.write("abc", 0, 1);
- fail("Test 8: IOException expected.");
- } catch (IOException e) {
- // Expected
- }
- }
-
- private void openInputStream() {
- try {
- isr = new InputStreamReader(new ByteArrayInputStream(fos.toByteArray()), "UTF-8");
- } catch (UnsupportedEncodingException e) {
- fail("UTF-8 not supported");
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/io/PipedInputStreamTest.java b/luni/src/test/java/tests/api/java/io/PipedInputStreamTest.java
deleted file mode 100644
index 1f35f97..0000000
--- a/luni/src/test/java/tests/api/java/io/PipedInputStreamTest.java
+++ /dev/null
@@ -1,528 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.IOException;
-import java.io.PipedInputStream;
-import java.io.PipedOutputStream;
-
-import dalvik.annotation.BrokenTest;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(PipedInputStream.class)
-public class PipedInputStreamTest extends junit.framework.TestCase {
-
- static class PWriter implements Runnable {
- PipedOutputStream pos;
-
- public byte bytes[];
-
- public void run() {
- try {
- pos.write(bytes);
- synchronized (this) {
- notify();
- }
- } catch (Exception e) {
- e.printStackTrace(System.out);
- System.out.println("Error while running the writer thread.");
- }
- }
-
- public PWriter(PipedOutputStream pout, int nbytes) {
- pos = pout;
- bytes = new byte[nbytes];
- for (int i = 0; i < bytes.length; i++)
- bytes[i] = (byte) (System.currentTimeMillis() % 9);
- }
- }
-
- static class PWriter2 implements Runnable {
- PipedOutputStream pos;
-
- public boolean keepRunning = true;
-
- public void run() {
- try {
- pos.write(42);
- pos.close();
- while (keepRunning) {
- Thread.sleep(1000);
- }
- } catch (Exception e) {
- e.printStackTrace(System.out);
- System.out.println("Error while running the writer thread.");
- }
- }
-
- public PWriter2(PipedOutputStream pout) {
- pos = pout;
- }
- }
-
- Thread t;
-
- PWriter pw;
-
- PipedInputStream pis;
-
- PipedOutputStream pos;
-
- /**
- * @tests java.io.PipedInputStream#PipedInputStream()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PipedInputStream",
- args = {}
- )
- public void test_Constructor() throws IOException {
- pis = new PipedInputStream();
- assertEquals("There should not be any bytes available. ", 0, pis.available());
- pis.close();
- }
-
- /**
- * @tests java.io.PipedInputStream#PipedInputStream(java.io.PipedOutputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PipedInputStream",
- args = {java.io.PipedOutputStream.class}
- )
- public void test_ConstructorLjava_io_PipedOutputStream() throws IOException {
- pos = new PipedOutputStream(new PipedInputStream());
-
- try {
- pis = new PipedInputStream(pos);
- fail("IOException expected since the output stream is already connected.");
- } catch (IOException e) {
- // Expected.
- }
-
- pis = new PipedInputStream(new PipedOutputStream());
- assertEquals("There should not be any bytes available. ", 0, pis.available());
-
- pis.close();
- pos.close();
- }
-
- /**
- * @tests java.io.PipedInputStream#available()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "No IOException checking because it is never thrown in the source code.",
- method = "available",
- args = {}
- )
- public void test_available() throws Exception {
- // Test for method int java.io.PipedInputStream.available()
- pis = new PipedInputStream();
- pos = new PipedOutputStream();
-
- pis.connect(pos);
- t = new Thread(pw = new PWriter(pos, 1000));
- t.start();
-
- synchronized (pw) {
- pw.wait(10000);
- }
- assertEquals("Test 1: Incorrect number of bytes available. ",
- 1000, pis.available());
-
- PipedInputStream pin = new PipedInputStream();
- PipedOutputStream pout = new PipedOutputStream(pin);
- // We know the PipedInputStream buffer size is 1024.
- // Writing another byte would cause the write to wait
- // for a read before returning
- for (int i = 0; i < 1024; i++)
- pout.write(i);
- assertEquals("Test 2: Incorrect number of bytes available. ",
- 1024 , pin.available());
- }
-
- /**
- * @tests java.io.PipedInputStream#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "No IOException checking because it is never thrown in the source code.",
- method = "close",
- args = {}
- )
- public void test_close() throws IOException {
- // Test for method void java.io.PipedInputStream.close()
- pis = new PipedInputStream();
- pos = new PipedOutputStream();
- pis.connect(pos);
- pis.close();
- try {
- pos.write((byte) 127);
- fail("IOException expected.");
- } catch (IOException e) {
- // The spec for PipedInput says an exception should be thrown if
- // a write is attempted to a closed input. The PipedOuput spec
- // indicates that an exception should be thrown only when the
- // piped input thread is terminated without closing
- return;
- }
- }
-
- /**
- * @tests java.io.PipedInputStream#connect(java.io.PipedOutputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "connect",
- args = {java.io.PipedOutputStream.class}
- )
- public void test_connectLjava_io_PipedOutputStream() throws Exception {
- // Test for method void
- // java.io.PipedInputStream.connect(java.io.PipedOutputStream)
- pis = new PipedInputStream();
- pos = new PipedOutputStream();
- assertEquals("Test 1: Not-connected pipe returned more than zero available bytes. ",
- 0, pis.available());
-
- pis.connect(pos);
- t = new Thread(pw = new PWriter(pos, 1000));
- t.start();
-
- synchronized (pw) {
- pw.wait(10000);
- }
- assertEquals("Test 2: Unexpected number of bytes available. ",
- 1000, pis.available());
-
- try {
- pis.connect(pos);
- fail("Test 3: IOException expected when reconnecting the pipe.");
- } catch (IOException e) {
- // Expected.
- }
-
- pis.close();
- pos.close();
- }
-
- /**
- * @tests java.io.PipedInputStream#read()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {}
- )
- public void test_read() throws Exception {
- pis = new PipedInputStream();
- pos = new PipedOutputStream();
-
- try {
- pis.read();
- fail("Test 1: IOException expected since the stream is not connected.");
- } catch (IOException e) {
- // Expected.
- }
-
- pis.connect(pos);
- t = new Thread(pw = new PWriter(pos, 100));
- t.start();
-
- synchronized (pw) {
- pw.wait(5000);
- }
- assertEquals("Test 2: Unexpected number of bytes available. ",
- 100, pis.available());
-
- for (int i = 0; i < 100; i++) {
- assertEquals("Test 3: read() returned incorrect byte. ",
- pw.bytes[i], (byte) pis.read());
- }
-
- try {
- pis.read();
- fail("Test 4: IOException expected since the thread that has " +
- "written to the pipe is no longer alive.");
- } catch (IOException e) {
- // Expected.
- }
-
- pis.close();
- try {
- pis.read();
- fail("Test 5: IOException expected since the stream is closed.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.PipedInputStream#read()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks that read returns -1 if the PipedOutputStream connected to this PipedInputStream is closed.",
- method = "read",
- args = {}
- )
- public void test_read_2() throws Exception {
- Thread writerThread;
- PWriter2 pwriter;
-
- pos = new PipedOutputStream();
- pis = new PipedInputStream(pos);
- writerThread = new Thread(pwriter = new PWriter2(pos));
- writerThread.start();
-
- synchronized (pwriter) {
- pwriter.wait(5000);
- }
- pis.read();
- assertEquals("Test 1: No more data indication expected. ", -1, pis.read());
- pwriter.keepRunning = false;
-
- pis.close();
- }
-
- /**
- * @tests java.io.PipedInputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Tests read from unconnected, connected and closed pipe.",
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII() throws Exception {
- byte[] buf = new byte[400];
- pis = new PipedInputStream();
- pos = new PipedOutputStream();
-
- try {
- pis.read(buf, 0, 10);
- fail("Test 1: IOException expected since the stream is not connected.");
- } catch (IOException e) {
- // Expected.
- }
-
- pis.connect(pos);
- t = new Thread(pw = new PWriter(pos, 1000));
- t.start();
-
- synchronized (pw) {
- pw.wait(10000);
- }
- assertEquals("Test 2: Unexpected number of bytes available. ",
- 1000, pis.available());
- pis.read(buf, 0, 400);
- for (int i = 0; i < 400; i++) {
- assertEquals("Test 3: read() returned incorrect byte. ",
- pw.bytes[i], buf[i]);
- }
-
- pis.close();
- try {
- pis.read(buf, 0, 10);
- fail("Test 4: IOException expected since the stream is closed.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.PipedInputStream#read(byte[], int, int)
- * Regression for HARMONY-387
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Tests illegal length argument.",
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII_2() throws IOException {
- PipedInputStream obj = new PipedInputStream();
- try {
- obj.read(new byte[0], 0, -1);
- fail("IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException t) {
- assertEquals(
- "IndexOutOfBoundsException rather than a subclass expected.",
- IndexOutOfBoundsException.class, t.getClass());
- }
- }
-
- /**
- * @tests java.io.PipedInputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Tests illegal offset argument.",
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII_3() throws IOException {
- PipedInputStream obj = new PipedInputStream();
- try {
- obj.read(new byte[10], -1, 1);
- fail("IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- assertTrue(e.getClass().equals(IndexOutOfBoundsException.class));
- }
- try {
- obj.read(new byte[10], 0, -1);
- fail("IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- assertTrue(e.getClass().equals(IndexOutOfBoundsException.class));
- }
- try {
- obj.read(new byte[10], 9, 2);
- fail("IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- assertTrue(e.getClass().equals(IndexOutOfBoundsException.class));
- }
- }
-
- /**
- * @tests java.io.PipedInputStream#receive(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "receive",
- args = {int.class}
- )
- @BrokenTest("Test hangs indefinitely on the RI")
- public void test_receive() throws IOException {
- pis = new PipedInputStream();
- pos = new PipedOutputStream();
-
- // test if writer recognizes dead reader
- pis.connect(pos);
- class WriteRunnable implements Runnable {
-
- boolean pass = false;
-
- boolean readerAlive = true;
-
- public void run() {
- try {
- pos.write(1);
- while (readerAlive)
- ;
- try {
- // should throw exception since reader thread
- // is now dead
- pos.write(1);
- } catch (IOException e) {
- pass = true;
- }
- } catch (IOException e) {}
- }
- }
- WriteRunnable writeRunnable = new WriteRunnable();
- Thread writeThread = new Thread(writeRunnable);
- class ReadRunnable implements Runnable {
-
- boolean pass;
-
- public void run() {
- try {
- pis.read();
- pass = true;
- } catch (IOException e) {}
- }
- }
- ;
- ReadRunnable readRunnable = new ReadRunnable();
- Thread readThread = new Thread(readRunnable);
- writeThread.start();
- readThread.start();
- while (readThread.isAlive())
- ;
- writeRunnable.readerAlive = false;
- assertTrue("reader thread failed to read", readRunnable.pass);
- while (writeThread.isAlive())
- ;
- assertTrue("writer thread failed to recognize dead reader",
- writeRunnable.pass);
-
- // attempt to write to stream after writer closed
- pis = new PipedInputStream();
- pos = new PipedOutputStream();
-
- pis.connect(pos);
- class MyRunnable implements Runnable {
-
- boolean pass;
-
- public void run() {
- try {
- pos.write(1);
- } catch (IOException e) {
- pass = true;
- }
- }
- }
- MyRunnable myRun = new MyRunnable();
- synchronized (pis) {
- t = new Thread(myRun);
- // thread t will be blocked inside pos.write(1)
- // when it tries to call the synchronized method pis.receive
- // because we hold the monitor for object pis
- t.start();
- try {
- // wait for thread t to get to the call to pis.receive
- Thread.sleep(100);
- } catch (InterruptedException e) {}
- // now we close
- pos.close();
- }
- // we have exited the synchronized block, so now thread t will make
- // a call to pis.receive AFTER the output stream was closed,
- // in which case an IOException should be thrown
- while (t.isAlive()) {
- ;
- }
- assertTrue(
- "write failed to throw IOException on closed PipedOutputStream",
- myRun.pass);
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() throws Exception {
- try {
- if (t != null) {
- t.interrupt();
- }
- } catch (Exception ignore) {
- }
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/PipedOutputStreamTest.java b/luni/src/test/java/tests/api/java/io/PipedOutputStreamTest.java
deleted file mode 100644
index 44d7e27..0000000
--- a/luni/src/test/java/tests/api/java/io/PipedOutputStreamTest.java
+++ /dev/null
@@ -1,339 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.IOException;
-import java.io.PipedInputStream;
-import java.io.PipedOutputStream;
-
-@TestTargetClass(PipedOutputStream.class)
-public class PipedOutputStreamTest extends junit.framework.TestCase {
-
- static class PReader implements Runnable {
- PipedInputStream reader;
-
- public PipedInputStream getReader() {
- return reader;
- }
-
- public PReader(PipedOutputStream out) {
- try {
- reader = new PipedInputStream(out);
- } catch (Exception e) {
- System.out.println("Exception setting up reader: "
- + e.toString());
- }
- }
-
- public int available() {
- try {
- return reader.available();
- } catch (Exception e) {
- return -1;
- }
- }
-
- public void run() {
- try {
- while (true) {
- Thread.sleep(1000);
- Thread.yield();
- }
- } catch (InterruptedException e) {
- }
- }
-
- public String read(int nbytes) {
- byte[] buf = new byte[nbytes];
- try {
- reader.read(buf, 0, nbytes);
- return new String(buf);
- } catch (IOException e) {
- System.out.println("Exception reading ("
- + Thread.currentThread().getName() + "): "
- + e.toString());
- return "ERROR";
- }
- }
- }
-
- static final String testString = "Lorem ipsum dolor sit amet,\n" +
- "consectetur adipisicing elit,\nsed do eiusmod tempor incididunt ut" +
- "labore et dolore magna aliqua.\n";
- static final int testLength = testString.length();
-
- Thread rt;
-
- PReader reader;
-
- PipedOutputStream out;
-
- /**
- * @tests java.io.PipedOutputStream#PipedOutputStream()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PipedOutputStream",
- args = {}
- )
- public void test_Constructor() {
- out = new PipedOutputStream();
- assertNotNull(out);
- try {
- out.close();
- } catch (IOException e) {
- fail("Unexpeceted IOException.");
- }
- }
-
- /**
- * @tests java.io.PipedOutputStream#PipedOutputStream(java.io.PipedInputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PipedOutputStream",
- args = {java.io.PipedInputStream.class}
- )
- public void test_ConstructorLjava_io_PipedInputStream() throws IOException {
- // Test for method java.io.PipedOutputStream(java.io.PipedInputStream)
-
- try {
- out = new PipedOutputStream(new PipedInputStream());
- out.write('b');
- } catch (Exception e) {
- fail("Test 1: Constructor failed: " + e.getMessage());
- }
- out.close();
-
- PipedInputStream pis = new PipedInputStream(new PipedOutputStream());
- try {
- out = new PipedOutputStream(pis);
- fail("Test 2: IOException expected because the input stream is already connected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.PipedOutputStream#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "close",
- args = {}
- )
- public void test_close() {
- out = new PipedOutputStream();
- rt = new Thread(reader = new PReader(out));
- rt.start();
- try {
- out.close();
- } catch (IOException e) {
- fail("Test 1: Unexpected IOException: " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.PipedOutputStream#connect(java.io.PipedInputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "connect",
- args = {java.io.PipedInputStream.class}
- )
- public void test_connectLjava_io_PipedInputStream() throws IOException {
- out = new PipedOutputStream();
-
- try {
- out.connect(new PipedInputStream());
- } catch (Exception e) {
- fail("Test 1: Unexpected exception when connecting: " +
- e.getLocalizedMessage());
- }
-
- try {
- out.write('B');
- } catch (IOException e) {
- fail("Test 2: Unexpected IOException when writing after connecting.");
- }
-
- try {
- out.connect(new PipedInputStream());
- fail("Test 3: IOException expected when reconnecting the stream.");
- } catch (IOException e) {
- // Expected.
- }
-
- try {
- out.connect(null);
- fail("Test 4: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.PipedOutputStream#flush()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "No IOException checking because it is never thrown in the source code.",
- method = "flush",
- args = {}
- )
- public void test_flush() throws Exception {
- out = new PipedOutputStream();
- rt = new Thread(reader = new PReader(out));
- rt.start();
- out.write(testString.getBytes(), 0, 10);
- assertTrue("Test 1: Bytes have been written before flush.", reader.available() != 0);
- out.flush();
- assertEquals("Test 2: Flush failed. ",
- testString.substring(0, 10), reader.read(10));
- }
-
- /**
- * @tests java.io.PipedOutputStream#write(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Test 6 disabled due to incomplete implementation, see ticket #92.",
- method = "write",
- args = {byte[].class, int.class, int.class}
- )
- public void test_write$BII() throws IOException {
- out = new PipedOutputStream();
-
- try {
- out.write(testString.getBytes(), 0, 5);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- out = new PipedOutputStream(new PipedInputStream());
-
- try {
- out.write(testString.getBytes(), -1, 10);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- out.write(testString.getBytes(), 0, -1);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- out.write(testString.getBytes(), 5, testString.length());
- fail("Test 4: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- out.close();
- out = new PipedOutputStream();
- try {
- rt = new Thread(reader = new PReader(out));
- rt.start();
- out.write(testString.getBytes(), 0, testString.length());
- out.flush();
- assertEquals("Test 5: Bytes read do not match the bytes written. ",
- testString, reader.read(testString.length()));
- } catch (IOException e) {
- fail("Test 5: Unexpected IOException: " + e.getMessage());
- }
-
- reader.getReader().close();
- try {
- out.write(testString.getBytes(), 0, 5);
- fail("Test 7: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
-
- /**
- * @tests java.io.PipedOutputStream#write(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Test 3 disabled due to incomplete implementation, see ticket #92.",
- method = "write",
- args = {int.class}
- )
- public void test_writeI() throws IOException {
- out = new PipedOutputStream();
-
- try {
- out.write(42);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- rt = new Thread(reader = new PReader(out));
- rt.start();
- out.write('c');
- out.flush();
- assertEquals("Test 2: The byte read does not match the byte written. ",
- "c", reader.read(1));
-
-/* Test disabled due to incomplete implementation, see ticket #92.
- rt.interrupt();
-
- try {
- out.write(42);
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-*/
- reader.getReader().close();
- try {
- out.write(42);
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() throws Exception {
- if (rt != null)
- rt.interrupt();
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/PipedReaderTest.java b/luni/src/test/java/tests/api/java/io/PipedReaderTest.java
deleted file mode 100644
index f67790b..0000000
--- a/luni/src/test/java/tests/api/java/io/PipedReaderTest.java
+++ /dev/null
@@ -1,408 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.IOException;
-import java.io.PipedReader;
-import java.io.PipedWriter;
-
-@TestTargetClass(PipedReader.class)
-public class PipedReaderTest extends junit.framework.TestCase {
-
- static class PWriter implements Runnable {
- public PipedWriter pw;
-
- public PWriter(PipedReader reader) {
- try {
- pw = new PipedWriter(reader);
- } catch (Exception e) {
- System.out.println("Couldn't create writer");
- }
- }
-
- public PWriter() {
- pw = new PipedWriter();
- }
-
- public void run() {
- try {
- char[] c = new char[11];
- "Hello World".getChars(0, 11, c, 0);
- pw.write(c);
- Thread.sleep(10000);
- } catch (InterruptedException e) {
- } catch (Exception e) {
- System.out.println("Exception occurred: " + e.toString());
- }
- }
- }
-
- static class PWriter2 implements Runnable {
- PipedWriter pw;
-
- public boolean keepRunning = true;
-
- public void run() {
- try {
- pw.write('H');
- pw.close();
- while (keepRunning) {
- Thread.sleep(1000);
- }
- } catch (Exception e) {
- e.printStackTrace(System.out);
- System.out.println("Error while running the writer thread.");
- }
- }
-
- public PWriter2(PipedWriter writer) {
- pw = writer;
- }
- }
-
- PipedReader preader;
-
- PWriter pwriter;
-
- Thread t;
-
- /**
- * @tests java.io.PipedReader#PipedReader()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PipedReader",
- args = {}
- )
- public void test_Constructor() {
- preader = new PipedReader();
- assertNotNull(preader);
- try {
- preader.close();
- } catch (IOException e) {
- fail("Unexpeceted IOException");
- }
- }
-
- /**
- * @tests java.io.PipedReader#PipedReader(java.io.PipedWriter)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PipedReader",
- args = {java.io.PipedWriter.class}
- )
- public void test_ConstructorLjava_io_PipedWriter() throws IOException {
- // Test for method java.io.PipedReader(java.io.PipedWriter)
- try {
- preader = new PipedReader(new PipedWriter());
- } catch (Exception e) {
- fail("Test 1: Constructor failed: " + e.getMessage());
- }
- preader.close();
-
- PipedWriter pw = new PipedWriter(new PipedReader());
- try {
- preader = new PipedReader(pw);
- fail("Test 2: IOException expected because the writer is already connected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.PipedReader#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "No IOException checking because it is never thrown in the source code.",
- method = "close",
- args = {}
- )
- public void test_close() throws Exception {
- // Test for method void java.io.PipedReader.close()
- char[] c = null;
- preader = new PipedReader();
- t = new Thread(new PWriter(preader), "");
- t.start();
- Thread.sleep(500); // Allow writer to start
- c = new char[11];
- preader.read(c, 0, 5);
- preader.close();
-
- try {
- preader.read(c, 0, 5);
- fail("IOException expected because the reader is closed.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.PipedReader#connect(java.io.PipedWriter)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "connect",
- args = {java.io.PipedWriter.class}
- )
- public void test_connectLjava_io_PipedWriter() throws Exception {
- // Test for method void java.io.PipedReader.connect(java.io.PipedWriter)
- char[] c = null;
-
- preader = new PipedReader();
- t = new Thread(pwriter = new PWriter(), "");
- preader.connect(pwriter.pw);
- t.start();
- Thread.sleep(500); // Allow writer to start
- c = new char[11];
- preader.read(c, 0, 11);
-
- assertEquals("Test 1: Wrong characters read. ", "Hello World", new String(c));
- try {
- preader.connect(new PipedWriter());
- fail("Test 2: IOException expected because the reader is already connected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.PipedReader#read()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {}
- )
- public void test_read_1() throws Exception {
- // Test for method int java.io.PipedReader.read()
- char[] c = null;
- preader = new PipedReader();
- t = new Thread(new PWriter(preader), "");
- t.start();
- Thread.sleep(500); // Allow writer to start
- c = new char[11];
- for (int i = 0; i < c.length; i++) {
- c[i] = (char) preader.read();
- }
- assertEquals("Test 1: Wrong characters read. ", "Hello World", new String(c));
-
- try {
- preader.read();
- fail("Test 2: IOException expected since the thread that has " +
- "written to the pipe is no longer alive.");
- } catch (IOException e) {
- // Expected.
- }
-
- preader.close();
- try {
- preader.read();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.PipedReader#read()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks that read() returns -1 if the PipedWriter connectedto this PipedReader is closed.",
- method = "read",
- args = {}
- )
- public void test_read_2() throws Exception {
- Thread writerThread;
- PipedWriter pw;
- PWriter2 pwriter;
-
- preader = new PipedReader();
- pw = new PipedWriter(preader);
-
- writerThread = new Thread(pwriter = new PWriter2(pw), "PWriter2");
- writerThread.start();
- Thread.sleep(500); // Allow writer to start
-
- preader.read();
- assertEquals("Test 1: No more data indication expected. ", -1, preader.read());
- pwriter.keepRunning = false;
- }
-
- /**
- * @tests java.io.PipedReader#read(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException checking missed.",
- method = "read",
- args = {char[].class, int.class, int.class}
- )
- public void test_read$CII_1() throws Exception {
- // Test for method int java.io.PipedReader.read(char [], int, int)
- char[] c = null;
- preader = new PipedReader();
- t = new Thread(new PWriter(preader), "");
- t.start();
- Thread.sleep(500); // Allow writer to start
- c = new char[11];
- int n = 0;
- int x = n;
- while (x < 11) {
- n = preader.read(c, x, 11 - x);
- x = x + n;
- }
- assertEquals("Test 1: Wrong characters read. ", "Hello World", new String(c));
-
- preader.close();
- try {
- preader.read(c, 8, 7);
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.PipedReader#read(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {char[].class, int.class, int.class}
- )
- public void test_read$CII_Exception() throws IOException{
- PipedWriter pw = new PipedWriter();
- PipedReader obj = new PipedReader(pw);
- try {
- obj.read(new char[10], 0, -1);
- fail("IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
- try {
- obj.read(new char[10], -1, 1);
- fail("IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
- try {
- obj.read(new char[10], 2, 9);
- fail("IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
- try {
- obj.read(null, 0, 1);
- fail("NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.PipedReader#read()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks that read() returns -1 if the PipedWriter connectedto this PipedReader is closed.",
- method = "read",
- args = {}
- )
- public void test_read$CII_2() throws Exception {
- Thread writerThread;
- PipedWriter pw;
- PWriter2 pwriter;
- char[] c = new char[1];
-
- preader = new PipedReader();
- pw = new PipedWriter(preader);
-
- writerThread = new Thread(pwriter = new PWriter2(pw), "PWriter2");
- writerThread.start();
- Thread.sleep(500); // Allow writer to start
-
- preader.read(c, 0, 1);
- assertEquals("Test 1: No more data indication expected. ",
- -1, preader.read(c, 0, 1));
- pwriter.keepRunning = false;
- }
-
- /**
- * @tests java.io.PipedReader#ready()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ready",
- args = {}
- )
- public void test_ready() throws Exception {
- // Test for method boolean java.io.PipedReader.ready()
- char[] c = null;
- preader = new PipedReader();
-
- try {
- preader.ready();
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- t = new Thread(new PWriter(preader), "");
- t.start();
- Thread.sleep(500); // Allow writer to start
- assertTrue("Test 2: Reader should be ready", preader.ready());
- c = new char[11];
- for (int i = 0; i < c.length; i++)
- c[i] = (char) preader.read();
- assertFalse("Test 3: Reader should not be ready after reading all chars",
- preader.ready());
-
- preader.close();
- try {
- preader.ready();
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() throws Exception {
- if (t != null) {
- t.interrupt();
- }
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/PipedWriterTest.java b/luni/src/test/java/tests/api/java/io/PipedWriterTest.java
deleted file mode 100644
index 263d9b2..0000000
--- a/luni/src/test/java/tests/api/java/io/PipedWriterTest.java
+++ /dev/null
@@ -1,501 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.BrokenTest;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.IOException;
-import java.io.PipedReader;
-import java.io.PipedWriter;
-
-import java.util.Arrays;
-
-@TestTargetClass(PipedWriter.class)
-public class PipedWriterTest extends junit.framework.TestCase {
-
- static final String testString = "Lorem ipsum...";
- static final int testLength = testString.length();
-
- static class PReader implements Runnable {
- public PipedReader pr;
-
- public char[] buf;
-
- public PReader(PipedWriter pw) {
- try {
- pr = new PipedReader(pw);
- } catch (IOException e) {
- System.out.println("Exception setting up reader: "
- + e.toString());
- }
- }
-
- public PReader(PipedReader pr) {
- this.pr = pr;
- }
-
-/* public void run() {
- try {
- int r = 0;
- for (int i = 0; i < buf.length; i++) {
- r = pr.read();
- if (r == -1)
- break;
- buf[i] = (char) r;
- }
- } catch (Exception e) {
- System.out.println("Exception reading ("
- + Thread.currentThread().getName() + "): "
- + e.toString());
- }
- } */
-
- public void run() {
- try {
- while (true) {
- Thread.sleep(1000);
- Thread.yield();
- }
- } catch (InterruptedException e) {
- }
- }
-
- public String read(int nbytes) {
- buf = new char[nbytes];
- try {
- pr.read(buf, 0, nbytes);
- return new String(buf);
- } catch (IOException e) {
- System.out.println("Exception reading ("
- + Thread.currentThread().getName() + "): "
- + e.toString());
- return "ERROR";
- }
- }
- }
-
- Thread readerThread;
- PReader reader;
- PipedWriter pw;
- char[] testBuf;
-
- /**
- * @tests java.io.PipedWriter#PipedWriter()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PipedWriter",
- args = {}
- )
- public void test_Constructor() {
- pw = new PipedWriter();
- assertNotNull(pw);
- try {
- pw.close();
- } catch (IOException e) {
- fail("Unexpeceted IOException.");
- }
- }
-
- /**
- * @tests java.io.PipedWriter#PipedWriter(java.io.PipedReader)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PipedWriter",
- args = {java.io.PipedReader.class}
- )
- public void test_ConstructorLjava_io_PipedReader() throws Exception {
- PipedReader rd = new PipedReader();
-
- try {
- pw = new PipedWriter(rd);
- } catch (Exception e) {
- fail("Test 1: Construtor failed:" + e.getMessage());
- }
-
- readerThread = new Thread(reader = new PReader(rd), "Constructor(Reader)");
- readerThread.start();
- try {
- pw.write(testBuf);
- } catch (Exception e) {
- fail("Test 2: Could not write to the constructed writer: "
- + e.getMessage());
- }
- pw.close();
- assertEquals("Test 3: Incorrect character string received.", testString,
- reader.read(testLength));
-
- rd = new PipedReader(new PipedWriter());
- try {
- pw = new PipedWriter(rd);
- fail("Test 4: IOException expected because the reader is already connected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.PipedWriter#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "close",
- args = {}
- )
- public void test_close() throws Exception {
- PipedReader rd = new PipedReader();
- pw = new PipedWriter(rd);
- reader = new PReader(rd);
- try {
- pw.close();
- } catch (IOException e) {
- fail("Test 1: Unexpected IOException: " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.PipedWriter#connect(java.io.PipedReader)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "connect",
- args = {java.io.PipedReader.class}
- )
- public void test_connectLjava_io_PipedReader() throws Exception {
- PipedReader rd = new PipedReader();
- pw = new PipedWriter();
-
- try {
- pw.connect(rd);
- } catch (Exception e) {
- fail("Test 1: Unexpected exception when connecting: " +
- e.getLocalizedMessage());
- }
-
- readerThread = new Thread(reader = new PReader(rd), "connect");
- readerThread.start();
-
- try {
- pw.write(testBuf);
- } catch (IOException e) {
- fail("Test 2: Unexpected IOException when writing after connecting.");
- }
- assertEquals("Test 3: Incorrect character string received.", testString,
- reader.read(testLength));
-
- try {
- pw.connect(new PipedReader());
- fail("Test 4: IOException expected when reconnecting the writer.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.PipedWriter#flush()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "No IOException checking because it is never thrown in the source code.",
- method = "flush",
- args = {}
- )
- public void test_flush() throws Exception {
- // Test for method void java.io.PipedWriter.flush()
- pw = new PipedWriter();
- readerThread = new Thread(reader = new PReader(pw), "flush");
- readerThread.start();
- pw.write(testBuf);
- pw.flush();
- assertEquals("Test 1: Flush failed. ", testString,
- reader.read(testLength));
- }
-
- /**
- * @tests java.io.PipedWriter#write(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {char[].class, int.class, int.class}
- )
- public void test_write$CII() throws Exception {
- pw = new PipedWriter();
-
- try {
- pw.write(testBuf, 0, 5);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- pw = new PipedWriter(new PipedReader());
-
- try {
- pw.write(testBuf, -1, 1);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- pw.write(testBuf, 0, -1);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- try {
- pw.write(testBuf, 5, testString.length());
- fail("Test 4: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- pw.close();
- pw = new PipedWriter();
- try {
- readerThread = new Thread(reader = new PReader(pw), "writeCII");
- readerThread.start();
- pw.write(testBuf, 0, testLength);
- pw.close();
- reader.read(testLength);
- assertTrue("Test 5: Characters read do not match the characters written.",
- Arrays.equals( testBuf, reader.buf));
- } catch (IOException e) {
- fail("Test 5: Unexpected IOException: " + e.getMessage());
- }
-
- readerThread.interrupt();
-
- try {
- pw.write(testBuf, 0, 5);
- fail("Test 6: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- reader.pr.close();
- try {
- pw.write(testBuf, 0, 5);
- fail("Test 7: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.PipedWriter#write(char[],int,int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {char[].class, int.class, int.class}
- )
- @BrokenTest("Hangs on RI")
- public void test_write$CII_MultiThread() throws Exception {
- final PipedReader pr = new PipedReader();
- final PipedWriter pw = new PipedWriter();
-
- // test if writer recognizes dead reader
- pr.connect(pw);
-
- class WriteRunnable implements Runnable {
- boolean pass = false;
-
- boolean readerAlive = true;
-
- public void run() {
- try {
- pw.write(1);
- while (readerAlive) {
- // wait the reader thread dead
- }
- try {
- // should throw exception since reader thread
- // is now dead
- char[] buf = new char[10];
- pw.write(buf, 0, 10);
- } catch (IOException e) {
- pass = true;
- }
- } catch (IOException e) {
- //ignore
- }
- }
- }
- WriteRunnable writeRunnable = new WriteRunnable();
- Thread writeThread = new Thread(writeRunnable);
- class ReadRunnable implements Runnable {
- boolean pass;
-
- public void run() {
- try {
- pr.read();
- pass = true;
- } catch (IOException e) {
- //ignore
- }
- }
- }
- ReadRunnable readRunnable = new ReadRunnable();
- Thread readThread = new Thread(readRunnable);
- writeThread.start();
- readThread.start();
- while (readThread.isAlive()) {
- //wait the reader thread dead
- }
- writeRunnable.readerAlive = false;
- assertTrue("reader thread failed to read", readRunnable.pass);
- while (writeThread.isAlive()) {
- //wait the writer thread dead
- }
- assertTrue("writer thread failed to recognize dead reader",
- writeRunnable.pass);
- }
-
- /**
- * @tests java.io.PipedWriter#write(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {int.class}
- )
- public void test_writeI() throws Exception {
- // Test for method void java.io.PipedWriter.write(int)
-
- pw = new PipedWriter();
-
- try {
- pw.write(42);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- readerThread = new Thread(reader = new PReader(pw), "writeI");
- readerThread.start();
- pw.write(1);
- pw.write(2);
- pw.write(3);
- pw.close();
- reader.read(3);
- assertTrue("Test 2: The charaacters read do not match the characters written: " +
- (int) reader.buf[0] + " " + (int) reader.buf[1] + " " + (int) reader.buf[2],
- reader.buf[0] == 1 && reader.buf[1] == 2 && reader.buf[2] == 3);
- }
-
- /**
- * @tests java.io.PipedWriter#write(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {int.class}
- )
- @BrokenTest("Hangs on RI")
- public void test_writeI_MultiThread() throws IOException {
- final PipedReader pr = new PipedReader();
- final PipedWriter pw = new PipedWriter();
- // test if writer recognizes dead reader
- pr.connect(pw);
-
- class WriteRunnable implements Runnable {
- boolean pass = false;
- boolean readerAlive = true;
- public void run() {
- try {
- pw.write(1);
- while (readerAlive) {
- // wait the reader thread dead
- }
- try {
- // should throw exception since reader thread
- // is now dead
- pw.write(1);
- } catch (IOException e) {
- pass = true;
- }
- } catch (IOException e) {
- //ignore
- }
- }
- }
- WriteRunnable writeRunnable = new WriteRunnable();
- Thread writeThread = new Thread(writeRunnable);
- class ReadRunnable implements Runnable {
- boolean pass;
- public void run() {
- try {
- pr.read();
- pass = true;
- } catch (IOException e) {
- //ignore
- }
- }
- }
- ReadRunnable readRunnable = new ReadRunnable();
- Thread readThread = new Thread(readRunnable);
- writeThread.start();
- readThread.start();
- while (readThread.isAlive()) {
- //wait the reader thread dead
- }
- writeRunnable.readerAlive = false;
- assertTrue("reader thread failed to read", readRunnable.pass);
- while (writeThread.isAlive()) {
- //wait the writer thread dead
- }
- assertTrue("writer thread failed to recognize dead reader",
- writeRunnable.pass);
- }
-
- protected void setUp() throws Exception {
- super.setUp();
- testBuf = new char[testLength];
- testString.getChars(0, testLength, testBuf, 0);
- }
-
- protected void tearDown() throws Exception {
- try {
- if (readerThread != null) {
- readerThread.interrupt();
- }
- } catch (Exception ignore) {}
- try {
- if (pw != null) {
- pw.close();
- }
- } catch (Exception ignore) {}
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/PrintStreamTest.java b/luni/src/test/java/tests/api/java/io/PrintStreamTest.java
deleted file mode 100644
index ccc0bc1..0000000
--- a/luni/src/test/java/tests/api/java/io/PrintStreamTest.java
+++ /dev/null
@@ -1,1167 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.DataInputStream;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.io.UnsupportedEncodingException;
-import java.util.IllegalFormatException;
-import java.util.Locale;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(PrintStream.class)
-public class PrintStreamTest extends junit.framework.TestCase {
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
- byte[] ibuf = new byte[4096];
-
- private File testFile = null;
- private String testFilePath = null;
-
- public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_java_io_File\nTest_java_io_FileDescriptor\nTest_java_io_FileInputStream\nTest_java_io_FileNotFoundException\nTest_java_io_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
-
- private static class MockPrintStream extends PrintStream {
-
- public MockPrintStream(String fileName) throws FileNotFoundException {
- super(fileName);
- }
-
- public MockPrintStream(String fileName, String csn) throws FileNotFoundException, UnsupportedEncodingException {
- super(fileName, csn);
- }
-
- public MockPrintStream(OutputStream os) {
- super(os);
- }
-
- @Override
- public void setError() {
- super.setError();
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PrintStream",
- args = {java.io.File.class}
- )
- public void test_Constructor_Ljava_io_File() throws IOException {
- PrintStream tobj;
-
- tobj = new PrintStream(testFile);
- assertNotNull(tobj);
- tobj.write(1);
- tobj.close();
- assertEquals("output file has wrong length", 1, testFile.length());
- tobj = new PrintStream(testFile);
- assertNotNull(tobj);
- tobj.close();
- assertEquals("output file should be empty", 0, testFile.length());
-
- File file = new File("/invalidDirectory/Dummy");
- try {
- tobj = new PrintStream(file);
- fail("FileNotFoundException not thrown.");
- } catch (FileNotFoundException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PrintStream",
- args = {java.io.File.class, java.lang.String.class}
- )
- public void test_Constructor_Ljava_io_File_Ljava_lang_String() throws Exception {
- PrintStream tobj;
-
- tobj = new PrintStream(testFile, "utf-8");
- assertNotNull(tobj);
- tobj.write(1);
- tobj.close();
- assertEquals("output file has wrong length", 1, testFile.length());
- tobj = new PrintStream(testFile, "utf-8");
- assertNotNull(tobj);
- tobj.close();
- assertEquals("output file should be empty", 0, testFile.length());
-
- File file = new File("/invalidDirectory/Dummy");
- try {
- tobj = new PrintStream(file, "utf-8");
- fail("FileNotFoundException not thrown.");
- } catch (FileNotFoundException e) {
- // expected
- }
-
- try {
- tobj = new PrintStream(testFile, "invalidEncoding");
- fail("UnsupportedEncodingException not thrown.");
- } catch (UnsupportedEncodingException e) {
- // expected
- }
- }
-
- /**
- * @tests {@link java.io.PrintStream#PrintStream(String)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PrintStream",
- args = {java.lang.String.class}
- )
- public void test_Constructor_Ljava_lang_String() throws IOException {
- PrintStream tobj;
-
- tobj = new PrintStream(testFilePath);
- assertNotNull(tobj);
- tobj.write(1);
- tobj.close();
- assertEquals("output file has wrong length", 1, testFile.length());
- tobj = new PrintStream(testFilePath);
- assertNotNull(tobj);
- tobj.close();
- assertEquals("output file should be empty", 0, testFile.length());
-
- try {
- tobj = new PrintStream("/invalidDirectory/Dummy");
- fail("FileNotFoundException not thrown.");
- } catch (FileNotFoundException e) {
- // expected
- }
- }
-
- /**
- * @tests {@link java.io.PrintStream#PrintStream(String, String)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PrintStream",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_Constructor_Ljava_lang_String_Ljava_lang_String() throws Exception {
- PrintStream tobj;
-
- tobj = new PrintStream(testFilePath, "utf-8");
- assertNotNull(tobj);
- tobj.write(1);
- tobj.close();
- assertEquals("output file has wrong length", 1, testFile.length());
- tobj = new PrintStream(testFilePath, "utf-8");
- assertNotNull(tobj);
- tobj.close();
- assertEquals("output file should be empty", 0, testFile.length());
-
- try {
- tobj = new PrintStream("/invalidDirectory/", "utf-8");
- fail("FileNotFoundException not thrown.");
- } catch (FileNotFoundException e) {
- // expected
- }
-
- try {
- tobj = new PrintStream(testFilePath, "invalidEncoding");
- fail("UnsupportedEncodingException not thrown.");
- } catch (UnsupportedEncodingException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.PrintStream#PrintStream(java.io.OutputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PrintStream",
- args = {java.io.OutputStream.class}
- )
- public void test_ConstructorLjava_io_OutputStream() throws Exception {
- // Test for method java.io.PrintStream(java.io.OutputStream)
- PrintStream os = new PrintStream(baos);
- os.print(2345.76834720202);
- os.close();
-
- // regression for HARMONY-1195
- try {
- os = new PrintStream(baos, true, null);
- fail("Should throw NPE");
- } catch (NullPointerException e) {}
- }
-
- /**
- * @throws FileNotFoundException
- * @tests java.io.PrintStream#PrintStream(java.io.OutputStream, boolean)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Passing FALSE for autoFlush not tested.",
- method = "PrintStream",
- args = {java.io.OutputStream.class, boolean.class}
- )
- public void test_ConstructorLjava_io_OutputStreamZ() throws FileNotFoundException {
- PrintStream tobj;
-
- tobj = new PrintStream(baos, true);
- tobj.println(2345.76834720202);
- assertTrue("Bytes not written", baos.size() > 0);
- tobj.close();
-
-// tobj = new PrintStream(bos, false);
-// tobj.println(2345.76834720202);
-// assertEquals("Bytes should not be written, yet", 0, bos.size());
-// tobj.flush();
-// assertTrue("Bytes not written", bos.size() > 0);
-// tobj.close();
-
-// FileOutputStream fos = new FileOutputStream(testFile);
-//
-// tobj = new PrintStream(fos, true);
-// tobj.println(2345.76834720202);
-// assertTrue("Bytes not written", testFile.length() > 0);
-// tobj.close();
-//
-// tobj = new PrintStream(fos, false);
-// tobj.println(2345.76834720202);
-// assertTrue("Bytes not written", testFile.length() > 0);
-// tobj.close();
-//
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PrintStream",
- args = {java.io.OutputStream.class, boolean.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_io_OutputStream_Z_Ljava_lang_String() {
- PrintStream tobj;
-
- tobj = new PrintStream(baos, true);
- tobj.println(2345.76834720202);
- assertTrue("Bytes not written", baos.size() > 0);
- tobj.close();
-
- try {
- tobj = new PrintStream(baos, true, "invalidEncoding");
- fail("UnsupportedEncodingException not thrown.");
- } catch (UnsupportedEncodingException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.PrintStream#checkError()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkError",
- args = {}
- )
- public void test_checkError() throws Exception {
- // Test for method boolean java.io.PrintStream.checkError()
- PrintStream os = new PrintStream(new OutputStream() {
-
- public void write(int b) throws IOException {
- throw new IOException();
- }
-
- public void write(byte[] b, int o, int l) throws IOException {
- throw new IOException();
- }
- });
- os.print(fileString.substring(0, 501));
-
- assertTrue("Checkerror should return true", os.checkError());
- }
-
- /**
- * @tests java.io.PrintStream#setError()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "setError",
- args = {}
- )
- public void test_setError() throws Exception {
- MockPrintStream os = new MockPrintStream(new ByteArrayOutputStream());
- assertFalse("Test 1: Error flag should not be set.", os.checkError());
- os.setError();
- assertTrue("Test 2: Error flag should be set.", os.checkError());
- }
-
- /**
- * @tests java.io.PrintStream#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "close",
- args = {}
- )
- public void test_close() throws Exception {
- // Test for method void java.io.PrintStream.close()
- PrintStream os = new PrintStream(baos);
- os.close();
- baos.close();
- }
-
- /**
- * @tests java.io.PrintStream#flush()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "flush",
- args = {}
- )
- public void test_flush() throws Exception {
- // Test for method void java.io.PrintStream.flush()
- PrintStream os = new PrintStream(baos);
- os.print(fileString.substring(0, 501));
- os.flush();
- assertEquals("Bytes not written after flush", 501, baos.size());
- baos.close();
- os.close();
- }
-
- /**
- * @tests java.io.PrintStream#print(char[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "print",
- args = {char[].class}
- )
- public void test_print$C() {
- // Test for method void java.io.PrintStream.print(char [])
- PrintStream os = new PrintStream(baos, true);
- try {
- os.print((char[]) null);
- fail("NPE expected");
- } catch (NullPointerException ok) {}
-
- os = new PrintStream(baos, true);
- char[] sc = new char[4000];
- fileString.getChars(0, fileString.length(), sc, 0);
- os.print(sc);
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- os.close();
-
- byte[] rbytes = new byte[4000];
- bis.read(rbytes, 0, fileString.length());
- assertEquals("Incorrect char[] written", fileString, new String(rbytes,
- 0, fileString.length()));
- }
-
- /**
- * @tests java.io.PrintStream#print(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "print",
- args = {char.class}
- )
- public void test_printC() {
- // Test for method void java.io.PrintStream.print(char)
- PrintStream os = new PrintStream(baos, true);
- os.print('t');
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- assertEquals("Incorrect char written", 't', bis.read());
- }
-
- /**
- * @tests java.io.PrintStream#print(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "print",
- args = {double.class}
- )
- public void test_printD() {
- // Test for method void java.io.PrintStream.print(double)
- byte[] rbuf = new byte[100];
- PrintStream os = new PrintStream(baos, true);
- os.print(2345.76834720202);
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- bis.read(rbuf, 0, 16);
- assertEquals("Incorrect double written", "2345.76834720202",
- new String(rbuf, 0, 16));
- }
-
- /**
- * @tests java.io.PrintStream#print(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "print",
- args = {float.class}
- )
- public void test_printF() {
- // Test for method void java.io.PrintStream.print(float)
- PrintStream os = new PrintStream(baos, true);
- byte rbuf[] = new byte[10];
- os.print(29.08764f);
- os.flush();
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- bis.read(rbuf, 0, 8);
- assertEquals("Incorrect float written", "29.08764", new String(rbuf, 0,
- 8));
-
- }
-
- /**
- * @tests java.io.PrintStream#print(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "print",
- args = {int.class}
- )
- public void test_printI() {
- // Test for method void java.io.PrintStream.print(int)
- PrintStream os = new PrintStream(baos, true);
- os.print(768347202);
- byte[] rbuf = new byte[18];
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- bis.read(rbuf, 0, 9);
- assertEquals("Incorrect int written", "768347202", new String(rbuf, 0,
- 9));
- }
-
- /**
- * @tests java.io.PrintStream#print(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "print",
- args = {long.class}
- )
- public void test_printJ() {
- // Test for method void java.io.PrintStream.print(long)
- byte[] rbuf = new byte[100];
- PrintStream os = new PrintStream(baos, true);
- os.print(9875645283333L);
- os.close();
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- bis.read(rbuf, 0, 13);
- assertEquals("Incorrect long written", "9875645283333", new String(
- rbuf, 0, 13));
- }
-
- /**
- * @tests java.io.PrintStream#print(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "print",
- args = {java.lang.Object.class}
- )
- public void test_printLjava_lang_Object() throws Exception {
- // Test for method void java.io.PrintStream.print(java.lang.Object)
- PrintStream os = new PrintStream(baos, true);
- os.print((Object) null);
- os.flush();
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- byte[] nullbytes = new byte[4];
- bis.read(nullbytes, 0, 4);
- assertEquals("null should be written", "null", new String(nullbytes, 0,
- 4));
-
- bis.close();
- baos.close();
- os.close();
-
- ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
- os = new PrintStream(bos1, true);
- os.print(new java.util.Vector());
- bis = new ByteArrayInputStream(bos1.toByteArray());
- byte[] rbytes = new byte[2];
- bis.read(rbytes, 0, 2);
- assertEquals("Incorrect Object written", "[]", new String(rbytes, 0, 2));
- }
-
- /**
- * @tests java.io.PrintStream#print(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "print",
- args = {java.lang.String.class}
- )
- public void test_printLjava_lang_String() throws Exception {
- // Test for method void java.io.PrintStream.print(java.lang.String)
- PrintStream os = new PrintStream(baos, true);
- os.print((String) null);
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- byte[] nullbytes = new byte[4];
- bis.read(nullbytes, 0, 4);
- assertEquals("null should be written", "null", new String(nullbytes, 0,
- 4));
-
- bis.close();
- baos.close();
- os.close();
-
- ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
- os = new PrintStream(bos1, true);
- os.print("Hello World");
- bis = new ByteArrayInputStream(bos1.toByteArray());
- byte rbytes[] = new byte[100];
- bis.read(rbytes, 0, 11);
- assertEquals("Incorrect string written", "Hello World", new String(
- rbytes, 0, 11));
- }
-
- /**
- * @tests java.io.PrintStream#print(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "print",
- args = {boolean.class}
- )
- public void test_printZ() throws Exception {
- // Test for method void java.io.PrintStream.print(boolean)
- PrintStream os = new PrintStream(baos, true);
- os.print(true);
- DataInputStream dis = new DataInputStream(new ByteArrayInputStream(baos
- .toByteArray()));
-
- assertTrue("Incorrect boolean written", dis.readBoolean());
- }
-
- /**
- * @tests java.io.PrintStream#println()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {}
- )
- public void test_println() {
- // Test for method void java.io.PrintStream.println()
- char c;
- PrintStream os = new PrintStream(baos, true);
- os.println("");
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- assertTrue("Newline not written", (c = (char) bis.read()) == '\r'
- || c == '\n');
- }
-
- /**
- * @tests java.io.PrintStream#println(char[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {char[].class}
- )
- public void test_println$C() {
- // Test for method void java.io.PrintStream.println(char [])
- PrintStream os = new PrintStream(baos, true);
- char[] sc = new char[4000];
- fileString.getChars(0, fileString.length(), sc, 0);
- os.println(sc);
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- byte[] rbytes = new byte[4000];
- bis.read(rbytes, 0, fileString.length());
- assertEquals("Incorrect char[] written", fileString, new String(rbytes,
- 0, fileString.length()));
-
- // In this particular test method, the end of data is not immediately
- // followed by newLine separator in the reading buffer, instead its
- // followed by zeros. The newline is written as the last entry
- // in the inputStream buffer. Therefore, we must keep reading until we
- // hit a new line.
- int r;
- boolean newline = false;
- while ((r = bis.read()) != -1) {
- if (r == '\r' || r == '\n')
- newline = true;
- }
- assertTrue("Newline not written", newline);
- }
-
- /**
- * @tests java.io.PrintStream#println(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {char.class}
- )
- public void test_printlnC() {
- // Test for method void java.io.PrintStream.println(char)
- int c;
- PrintStream os = new PrintStream(baos, true);
- os.println('t');
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- assertEquals("Incorrect char written", 't', bis.read());
- assertTrue("Newline not written", (c = bis.read()) == '\r' || c == '\n');
- }
-
- /**
- * @tests java.io.PrintStream#println(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {double.class}
- )
- public void test_printlnD() {
- // Test for method void java.io.PrintStream.println(double)
- int c;
- PrintStream os = new PrintStream(baos, true);
- os.println(2345.76834720202);
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- byte[] rbuf = new byte[100];
- bis.read(rbuf, 0, 16);
- assertEquals("Incorrect double written", "2345.76834720202",
- new String(rbuf, 0, 16));
- assertTrue("Newline not written", (c = bis.read()) == '\r' || c == '\n');
- }
-
- /**
- * @tests java.io.PrintStream#println(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {float.class}
- )
- public void test_printlnF() {
- // Test for method void java.io.PrintStream.println(float)
- int c;
- byte[] rbuf = new byte[100];
- PrintStream os = new PrintStream(baos, true);
- os.println(29.08764f);
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- bis.read(rbuf, 0, 8);
- assertEquals("Incorrect float written", "29.08764", new String(rbuf, 0,
- 8));
- assertTrue("Newline not written", (c = bis.read()) == '\r' || c == '\n');
- }
-
- /**
- * @tests java.io.PrintStream#println(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {int.class}
- )
- public void test_printlnI() {
- // Test for method void java.io.PrintStream.println(int)
- int c;
- PrintStream os = new PrintStream(baos, true);
- os.println(768347202);
- byte[] rbuf = new byte[100];
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- bis.read(rbuf, 0, 9);
- assertEquals("Incorrect int written", "768347202", new String(rbuf, 0,
- 9));
- assertTrue("Newline not written", (c = bis.read()) == '\r' || c == '\n');
- }
-
- /**
- * @tests java.io.PrintStream#println(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {long.class}
- )
- public void test_printlnJ() {
- // Test for method void java.io.PrintStream.println(long)
- int c;
- PrintStream os = new PrintStream(baos, true);
- os.println(9875645283333L);
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- byte[] rbuf = new byte[100];
- bis.read(rbuf, 0, 13);
- assertEquals("Incorrect long written", "9875645283333", new String(
- rbuf, 0, 13));
- assertTrue("Newline not written", (c = bis.read()) == '\r' || c == '\n');
- }
-
- /**
- * @tests java.io.PrintStream#println(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {java.lang.Object.class}
- )
- public void test_printlnLjava_lang_Object() {
- // Test for method void java.io.PrintStream.println(java.lang.Object)
- char c;
- PrintStream os = new PrintStream(baos, true);
- os.println(new java.util.Vector());
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- byte[] rbytes = new byte[2];
- bis.read(rbytes, 0, 2);
- assertEquals("Incorrect Vector written", "[]", new String(rbytes, 0, 2));
- assertTrue("Newline not written", (c = (char) bis.read()) == '\r'
- || c == '\n');
- }
-
- /**
- * @tests java.io.PrintStream#println(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {java.lang.String.class}
- )
- public void test_printlnLjava_lang_String() {
- // Test for method void java.io.PrintStream.println(java.lang.String)
- char c;
- PrintStream os = new PrintStream(baos, true);
- os.println("Hello World");
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- byte rbytes[] = new byte[100];
- bis.read(rbytes, 0, 11);
- assertEquals("Incorrect string written", "Hello World", new String(
- rbytes, 0, 11));
- assertTrue("Newline not written", (c = (char) bis.read()) == '\r'
- || c == '\n');
- }
-
- /**
- * @tests java.io.PrintStream#println(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {boolean.class}
- )
- public void test_printlnZ() {
- // Test for method void java.io.PrintStream.println(boolean)
- int c;
- PrintStream os = new PrintStream(baos, true);
- os.println(true);
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- byte[] rbuf = new byte[100];
- bis.read(rbuf, 0, 4);
- assertEquals("Incorrect boolean written", "true",
- new String(rbuf, 0, 4));
- assertTrue("Newline not written", (c = bis.read()) == '\r' || c == '\n');
- }
-
- /**
- * @tests java.io.PrintStream#write(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {byte[].class, int.class, int.class}
- )
- public void test_write$BII() {
- // Test for method void java.io.PrintStream.write(byte [], int, int)
- PrintStream os = new PrintStream(baos, true);
- os.write(fileString.getBytes(), 0, fileString.length());
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- byte rbytes[] = new byte[4000];
- bis.read(rbytes, 0, fileString.length());
- assertTrue("Incorrect bytes written", new String(rbytes, 0, fileString
- .length()).equals(fileString));
-
- try {
- os.write(rbytes, -1, 1);
- fail("IndexOutOfBoundsException should have been thrown.");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- os.write(rbytes, 0, -1);
- fail("IndexOutOfBoundsException should have been thrown.");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- os.write(rbytes, 1, rbytes.length);
- fail("IndexOutOfBoundsException should have been thrown.");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.PrintStream#write(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {int.class}
- )
- public void test_writeI() {
- // Test for method void java.io.PrintStream.write(int)
- PrintStream os = new PrintStream(baos, true);
- os.write('t');
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- assertEquals("Incorrect char written", 't', bis.read());
- }
-
- /**
- * @tests java.io.PrintStream#append(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {char.class}
- )
- public void test_appendChar() throws IOException {
- char testChar = ' ';
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- PrintStream printStream = new PrintStream(out);
- printStream.append(testChar);
- printStream.flush();
- assertEquals(String.valueOf(testChar), out.toString());
- printStream.close();
- }
-
- /**
- * @tests java.io.PrintStream#append(CharSequence)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {java.lang.CharSequence.class}
- )
- public void test_appendCharSequence() {
- String testString = "My Test String";
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- PrintStream printStream = new PrintStream(out);
- printStream.append(testString);
- printStream.flush();
- assertEquals(testString, out.toString());
- printStream.close();
- }
-
- /**
- * @tests java.io.PrintStream#append(CharSequence, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {java.lang.CharSequence.class, int.class, int.class}
- )
- public void test_appendCharSequenceIntInt() {
- String testString = "My Test String";
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- PrintStream printStream = new PrintStream(out);
- printStream.append(testString, 1, 3);
- printStream.flush();
- assertEquals(testString.substring(1, 3), out.toString());
- try {
- printStream.append(testString, 4, 100);
- fail("IndexOutOfBoundsException not thrown");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- printStream.append(testString, 100, 1);
- fail("IndexOutOfBoundsException not thrown");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- printStream.close();
- }
-
- /**
- * @tests java.io.PrintStream#format(java.lang.String, java.lang.Object...)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object() {
- PrintStream tobj;
-
- tobj = new PrintStream(baos, false);
- tobj.format("%s %s", "Hello", "World");
- tobj.flush();
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- byte[] rbytes = new byte[11];
- bis.read(rbytes, 0, rbytes.length);
- assertEquals("Wrote incorrect string", "Hello World",
- new String(rbytes));
-
- baos.reset();
- tobj = new PrintStream(baos);
- tobj.format("%1$.3G, %1$.5f, 0%2$xx", 12345.678, 123456);
- tobj.flush();
- assertEquals("Wrong output!", "1.23E+04, 12345.67800, 01e240x", new String(baos.toByteArray()));
- tobj.close();
-
- baos.reset();
- tobj = new PrintStream(baos);
- try {
- tobj.format("%1$.3G, %1$x", 12345.678);
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
-
- try {
- tobj.format("%s %q", "Hello", "World");
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
-
- try {
- tobj.format("%s %s", "Hello");
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.PrintStream#format(java.util.Locale, java.lang.String,
- * java.lang.Object...)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "format",
- args = {java.util.Locale.class, java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_util_Locale_Ljava_lang_String_$Ljava_lang_Object() {
- PrintStream tobj;
-
- tobj = new PrintStream(baos, false);
- tobj.format(Locale.US, "%s %s", "Hello", "World");
- tobj.flush();
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- byte[] rbytes = new byte[11];
- bis.read(rbytes, 0, rbytes.length);
- assertEquals("Wrote incorrect string", "Hello World",
- new String(rbytes));
-
- baos.reset();
- tobj = new PrintStream(baos);
- tobj.format(Locale.GERMANY, "%1$.3G; %1$.5f; 0%2$xx", 12345.678, 123456);
- tobj.flush();
- assertEquals("Wrong output!", "1,23E+04; 12345,67800; 01e240x", new String(baos.toByteArray()));
- tobj.close();
-
- baos.reset();
- tobj = new PrintStream(baos);
- tobj.format(Locale.US, "%1$.3G, %1$.5f, 0%2$xx", 12345.678, 123456);
- tobj.flush();
- assertEquals("Wrong output!", "1.23E+04, 12345.67800, 01e240x", new String(baos.toByteArray()));
- tobj.close();
-
- baos.reset();
- tobj = new PrintStream(baos);
- try {
- tobj.format(Locale.US, "%1$.3G, %1$x", 12345.678);
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
-
- try {
- tobj.format(Locale.US, "%s %q", "Hello", "World");
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
-
- try {
- tobj.format(Locale.US, "%s %s", "Hello");
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.PrintStream#printf(java.lang.String, java.lang.Object...)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "printf",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_printfLjava_lang_String$Ljava_lang_Object() {
- PrintStream tobj;
-
- tobj = new PrintStream(baos, false);
- tobj.printf("%s %s", "Hello", "World");
- tobj.flush();
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- byte[] rbytes = new byte[11];
- bis.read(rbytes, 0, rbytes.length);
- assertEquals("Wrote incorrect string", "Hello World",
- new String(rbytes));
-
- baos.reset();
- tobj = new PrintStream(baos);
- tobj.printf("%1$.3G, %1$.5f, 0%2$xx", 12345.678, 123456);
- tobj.flush();
- assertEquals("Wrong output!", "1.23E+04, 12345.67800, 01e240x", new String(baos.toByteArray()));
- tobj.close();
-
- baos.reset();
- tobj = new PrintStream(baos);
- try {
- tobj.printf("%1$.3G, %1$x", 12345.678);
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
-
- try {
- tobj.printf("%s %q", "Hello", "World");
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
-
- try {
- tobj.printf("%s %s", "Hello");
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.PrintStream#printf(java.util.Locale, java.lang.String,
- * java.lang.Object...)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "printf",
- args = {java.util.Locale.class, java.lang.String.class, java.lang.Object[].class}
- )
- public void test_printfLjava_util_Locale_Ljava_lang_String_$Ljava_lang_Object() {
- PrintStream tobj;
-
- tobj = new PrintStream(baos, false);
- tobj.printf(Locale.US, "%s %s", "Hello", "World");
- tobj.flush();
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- byte[] rbytes = new byte[11];
- bis.read(rbytes, 0, rbytes.length);
- assertEquals("Wrote incorrect string", "Hello World",
- new String(rbytes));
-
- baos.reset();
- tobj = new PrintStream(baos);
- tobj.printf(Locale.GERMANY, "%1$.3G; %1$.5f; 0%2$xx", 12345.678, 123456);
- tobj.flush();
- assertEquals("Wrong output!", "1,23E+04; 12345,67800; 01e240x", new String(baos.toByteArray()));
- tobj.close();
-
- baos.reset();
- tobj = new PrintStream(baos);
- tobj.printf(Locale.US, "%1$.3G, %1$.5f, 0%2$xx", 12345.678, 123456);
- tobj.flush();
- assertEquals("Wrong output!", "1.23E+04, 12345.67800, 01e240x", new String(baos.toByteArray()));
- tobj.close();
-
- baos.reset();
- tobj = new PrintStream(baos);
- try {
- tobj.printf(Locale.US, "%1$.3G, %1$x", 12345.678);
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
-
- try {
- tobj.printf(Locale.US, "%s %q", "Hello", "World");
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
-
- try {
- tobj.printf(Locale.US, "%s %s", "Hello");
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
- }
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- testFile = File.createTempFile("test", null);
- testFilePath = testFile.getAbsolutePath();
- }
-
- @Override
- protected void tearDown() throws Exception {
- testFile.delete();
- testFile = null;
- testFilePath = null;
- super.tearDown();
- }
-
-
-}
diff --git a/luni/src/test/java/tests/api/java/io/PrintWriterTest.java b/luni/src/test/java/tests/api/java/io/PrintWriterTest.java
deleted file mode 100644
index 2796e7b..0000000
--- a/luni/src/test/java/tests/api/java/io/PrintWriterTest.java
+++ /dev/null
@@ -1,1296 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.io.UnsupportedEncodingException;
-import java.util.IllegalFormatException;
-import java.util.Locale;
-
-import tests.support.Support_StringReader;
-import tests.support.Support_StringWriter;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(PrintWriter.class)
-public class PrintWriterTest extends junit.framework.TestCase {
-
- private static class MockPrintWriter extends PrintWriter {
-
- public MockPrintWriter(OutputStream os) {
- super(os);
- }
-
- @Override
- public void setError() {
- super.setError();
- }
- }
-
- static class Bogus {
- public String toString() {
- return "Bogus";
- }
- }
-
- private File testFile = null;
- private String testFilePath = null;
-
- PrintWriter pw;
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
- ByteArrayInputStream bai;
-
- BufferedReader br;
-
- /**
- * @tests java.io.PrintWriter#PrintWriter(java.io.OutputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PrintWriter",
- args = {java.io.OutputStream.class}
- )
- public void test_ConstructorLjava_io_OutputStream() {
- // Test for method java.io.PrintWriter(java.io.OutputStream)
- String s;
- pw = new PrintWriter(baos);
- pw.println("Random Chars");
- pw.write("Hello World");
- pw.flush();
- try {
- br = new BufferedReader(new Support_StringReader(baos.toString()));
- s = br.readLine();
- assertTrue("Incorrect string written/read: " + s, s
- .equals("Random Chars"));
- s = br.readLine();
- assertTrue("Incorrect string written/read: " + s, s
- .equals("Hello World"));
- } catch (IOException e) {
- fail("IOException during test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.PrintWriter#PrintWriter(java.io.OutputStream, boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PrintWriter",
- args = {java.io.OutputStream.class, boolean.class}
- )
- public void test_ConstructorLjava_io_OutputStreamZ() {
- // Test for method java.io.PrintWriter(java.io.OutputStream, boolean)
- String s;
- pw = new PrintWriter(baos, true);
- pw.println("Random Chars");
- pw.write("Hello World");
- try {
- br = new BufferedReader(new Support_StringReader(baos.toString()));
- s = br.readLine();
- assertTrue("Incorrect string written/read: " + s, s
- .equals("Random Chars"));
- pw.flush();
- br = new BufferedReader(new Support_StringReader(baos.toString()));
- s = br.readLine();
- assertTrue("Incorrect string written/read: " + s, s
- .equals("Random Chars"));
- s = br.readLine();
- assertTrue("Incorrect string written/read: " + s, s
- .equals("Hello World"));
- } catch (IOException e) {
- fail("IOException during test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.PrintWriter#PrintWriter(java.io.Writer)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PrintWriter",
- args = {java.io.Writer.class}
- )
- public void test_ConstructorLjava_io_Writer() {
- // Test for method java.io.PrintWriter(java.io.Writer)
- Support_StringWriter sw;
- pw = new PrintWriter(sw = new Support_StringWriter());
- pw.print("Hello");
- pw.flush();
- assertEquals("Failed to construct proper writer",
- "Hello", sw.toString());
- }
-
- /**
- * @tests java.io.PrintWriter#PrintWriter(java.io.Writer, boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PrintWriter",
- args = {java.io.Writer.class, boolean.class}
- )
- public void test_ConstructorLjava_io_WriterZ() {
- // Test for method java.io.PrintWriter(java.io.Writer, boolean)
- Support_StringWriter sw;
- pw = new PrintWriter(sw = new Support_StringWriter(), true);
- pw.print("Hello");
- // Auto-flush should have happened
- assertEquals("Failed to construct proper writer",
- "Hello", sw.toString());
- }
-
- /**
- * @tests java.io.PrintWriter#PrintWriter(java.io.File)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PrintWriter",
- args = {java.io.File.class}
- )
- public void test_ConstructorLjava_io_File() throws Exception {
- PrintWriter tobj;
-
- tobj = new PrintWriter(testFile);
- tobj.write(1);
- tobj.close();
- assertEquals("output file has wrong length", 1, testFile.length());
- tobj = new PrintWriter(testFile);
- assertNotNull(tobj);
- tobj.close();
- assertEquals("output file should be empty", 0, testFile.length());
-
- File file = new File("/invalidDirectory/Dummy");
- try {
- tobj = new PrintWriter(file);
- fail("FileNotFoundException not thrown.");
- } catch (FileNotFoundException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.PrintWriter#PrintWriter(java.io.File, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PrintWriter",
- args = {java.io.File.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_io_File_Ljava_lang_String() throws Exception {
- PrintWriter tobj;
-
- tobj = new PrintWriter(testFile, "utf-8");
- tobj.write(1);
- tobj.close();
- assertEquals("output file has wrong length", 1, testFile.length());
- tobj = new PrintWriter(testFile, "utf-8");
- assertNotNull(tobj);
- tobj.close();
- assertEquals("output file should be empty", 0, testFile.length());
-
- File file = new File("/invalidDirectory/Dummy");
- try {
- tobj = new PrintWriter(file, "utf-8");
- fail("FileNotFoundException not thrown.");
- } catch (FileNotFoundException e) {
- // expected
- }
-
- try {
- tobj = new PrintWriter(testFile, "invalidEncoding");
- fail("UnsupportedEncodingException not thrown.");
- } catch (UnsupportedEncodingException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.PrintWriter#PrintWriter(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PrintWriter",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() throws Exception {
- PrintWriter tobj;
-
- tobj = new PrintWriter(testFilePath);
- assertNotNull(tobj);
- tobj.write(1);
- tobj.close();
- assertEquals("output file has wrong length", 1, testFile.length());
- tobj = new PrintWriter(testFilePath);
- assertNotNull(tobj);
- tobj.close();
- assertEquals("output file should be empty", 0, testFile.length());
-
- try {
- tobj = new PrintWriter("/invalidDirectory/Dummy");
- fail("FileNotFoundException not thrown.");
- } catch (FileNotFoundException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.PrintWriter#PrintWriter(java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PrintWriter",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String_Ljava_lang_String() throws Exception {
- PrintWriter tobj;
-
- tobj = new PrintWriter(testFilePath, "utf-8");
- assertNotNull(tobj);
- tobj.write(1);
- tobj.close();
- assertEquals("output file has wrong length", 1, testFile.length());
- tobj = new PrintWriter(testFilePath, "utf-8");
- assertNotNull(tobj);
- tobj.close();
- assertEquals("output file should be empty", 0, testFile.length());
-
- try {
- tobj = new PrintWriter("/invalidDirectory/", "utf-8");
- fail("FileNotFoundException not thrown.");
- } catch (FileNotFoundException e) {
- // expected
- }
-
- try {
- tobj = new PrintWriter(testFilePath, "invalidEncoding");
- fail("UnsupportedEncodingException not thrown.");
- } catch (UnsupportedEncodingException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.PrintWriter#checkError()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkError",
- args = {}
- )
- public void test_checkError() {
- // Test for method boolean java.io.PrintWriter.checkError()
- pw.close();
- pw.print(490000000000.08765);
- assertTrue("Failed to return error", pw.checkError());
- }
-
- /**
- * @tests java.io.PrintStream#setError()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "setError",
- args = {}
- )
- public void test_setError() throws Exception {
- MockPrintWriter os = new MockPrintWriter(new ByteArrayOutputStream());
- assertFalse("Test 1: Error flag should not be set.", os.checkError());
- os.setError();
- assertTrue("Test 2: Error flag should be set.", os.checkError());
- }
-
- /**
- * @tests java.io.PrintWriter#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "close",
- args = {}
- )
- public void test_close() {
- // Test for method void java.io.PrintWriter.close()
- pw.close();
- pw.println("l");
- assertTrue("Write on closed stream failed to generate error", pw
- .checkError());
- }
-
- /**
- * @tests java.io.PrintWriter#flush()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "flush",
- args = {}
- )
- public void test_flush() {
- // Test for method void java.io.PrintWriter.flush()
- final double dub = 490000000000.08765;
- pw.print(dub);
- pw.flush();
- assertTrue("Failed to flush", new String(baos.toByteArray())
- .equals(String.valueOf(dub)));
- }
-
- /**
- * @tests java.io.PrintWriter#print(char[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "print",
- args = {char[].class}
- )
- public void test_print$C() {
- // Test for method void java.io.PrintWriter.print(char [])
- String s = null;
- char[] schars = new char[11];
- "Hello World".getChars(0, 11, schars, 0);
- pw.print(schars);
- pw.flush();
- try {
- br = new BufferedReader(new Support_StringReader(baos.toString()));
- s = br.readLine();
- } catch (IOException e) {
- fail("IOException during test : " + e.getMessage());
- }
- assertTrue("Wrote incorrect char[] string: " + s, s
- .equals("Hello World"));
- int r = 0;
- try {
- pw.print((char[]) null);
- } catch (NullPointerException e) {
- r = 1;
- }
- assertEquals("null pointer exception for printing null char[] is not caught",
- 1, r);
- }
-
- /**
- * @tests java.io.PrintWriter#print(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "print",
- args = {char.class}
- )
- public void test_printC() {
- // Test for method void java.io.PrintWriter.print(char)
- pw.print('c');
- pw.flush();
- assertEquals("Wrote incorrect char string", "c", new String(baos.toByteArray())
- );
- }
-
- /**
- * @tests java.io.PrintWriter#print(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "print",
- args = {double.class}
- )
- public void test_printD() {
- // Test for method void java.io.PrintWriter.print(double)
- final double dub = 490000000000.08765;
- pw.print(dub);
- pw.flush();
- assertTrue("Wrote incorrect double string", new String(baos
- .toByteArray()).equals(String.valueOf(dub)));
- }
-
- /**
- * @tests java.io.PrintWriter#print(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "print",
- args = {float.class}
- )
- public void test_printF() {
- // Test for method void java.io.PrintWriter.print(float)
- final float flo = 49.08765f;
- pw.print(flo);
- pw.flush();
- assertTrue("Wrote incorrect float string",
- new String(baos.toByteArray()).equals(String.valueOf(flo)));
- }
-
- /**
- * @tests java.io.PrintWriter#print(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "print",
- args = {int.class}
- )
- public void test_printI() {
- // Test for method void java.io.PrintWriter.print(int)
- pw.print(4908765);
- pw.flush();
- assertEquals("Wrote incorrect int string", "4908765", new String(baos.toByteArray())
- );
- }
-
- /**
- * @tests java.io.PrintWriter#print(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "print",
- args = {long.class}
- )
- public void test_printJ() {
- // Test for method void java.io.PrintWriter.print(long)
- pw.print(49087650000L);
- pw.flush();
- assertEquals("Wrote incorrect long string", "49087650000", new String(baos.toByteArray())
- );
- }
-
- /**
- * @tests java.io.PrintWriter#print(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "print",
- args = {java.lang.Object.class}
- )
- public void test_printLjava_lang_Object() {
- // Test for method void java.io.PrintWriter.print(java.lang.Object)
- pw.print((Object) null);
- pw.flush();
- assertEquals("Did not write null", "null", new String(baos.toByteArray()));
- baos.reset();
-
- pw.print(new Bogus());
- pw.flush();
- assertEquals("Wrote in incorrect Object string", "Bogus", new String(baos
- .toByteArray()));
- }
-
- /**
- * @tests java.io.PrintWriter#print(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "print",
- args = {java.lang.String.class}
- )
- public void test_printLjava_lang_String() {
- // Test for method void java.io.PrintWriter.print(java.lang.String)
- pw.print((String) null);
- pw.flush();
- assertEquals("did not write null", "null", new String(baos.toByteArray()));
- baos.reset();
-
- pw.print("Hello World");
- pw.flush();
- assertEquals("Wrote incorrect string", "Hello World", new String(baos.toByteArray()));
- }
-
- /**
- * @tests java.io.PrintWriter#print(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "print",
- args = {boolean.class}
- )
- public void test_printZ() {
- // Test for method void java.io.PrintWriter.print(boolean)
- pw.print(true);
- pw.flush();
- assertEquals("Wrote in incorrect boolean string", "true", new String(baos
- .toByteArray()));
- }
-
- /**
- * @tests java.io.PrintWriter#println()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {}
- )
- public void test_println() {
- // Test for method void java.io.PrintWriter.println()
- String s;
- pw.println("Blarg");
- pw.println();
- pw.println("Bleep");
- pw.flush();
- try {
- br = new BufferedReader(new Support_StringReader(baos.toString()));
- s = br.readLine();
- assertTrue("Wrote incorrect line: " + s, s.equals("Blarg"));
- s = br.readLine();
- assertTrue("Wrote incorrect line: " + s, s.equals(""));
- s = br.readLine();
- assertTrue("Wrote incorrect line: " + s, s.equals("Bleep"));
- } catch (IOException e) {
- fail("IOException during test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.PrintWriter#println(char[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {char[].class}
- )
- public void test_println$C() {
- // Test for method void java.io.PrintWriter.println(char [])
- String s = null;
- char[] schars = new char[11];
- "Hello World".getChars(0, 11, schars, 0);
- pw.println("Random Chars");
- pw.println(schars);
- pw.flush();
- try {
- br = new BufferedReader(new Support_StringReader(baos.toString()));
- s = br.readLine();
- s = br.readLine();
- } catch (IOException e) {
- fail("IOException during test : " + e.getMessage());
- }
- assertTrue("Wrote incorrect char[] string: " + s, s
- .equals("Hello World"));
- }
-
- /**
- * @tests java.io.PrintWriter#println(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {char.class}
- )
- public void test_printlnC() {
- // Test for method void java.io.PrintWriter.println(char)
- String s = null;
- pw.println("Random Chars");
- pw.println('c');
- pw.flush();
- try {
- br = new BufferedReader(new Support_StringReader(baos.toString()));
- s = br.readLine();
- s = br.readLine();
- } catch (IOException e) {
- fail("IOException during test : " + e.getMessage());
- }
- assertTrue("Wrote incorrect char string: " + s, s.equals("c"));
- }
-
- /**
- * @tests java.io.PrintWriter#println(double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {double.class}
- )
- public void test_printlnD() {
- // Test for method void java.io.PrintWriter.println(double)
- String s = null;
- final double dub = 4000000000000000.657483;
- pw.println("Random Chars");
- pw.println(dub);
- pw.flush();
- try {
- br = new BufferedReader(new Support_StringReader(baos.toString()));
- br.readLine();
- s = br.readLine();
- } catch (IOException e) {
- fail("IOException during test : " + e.getMessage());
- }
- assertTrue("Wrote incorrect double string: " + s, s.equals(String
- .valueOf(dub)));
- }
-
- /**
- * @tests java.io.PrintWriter#println(float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {float.class}
- )
- public void test_printlnF() {
- // Test for method void java.io.PrintWriter.println(float)
- String s;
- final float flo = 40.4646464f;
- pw.println("Random Chars");
- pw.println(flo);
- pw.flush();
- try {
- br = new BufferedReader(new Support_StringReader(baos.toString()));
- br.readLine();
- s = br.readLine();
- assertTrue("Wrote incorrect float string: " + s + " wanted: "
- + String.valueOf(flo), s.equals(String.valueOf(flo)));
- } catch (IOException e) {
- fail("IOException during test : " + e.getMessage());
- }
-
- }
-
- /**
- * @tests java.io.PrintWriter#println(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {int.class}
- )
- public void test_printlnI() {
- // Test for method void java.io.PrintWriter.println(int)
- String s = null;
- pw.println("Random Chars");
- pw.println(400000);
- pw.flush();
- try {
- br = new BufferedReader(new Support_StringReader(baos.toString()));
- br.readLine();
- s = br.readLine();
- } catch (IOException e) {
- fail("IOException during test : " + e.getMessage());
- }
- assertTrue("Wrote incorrect int string: " + s, s.equals("400000"));
- }
-
- /**
- * @tests java.io.PrintWriter#println(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {long.class}
- )
- public void test_printlnJ() {
- // Test for method void java.io.PrintWriter.println(long)
- String s = null;
- pw.println("Random Chars");
- pw.println(4000000000000L);
- pw.flush();
- try {
- br = new BufferedReader(new Support_StringReader(baos.toString()));
- br.readLine();
- s = br.readLine();
- } catch (IOException e) {
- fail("IOException during test : " + e.getMessage());
- }
- assertTrue("Wrote incorrect long string: " + s, s
- .equals("4000000000000"));
- }
-
- /**
- * @tests java.io.PrintWriter#println(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {java.lang.Object.class}
- )
- public void test_printlnLjava_lang_Object() {
- // Test for method void java.io.PrintWriter.println(java.lang.Object)
- String s = null;
- pw.println("Random Chars");
- pw.println(new Bogus());
- pw.flush();
- try {
- br = new BufferedReader(new Support_StringReader(baos.toString()));
- br.readLine();
- s = br.readLine();
- } catch (IOException e) {
- fail("IOException during test : " + e.getMessage());
- }
- assertTrue("Wrote incorrect Object string: " + s, s.equals("Bogus"));
- }
-
- /**
- * @tests java.io.PrintWriter#println(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {java.lang.String.class}
- )
- public void test_printlnLjava_lang_String() {
- // Test for method void java.io.PrintWriter.println(java.lang.String)
- String s = null;
- pw.println("Random Chars");
- pw.println("Hello World");
- pw.flush();
- try {
- br = new BufferedReader(new Support_StringReader(baos.toString()));
- br.readLine();
- s = br.readLine();
- } catch (IOException e) {
- fail("IOException during test : " + e.getMessage());
- }
- assertTrue("Wrote incorrect string: " + s, s.equals("Hello World"));
- }
-
- /**
- * @tests java.io.PrintWriter#println(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "println",
- args = {boolean.class}
- )
- public void test_printlnZ() {
- // Test for method void java.io.PrintWriter.println(boolean)
- String s = null;
- pw.println("Random Chars");
- pw.println(false);
- pw.flush();
- try {
- br = new BufferedReader(new Support_StringReader(baos.toString()));
- br.readLine();
- s = br.readLine();
- } catch (IOException e) {
- fail("IOException during test : " + e.getMessage());
- }
- assertTrue("Wrote incorrect boolean string: " + s, s.equals("false"));
- }
-
- /**
- * @tests java.io.PrintWriter#write(char[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {char[].class}
- )
- public void test_write$C() {
- // Test for method void java.io.PrintWriter.write(char [])
- String s = null;
- char[] schars = new char[11];
- "Hello World".getChars(0, 11, schars, 0);
- pw.println("Random Chars");
- pw.write(schars);
- pw.flush();
- try {
- br = new BufferedReader(new Support_StringReader(baos.toString()));
- br.readLine();
- s = br.readLine();
- } catch (IOException e) {
- fail("IOException during test: " + e.getMessage());
- }
- assertTrue("Wrote incorrect char[] string: " + s, s
- .equals("Hello World"));
- }
-
- /**
- * @tests java.io.PrintWriter#write(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {char[].class, int.class, int.class}
- )
- public void test_write$CII() {
- // Test for method void java.io.PrintWriter.write(char [], int, int)
- String s = null;
- char[] schars = new char[11];
- "Hello World".getChars(0, 11, schars, 0);
- pw.println("Random Chars");
- pw.write(schars, 6, 5);
- pw.flush();
- try {
- br = new BufferedReader(new Support_StringReader(baos.toString()));
- br.readLine();
- s = br.readLine();
- } catch (IOException e) {
- fail("IOException during test : " + e.getMessage());
- }
- assertTrue("Wrote incorrect char[] string: " + s, s.equals("World"));
- }
-
- /**
- * @tests java.io.PrintWriter#write(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {char[].class, int.class, int.class}
- )
- public void test_write$CII_Exception() {
- // Test for method void java.io.PrintWriter.write(char [], int, int)
- char[] chars = new char[10];
- try {
- pw.write(chars, 0, -1);
- fail("IndexOutOfBoundsException was not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- pw.write(chars, -1, 1);
- fail("IndexOutOfBoundsException was not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- pw.write(chars, 10, 1);
- fail("IndexOutOfBoundsException was not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.io.PrintWriter#write(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {int.class}
- )
- public void test_writeI() {
- // Test for method void java.io.PrintWriter.write(int)
- char[] cab = new char[3];
- pw.write('a');
- pw.write('b');
- pw.write('c');
- pw.flush();
- bai = new ByteArrayInputStream(baos.toByteArray());
- cab[0] = (char) bai.read();
- cab[1] = (char) bai.read();
- cab[2] = (char) bai.read();
- assertTrue("Wrote incorrect ints", cab[0] == 'a' && cab[1] == 'b'
- && cab[2] == 'c');
-
- }
-
- /**
- * @tests java.io.PrintWriter#write(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {java.lang.String.class}
- )
- public void test_writeLjava_lang_String() {
- // Test for method void java.io.PrintWriter.write(java.lang.String)
- String s = null;
- pw.println("Random Chars");
- pw.write("Hello World");
- pw.flush();
- try {
- br = new BufferedReader(new Support_StringReader(baos.toString()));
- br.readLine();
- s = br.readLine();
- } catch (IOException e) {
- fail("IOException during test : " + e.getMessage());
- }
- assertTrue("Wrote incorrect char[] string: " + s, s
- .equals("Hello World"));
- }
-
- /**
- * @tests java.io.PrintWriter#write(java.lang.String, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {java.lang.String.class, int.class, int.class}
- )
- public void test_writeLjava_lang_StringII() {
- // Test for method void java.io.PrintWriter.write(java.lang.String, int,
- // int)
- String s = null;
- pw.println("Random Chars");
- pw.write("Hello World", 6, 5);
- pw.flush();
- try {
- br = new BufferedReader(new Support_StringReader(baos.toString()));
- br.readLine();
- s = br.readLine();
- } catch (IOException e) {
- fail("IOException during test : " + e.getMessage());
- }
- assertTrue("Wrote incorrect char[] string: " + s, s.equals("World"));
- }
-
- /**
- * @tests java.io.PrintWriter#append(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {char.class}
- )
- public void test_appendChar() {
- char testChar = ' ';
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- PrintWriter printWriter = new PrintWriter(out);
- printWriter.append(testChar);
- printWriter.flush();
- assertEquals(String.valueOf(testChar),out.toString());
- printWriter.close();
- }
- /**
- * @tests java.io.PrintWriter#append(CharSequence)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {java.lang.CharSequence.class}
- )
- public void test_appendCharSequence() {
-
- String testString = "My Test String";
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- PrintWriter printWriter = new PrintWriter(out);
- printWriter.append(testString);
- printWriter.flush();
- assertEquals(testString, out.toString());
- printWriter.close();
-
- }
-
- /**
- * @tests java.io.PrintWriter#append(CharSequence, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {java.lang.CharSequence.class, int.class, int.class}
- )
- public void test_appendCharSequenceIntInt() {
- String testString = "My Test String";
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- PrintWriter printWriter = new PrintWriter(out);
- printWriter.append(testString, 1, 3);
- printWriter.flush();
- assertEquals(testString.substring(1, 3), out.toString());
- try {
- printWriter.append(testString, 4, 100);
- fail("IndexOutOfBoundsException not thrown");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- printWriter.append(testString, 100, 1);
- fail("IndexOutOfBoundsException not thrown");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- printWriter.close();
- }
-
- /**
- * @tests java.io.PrintWriter#format(java.lang.String, java.lang.Object...)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object() {
- PrintWriter tobj;
-
- tobj = new PrintWriter(baos, false);
- tobj.format("%s %s", "Hello", "World");
- tobj.flush();
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- byte[] rbytes = new byte[11];
- bis.read(rbytes, 0, rbytes.length);
- assertEquals("Wrote incorrect string", "Hello World",
- new String(rbytes));
-
- baos.reset();
- tobj = new PrintWriter(baos);
- tobj.format("%1$.3G, %1$.5f, 0%2$xx", 12345.678, 123456);
- tobj.flush();
- assertEquals("Wrong output!", "1.23E+04, 12345.67800, 01e240x", new String(baos.toByteArray()));
- tobj.close();
-
- baos.reset();
- tobj = new PrintWriter(baos);
- try {
- tobj.format("%1$.3G, %1$x", 12345.678);
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
-
- try {
- tobj.format("%s %q", "Hello", "World");
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
-
- try {
- tobj.format("%s %s", "Hello");
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.PrintWriter#format(java.util.Locale, java.lang.String, java.lang.Object...)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "format",
- args = {java.util.Locale.class, java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_util_Locale_Ljava_lang_String_$Ljava_lang_Object() {
- PrintWriter tobj;
-
- tobj = new PrintWriter(baos, false);
- tobj.format(Locale.US, "%s %s", "Hello", "World");
- tobj.flush();
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- byte[] rbytes = new byte[11];
- bis.read(rbytes, 0, rbytes.length);
- assertEquals("Wrote incorrect string", "Hello World",
- new String(rbytes));
-
- baos.reset();
- tobj = new PrintWriter(baos);
- tobj.format(Locale.GERMANY, "%1$.3G; %1$.5f; 0%2$xx", 12345.678, 123456);
- tobj.flush();
- assertEquals("Wrong output!", "1,23E+04; 12345,67800; 01e240x", new String(baos.toByteArray()));
- tobj.close();
-
- baos.reset();
- tobj = new PrintWriter(baos);
- tobj.format(Locale.US, "%1$.3G, %1$.5f, 0%2$xx", 12345.678, 123456);
- tobj.flush();
- assertEquals("Wrong output!", "1.23E+04, 12345.67800, 01e240x", new String(baos.toByteArray()));
- tobj.close();
-
- baos.reset();
- tobj = new PrintWriter(baos);
- try {
- tobj.format(Locale.US, "%1$.3G, %1$x", 12345.678);
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
-
- try {
- tobj.format(Locale.US, "%s %q", "Hello", "World");
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
-
- try {
- tobj.format(Locale.US, "%s %s", "Hello");
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.PrintWriter#printf(java.lang.String, java.lang.Object...)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "printf",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_printfLjava_lang_String$Ljava_lang_Object() {
- PrintWriter tobj;
-
- tobj = new PrintWriter(baos, false);
- tobj.printf("%s %s", "Hello", "World");
- tobj.flush();
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- byte[] rbytes = new byte[11];
- bis.read(rbytes, 0, rbytes.length);
- assertEquals("Wrote incorrect string", "Hello World",
- new String(rbytes));
-
- baos.reset();
- tobj = new PrintWriter(baos);
- tobj.printf("%1$.3G, %1$.5f, 0%2$xx", 12345.678, 123456);
- tobj.flush();
- assertEquals("Wrong output!", "1.23E+04, 12345.67800, 01e240x", new String(baos.toByteArray()));
- tobj.close();
-
- baos.reset();
- tobj = new PrintWriter(baos);
- try {
- tobj.printf("%1$.3G, %1$x", 12345.678);
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
-
- try {
- tobj.printf("%s %q", "Hello", "World");
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
-
- try {
- tobj.printf("%s %s", "Hello");
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.PrintWriter#printf(java.util.Locale, java.lang.String, java.lang.Object...)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "printf",
- args = {java.util.Locale.class, java.lang.String.class, java.lang.Object[].class}
- )
- public void test_printfLjava_util_Locale_Ljava_lang_String_$Ljava_lang_Object() {
- PrintWriter tobj;
-
- tobj = new PrintWriter(baos, false);
- tobj.printf(Locale.US, "%s %s", "Hello", "World");
- tobj.flush();
- ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
- byte[] rbytes = new byte[11];
- bis.read(rbytes, 0, rbytes.length);
- assertEquals("Wrote incorrect string", "Hello World",
- new String(rbytes));
-
- baos.reset();
- tobj = new PrintWriter(baos);
- tobj.printf(Locale.GERMANY, "%1$.3G; %1$.5f; 0%2$xx", 12345.678, 123456);
- tobj.flush();
- assertEquals("Wrong output!", "1,23E+04; 12345,67800; 01e240x", new String(baos.toByteArray()));
- tobj.close();
-
- baos.reset();
- tobj = new PrintWriter(baos);
- tobj.printf(Locale.US, "%1$.3G, %1$.5f, 0%2$xx", 12345.678, 123456);
- tobj.flush();
- assertEquals("Wrong output!", "1.23E+04, 12345.67800, 01e240x", new String(baos.toByteArray()));
- tobj.close();
-
- baos.reset();
- tobj = new PrintWriter(baos);
- try {
- tobj.printf(Locale.US, "%1$.3G, %1$x", 12345.678);
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
-
- try {
- tobj.printf(Locale.US, "%s %q", "Hello", "World");
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
-
- try {
- tobj.printf(Locale.US, "%s %s", "Hello");
- fail("IllegalFormatException not thrown");
- } catch (IllegalFormatException e) {
- // expected
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- @Override
- protected void setUp() throws Exception {
- testFile = File.createTempFile("test", null);
- testFilePath = testFile.getAbsolutePath();
- pw = new PrintWriter(baos, false);
-
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- @Override
- protected void tearDown() throws Exception {
- testFile.delete();
- testFile = null;
- testFilePath = null;
- try {
- pw.close();
- } catch (Exception e) {
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/PushbackInputStreamTest.java b/luni/src/test/java/tests/api/java/io/PushbackInputStreamTest.java
deleted file mode 100644
index 8625664..0000000
--- a/luni/src/test/java/tests/api/java/io/PushbackInputStreamTest.java
+++ /dev/null
@@ -1,466 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.PushbackInputStream;
-
-import tests.support.Support_ASimpleInputStream;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(PushbackInputStream.class)
-public class PushbackInputStreamTest extends junit.framework.TestCase {
-
- Support_ASimpleInputStream underlying = new Support_ASimpleInputStream();
- PushbackInputStream pis;
-
- public String fileString = "Test_All_Tests\nTest_java_io_BufferedInputStream\nTest_java_io_BufferedOutputStream\nTest_java_io_ByteArrayInputStream\nTest_java_io_ByteArrayOutputStream\nTest_java_io_DataInputStream\nTest_java_io_File\nTest_java_io_FileDescriptor\nTest_java_io_FileInputStream\nTest_java_io_FileNotFoundException\nTest_java_io_FileOutputStream\nTest_java_io_FilterInputStream\nTest_java_io_FilterOutputStream\nTest_java_io_InputStream\nTest_java_io_IOException\nTest_java_io_OutputStream\nTest_java_io_PrintStream\nTest_java_io_RandomAccessFile\nTest_java_io_SyncFailedException\nTest_java_lang_AbstractMethodError\nTest_java_lang_ArithmeticException\nTest_java_lang_ArrayIndexOutOfBoundsException\nTest_java_lang_ArrayStoreException\nTest_java_lang_Boolean\nTest_java_lang_Byte\nTest_java_lang_Character\nTest_java_lang_Class\nTest_java_lang_ClassCastException\nTest_java_lang_ClassCircularityError\nTest_java_lang_ClassFormatError\nTest_java_lang_ClassLoader\nTest_java_lang_ClassNotFoundException\nTest_java_lang_CloneNotSupportedException\nTest_java_lang_Double\nTest_java_lang_Error\nTest_java_lang_Exception\nTest_java_lang_ExceptionInInitializerError\nTest_java_lang_Float\nTest_java_lang_IllegalAccessError\nTest_java_lang_IllegalAccessException\nTest_java_lang_IllegalArgumentException\nTest_java_lang_IllegalMonitorStateException\nTest_java_lang_IllegalThreadStateException\nTest_java_lang_IncompatibleClassChangeError\nTest_java_lang_IndexOutOfBoundsException\nTest_java_lang_InstantiationError\nTest_java_lang_InstantiationException\nTest_java_lang_Integer\nTest_java_lang_InternalError\nTest_java_lang_InterruptedException\nTest_java_lang_LinkageError\nTest_java_lang_Long\nTest_java_lang_Math\nTest_java_lang_NegativeArraySizeException\nTest_java_lang_NoClassDefFoundError\nTest_java_lang_NoSuchFieldError\nTest_java_lang_NoSuchMethodError\nTest_java_lang_NullPointerException\nTest_java_lang_Number\nTest_java_lang_NumberFormatException\nTest_java_lang_Object\nTest_java_lang_OutOfMemoryError\nTest_java_lang_RuntimeException\nTest_java_lang_SecurityManager\nTest_java_lang_Short\nTest_java_lang_StackOverflowError\nTest_java_lang_String\nTest_java_lang_StringBuffer\nTest_java_lang_StringIndexOutOfBoundsException\nTest_java_lang_System\nTest_java_lang_Thread\nTest_java_lang_ThreadDeath\nTest_java_lang_ThreadGroup\nTest_java_lang_Throwable\nTest_java_lang_UnknownError\nTest_java_lang_UnsatisfiedLinkError\nTest_java_lang_VerifyError\nTest_java_lang_VirtualMachineError\nTest_java_lang_vm_Image\nTest_java_lang_vm_MemorySegment\nTest_java_lang_vm_ROMStoreException\nTest_java_lang_vm_VM\nTest_java_lang_Void\nTest_java_net_BindException\nTest_java_net_ConnectException\nTest_java_net_DatagramPacket\nTest_java_net_DatagramSocket\nTest_java_net_DatagramSocketImpl\nTest_java_net_InetAddress\nTest_java_net_NoRouteToHostException\nTest_java_net_PlainDatagramSocketImpl\nTest_java_net_PlainSocketImpl\nTest_java_net_Socket\nTest_java_net_SocketException\nTest_java_net_SocketImpl\nTest_java_net_SocketInputStream\nTest_java_net_SocketOutputStream\nTest_java_net_UnknownHostException\nTest_java_util_ArrayEnumerator\nTest_java_util_Date\nTest_java_util_EventObject\nTest_java_util_HashEnumerator\nTest_java_util_Hashtable\nTest_java_util_Properties\nTest_java_util_ResourceBundle\nTest_java_util_tm\nTest_java_util_Vector\n";
-
- /**
- * @tests java.io.PushbackInputStream#PushbackInputStream(java.io.InputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PushbackInputStream",
- args = {java.io.InputStream.class}
- )
- public void test_ConstructorLjava_io_InputStream() {
- // Test for method java.io.PushbackInputStream(java.io.InputStream)
- try {
- pis = new PushbackInputStream(new ByteArrayInputStream("Hello"
- .getBytes()));
- pis.unread("He".getBytes());
- } catch (IOException e) {
- // Correct
- // Pushback buffer should be full
- return;
-
- }
- fail("Failed to throw exception on unread when buffer full");
- }
-
- /**
- * @tests java.io.PushbackInputStream#PushbackInputStream(java.io.InputStream,
- * int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "PushbackInputStream",
- args = {java.io.InputStream.class, int.class}
- )
- public void test_ConstructorLjava_io_InputStreamI() {
- ByteArrayInputStream bas = new ByteArrayInputStream("Hello".getBytes());
- try {
- pis = new PushbackInputStream(bas, 0);
- fail("Test 1: IllegalArgumentException expected.");
- } catch (IllegalArgumentException e) {
- // Expected.
- }
- try {
- pis = new PushbackInputStream(bas, -1);
- fail("Test 2: IllegalArgumentException expected.");
- } catch (IllegalArgumentException e) {
- // Expected.
- }
-
- pis = new PushbackInputStream(bas , 5);
- try {
- pis.unread("Hello world".getBytes());
- fail("Test 3: IOException expected when the unread buffer is full.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "close",
- args = {}
- )
- public void test_close() throws IOException {
- PushbackInputStream tobj;
-
- tobj = new PushbackInputStream(underlying);
- tobj.close();
- tobj.close();
- tobj = new PushbackInputStream(underlying);
- underlying.throwExceptionOnNextUse = true;
- try {
- tobj.close();
- fail("IOException not thrown.");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.io.PushbackInputStream#available()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "",
- method = "available",
- args = {}
- )
- public void test_available() throws IOException {
- PushbackInputStream tobj;
-
- tobj = new PushbackInputStream(underlying);
- assertEquals("Wrong number!", 30, tobj.available());
- underlying.throwExceptionOnNextUse = true;
- try {
- tobj.available();
- fail("IOException not thrown.");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.PushbackInputStream#markSupported()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "markSupported",
- args = {}
- )
- public void test_markSupported() {
- // Test for method boolean java.io.PushbackInputStream.markSupported()
- assertTrue("markSupported returned true", !pis.markSupported());
- }
-
- /**
- * @tests java.io.PushbackInputStream#read()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {}
- )
- public void test_read() throws IOException {
- PushbackInputStream tobj;
-
- tobj = new PushbackInputStream(underlying);
- assertEquals("Test 1: Incorrect byte read;", 66, tobj.read());
- underlying.throwExceptionOnNextUse = true;
- try {
- tobj.read();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // expected
- }
-
- assertEquals("Test 3: Incorrect byte read;",
- fileString.getBytes()[0], pis.read());
- }
-
- /**
- * @tests java.io.PushbackInputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII() throws IOException {
- PushbackInputStream tobj;
- byte[] buf = ("01234567890123456789").getBytes();
-
- tobj = new PushbackInputStream(underlying);
- tobj.read(buf, 6, 5);
- assertEquals("Wrong value read!", "BEGIN", new String(buf, 6, 5));
- assertEquals("Too much read!", "012345BEGIN123456789", new String(buf));
- underlying.throwExceptionOnNextUse = true;
- try {
- tobj.read(buf, 6, 5);
- fail("IOException not thrown.");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.PushbackInputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII_Exception() throws IOException {
- PushbackInputStream tobj;
- byte[] buf = new byte[10];
-
- tobj = new PushbackInputStream(underlying);
- try {
- tobj.read(buf, -1, 1);
- fail("IndexOutOfBoundsException was not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- tobj.read(buf, 0, -1);
- fail("IndexOutOfBoundsException was not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- tobj.read(buf, 10, 1);
- fail("IndexOutOfBoundsException was not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.io.PushbackInputStream#skip(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "skip",
- args = {long.class}
- )
- public void test_skipJ() throws IOException {
- PushbackInputStream tobj;
- byte[] buf = ("01234567890123456789").getBytes();
-
- tobj = new PushbackInputStream(underlying);
- tobj.skip(6);
- assertEquals("Wrong number!", 30 - 6, tobj.available());
- tobj.skip(1000000);
- tobj.skip(1000000);
- underlying.throwExceptionOnNextUse = true;
- try {
- tobj.skip(1);
- fail("IOException not thrown.");
- } catch (IOException e) {
- // expected
- }
-
- // Test for method long java.io.PushbackInputStream.skip(long)
- try {
- buf = new byte[50];
- pis.skip(50);
- pis.read(buf, 0, buf.length);
- assertTrue("a) Incorrect bytes read", new String(buf)
- .equals(fileString.substring(50, 100)));
- pis.unread(buf);
- pis.skip(25);
- byte[] buf2 = new byte[25];
- pis.read(buf2, 0, buf2.length);
- assertTrue("b) Incorrect bytes read", new String(buf2)
- .equals(fileString.substring(75, 100)));
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.PushbackInputStream#unread(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "unread",
- args = {byte[].class}
- )
- public void test_unread$B() throws IOException {
- PushbackInputStream tobj;
- String str2 = "0123456789";
- byte[] buf2 = str2.getBytes();
- byte[] readBuf = new byte[10];
-
- tobj = new PushbackInputStream(underlying, 10);
- tobj.unread(buf2);
- assertEquals("Wrong number!", 30 + 10, tobj.available());
- try {
- tobj.unread(buf2);
- fail("IOException not thrown.");
- } catch (IOException e) {
- // expected
- }
- tobj.read(readBuf);
- assertEquals("Incorrect bytes read", str2, new String(readBuf));
- underlying.throwExceptionOnNextUse = true;
- try {
- tobj.read(buf2);
- fail("IOException not thrown.");
- } catch (IOException e) {
- // expected
- }
-
- // Test for method void java.io.PushbackInputStream.unread(byte [])
- try {
- byte[] buf = new byte[100];
- pis.read(buf, 0, buf.length);
- assertTrue("Incorrect bytes read", new String(buf)
- .equals(fileString.substring(0, 100)));
- pis.unread(buf);
- pis.read(buf, 0, 50);
- assertTrue("Failed to unread bytes", new String(buf, 0, 50)
- .equals(fileString.substring(0, 50)));
- } catch (IOException e) {
- fail("IOException during unread test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.PushbackInputStream#unread(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "unread",
- args = {byte[].class, int.class, int.class}
- )
- public void test_unread$BII() throws IOException {
- PushbackInputStream tobj;
- String str2 = "0123456789";
- byte[] buf2 = (str2 + str2 + str2).getBytes();
- byte[] readBuf = new byte[10];
-
- tobj = new PushbackInputStream(underlying, 10);
- tobj.unread(buf2, 15, 10);
- assertEquals("Wrong number!", 30 + 10, tobj.available());
- try {
- tobj.unread(buf2, 15, 10);
- fail("IOException not thrown.");
- } catch (IOException e) {
- // expected
- }
- tobj.read(readBuf);
- assertEquals("Incorrect bytes read", "5678901234", new String(readBuf));
- underlying.throwExceptionOnNextUse = true;
- try {
- tobj.read(buf2, 15, 10);
- fail("IOException not thrown.");
- } catch (IOException e) {
- // expected
- }
-
- // Test for method void java.io.PushbackInputStream.unread(byte [], int,
- // int)
- try {
- byte[] buf = new byte[100];
- pis.read(buf, 0, buf.length);
- assertTrue("Incorrect bytes read", new String(buf)
- .equals(fileString.substring(0, 100)));
- pis.unread(buf, 50, 50);
- pis.read(buf, 0, 50);
- assertTrue("Failed to unread bytes", new String(buf, 0, 50)
- .equals(fileString.substring(50, 100)));
- } catch (IOException e) {
- fail("IOException during unread test : " + e.getMessage());
- }
-
- try {
- byte[] buf = new byte[10];
- pis.unread(buf, 0, -1);
- fail("IndexOutOfBoundsException was not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- byte[] buf = new byte[10];
- pis.unread(buf, -1, 1);
- fail("IndexOutOfBoundsException was not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- byte[] buf = new byte[10];
- pis.unread(buf, 10, 1);
- fail("IndexOutOfBoundsException was not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.io.PushbackInputStream#unread(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "unread",
- args = {int.class}
- )
- public void test_unreadI() throws IOException {
- PushbackInputStream tobj;
-
- tobj = new PushbackInputStream(underlying);
- tobj.unread(23); // Why does this work?!?
- tobj.skip(2);
- tobj.unread(23);
- assertEquals("Wrong number!", 30, tobj.available());
- assertEquals("Wrong value read!", 23, tobj.read());
- tobj.unread(13);
- try {
- tobj.unread(13);
- fail("IOException not thrown (ACTUALLY NOT SURE WHETHER IT REALLY MUST BE THROWN!).");
- } catch (IOException e) {
- // expected
- }
-
- // Test for method void java.io.PushbackInputStream.unread(int)
- try {
- int x;
- assertTrue("Incorrect byte read", (x = pis.read()) == fileString
- .getBytes()[0]);
- pis.unread(x);
- assertTrue("Failed to unread", pis.read() == x);
- } catch (IOException e) {
- fail("IOException during read test : " + e.getMessage());
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
-
- pis = new PushbackInputStream(new ByteArrayInputStream(fileString
- .getBytes()), 65535);
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- try {
- pis.close();
- } catch (IOException e) {
- fail("IOException during tearDown : " + e.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/PushbackReaderTest.java b/luni/src/test/java/tests/api/java/io/PushbackReaderTest.java
deleted file mode 100644
index 12ffce7..0000000
--- a/luni/src/test/java/tests/api/java/io/PushbackReaderTest.java
+++ /dev/null
@@ -1,673 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.CharArrayReader;
-import java.io.FilterReader;
-import java.io.IOException;
-import java.io.PushbackReader;
-import java.io.Reader;
-import java.io.StringReader;
-
-import tests.support.Support_ASimpleReader;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(PushbackReader.class)
-public class PushbackReaderTest extends junit.framework.TestCase {
-
- Support_ASimpleReader underlying = new Support_ASimpleReader();
- PushbackReader pbr;
-
- String pbString = "Hello World";
-
- /**
- * @tests java.io.PushbackReader#PushbackReader(java.io.Reader)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "PushbackReader",
- args = {java.io.Reader.class}
- )
- public void test_ConstructorLjava_io_Reader() {
- // Test for method java.io.PushbackReader(java.io.Reader)
- try {
- pbr.close();
- pbr = new PushbackReader(new StringReader(pbString));
- char buf[] = new char[5];
- pbr.read(buf, 0, 5);
- pbr.unread(buf);
- fail("Created reader with buffer larger than 1");;
- } catch (IOException e) {
- // Expected
- }
-
- try {
- pbr = new PushbackReader(null);
- } catch (NullPointerException e) {
- // EXpected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.io.PushbackReader#PushbackReader(java.io.Reader, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "PushbackReader",
- args = {java.io.Reader.class, int.class}
- )
- public void test_ConstructorLjava_io_ReaderI() throws IOException {
- PushbackReader tobj;
-
- tobj = new PushbackReader(underlying, 10000);
- tobj = new PushbackReader(underlying, 1);
-
- try {
- tobj = new PushbackReader(underlying, -1);
- tobj.close();
- fail("IOException not thrown.");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- tobj = new PushbackReader(underlying, 0);
- tobj.close();
- fail("IOException not thrown.");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.io.PushbackReader#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "close",
- args = {}
- )
- public void test_close() throws IOException {
- PushbackReader tobj;
-
- tobj = new PushbackReader(underlying);
- tobj.close();
- tobj.close();
- tobj = new PushbackReader(underlying);
- underlying.throwExceptionOnNextUse = true;
- try {
- tobj.close();
- fail("IOException not thrown.");
- } catch (IOException e) {
- // expected
- }
-
- // Test for method void java.io.PushbackReader.close()
- try {
- pbr.close();
- pbr.read();
- } catch (Exception e) {
- return;
- }
- fail("Failed to throw exception reading from closed reader");
-
- }
-
- /**
- * @tests java.io.PushbackReader#mark(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "mark",
- args = {int.class}
- )
- public void test_markI() {
- try {
- pbr.mark(3);
- fail("Test 1: IOException expected because marking is not supported.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.PushbackReader#markSupported()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "markSupported",
- args = {}
- )
- public void test_markSupported() {
- assertFalse("Test 1: markSupported() must return false.",
- pbr.markSupported());
- }
-
- /**
- * @throws IOException
- * @tests java.io.PushbackReader#read()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "read",
- args = {}
- )
- public void test_read() throws IOException {
- PushbackReader tobj;
-
- tobj = new PushbackReader(underlying);
- assertEquals("Wrong value read!", 66, tobj.read());
- underlying.throwExceptionOnNextUse = true;
- try {
- tobj.read();
- fail("IOException not thrown.");
- } catch (IOException e) {
- // expected
- }
-
- // Test for method int java.io.PushbackReader.read()
- try {
- char c;
- pbr.read();
- c = (char) pbr.read();
- assertTrue("Failed to read char: " + c, c == pbString.charAt(1));
- Reader reader = new PushbackReader(new CharArrayReader(
- new char[] { '\u8765' }));
- assertTrue("Wrong double byte character", reader.read() == '\u8765');
- } catch (IOException e) {
- fail("IOException during read test : " + e.getMessage());
- }
- }
-
- /**
- * @throws IOException
- * @tests java.io.PushbackReader#read(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "read",
- args = {char[].class, int.class, int.class}
- )
- public void test_read$CII() throws IOException {
- PushbackReader tobj;
- char[] buf = ("01234567890123456789").toCharArray();
-
- tobj = new PushbackReader(underlying);
- tobj.read(buf, 6, 5);
- assertEquals("Wrong value read!", "BEGIN", new String(buf, 6, 5));
- assertEquals("Too much read!", "012345BEGIN123456789", new String(buf));
- underlying.throwExceptionOnNextUse = true;
- try {
- tobj.read(buf, 6, 5);
- fail("IOException not thrown.");
- } catch (IOException e) {
- // expected
- }
-
- // Test for method int java.io.PushbackReader.read(char [], int, int)
- try {
- char[] c = new char[5];
- pbr.read(c, 0, 5);
- assertTrue("Failed to read chars", new String(c).equals(pbString
- .substring(0, 5)));
-
- assertEquals(0, pbr.read(c, 0, 0));
- assertEquals(c.length, pbr.read(c, 0, c.length));
- assertEquals(0, pbr.read(c, c.length, 0));
- } catch (IOException e) {
- fail("IOException during read test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.PushbackReader#read(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks exceptions.",
- method = "read",
- args = {char[].class, int.class, int.class}
- )
- public void test_read_$CII_Exception() throws IOException {
- pbr = new PushbackReader(new StringReader(pbString), 10);
-
- char[] nullCharArray = null;
- char[] charArray = new char[10];
-
- try {
- pbr.read(nullCharArray, 0, 1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- pbr.read(charArray, 0, -1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- pbr.read(charArray, -1, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- pbr.read(charArray, charArray.length + 1, 0);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- pbr.read(charArray, charArray.length, 1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- pbr.read(charArray, 1, charArray.length);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- pbr.read(charArray, 0, charArray.length + 1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- pbr.close();
-
- try {
- pbr.read(charArray, 0, 1);
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.io.PushbackReader#ready()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Could also add tests where underlying says no but push back buffer has contents.",
- method = "ready",
- args = {}
- )
- public void test_ready() throws IOException {
- PushbackReader tobj;
-
- tobj = new PushbackReader(underlying);
- assertTrue("Should be ready!", tobj.ready());
- underlying.throwExceptionOnNextUse = true;
- try {
- tobj.ready();
- fail("IOException not thrown.");
- } catch (IOException e) {
- // expected
- }
-
- // Test for method boolean java.io.PushbackReader.ready()
- try {
- char[] c = new char[11];
- if (c.length > 0)
- ;// use c to avoid warning msg
- assertTrue("Ready stream returned false to ready()", pbr.ready());
- } catch (IOException e) {
- fail("IOException during ready() test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.PushbackReader#reset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "reset",
- args = {}
- )
- public void test_reset() {
- try {
- pbr.reset();
- } catch (IOException e) {
- // correct
- return;
- }
- fail("reset failed to throw expected IOException");
- }
-
- /**
- * @throws IOException
- * @tests java.io.PushbackReader#unread(char[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "unread",
- args = {char[].class}
- )
- public void test_unread$C() throws IOException {
- PushbackReader tobj;
- String str2 = "0123456789";
- char[] buf2 = str2.toCharArray();
- char[] readBuf = new char[10];
-
- tobj = new PushbackReader(underlying, 10);
- tobj.unread(buf2);
- try {
- tobj.unread(buf2);
- fail("IOException not thrown.");
- } catch (IOException e) {
- // expected
- }
- tobj.read(readBuf);
- assertEquals("Incorrect bytes read", str2, new String(readBuf));
- underlying.throwExceptionOnNextUse = true;
- try {
- tobj.read(buf2);
- fail("IOException not thrown.");
- } catch (IOException e) {
- // expected
- }
-
- // Test for method void java.io.PushbackReader.unread(char [])
- try {
- char[] c = new char[5];
- pbr.read(c, 0, 5);
- pbr.unread(c);
- pbr.read(c, 0, 5);
- assertTrue("Failed to unread chars", new String(c).equals(pbString
- .substring(0, 5)));
- } catch (IOException e) {
- fail("IOException during read test : " + e.getMessage());
- }
- }
-
- /**
- * @throws IOException
- * @tests java.io.PushbackReader#skip(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "skip",
- args = {long.class}
- )
- public void test_skip$J() throws IOException {
- PushbackReader tobj;
-
- tobj = new PushbackReader(underlying);
- tobj.skip(6);
- tobj.skip(1000000);
- tobj.skip(1000000);
- underlying.throwExceptionOnNextUse = true;
- try {
- tobj.skip(1);
- fail("IOException not thrown.");
- } catch (IOException e) {
- // expected
- }
-
- char chars[] = new char[] { 'h', 'e', 'l', 'l', 'o' };
- for (int i = 0; i < 3; i++) {
- Reader reader, reader2;
- switch (i) {
- case 0:
- reader = new StringReader(new String(chars));
- reader2 = new StringReader(new String(chars));
- break;
- case 1:
- reader = new FilterReader(new StringReader(new String(chars))) {
- };
- reader2 = new FilterReader(new StringReader(new String(chars))) {
- };
- break;
- default:
- reader = new CharArrayReader(chars);
- reader2 = new CharArrayReader(chars);
- }
- PushbackReader pReader = new PushbackReader(reader, 2);
- PushbackReader pReader2 = new PushbackReader(reader2, 2);
- boolean skipped = false;
- long numSkipped = 0;
- try {
- numSkipped = pReader2.skip(3);
- pReader2.unread('a');
- pReader2.unread('b');
- numSkipped += pReader2.skip(10);
- numSkipped += pReader2.skip(10);
- numSkipped += pReader2.skip(10);
- numSkipped += pReader2.skip(10);
- numSkipped += pReader2.skip(10);
- numSkipped += pReader2.skip(10);
- assertEquals("Did not skip correct number of characters",
- 7, numSkipped);
- numSkipped = 0;
- numSkipped += pReader.skip(2);
- pReader.unread('i');
- numSkipped += pReader.skip(2);
- numSkipped += pReader.skip(0);
- skipped = true;
- numSkipped += pReader.skip(-1);
- fail("Failed to throw "
- + new IllegalArgumentException().getClass().getName());
- } catch (IllegalArgumentException e) {
- assertTrue("Failed to skip characters" + e, skipped);
- } catch (IOException e) {
- fail("Failed to skip characters" + e);
- }
- try {
- numSkipped += pReader.skip(1);
- numSkipped += pReader.skip(1);
- numSkipped += pReader.skip(1);
- assertEquals("Failed to skip all characters", 6, numSkipped);
- long nextSkipped = pReader.skip(1);
- assertEquals("skipped empty reader", 0, nextSkipped);
- } catch (IOException e) {
- fail("Failed to skip more characters" + e);
- }
- }
- }
-
- /**
- * @throws IOException
- * @tests java.io.PushbackReader#unread(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "unread",
- args = {char[].class, int.class, int.class}
- )
- public void test_unread$CII() throws IOException {
- PushbackReader tobj;
- String str2 = "0123456789";
- char[] buf2 = (str2 + str2 + str2).toCharArray();
- char[] readBuf = new char[10];
-
- tobj = new PushbackReader(underlying, 10);
- tobj.unread(buf2, 15, 10);
- try {
- tobj.unread(buf2, 15, 10);
- fail("IOException not thrown.");
- } catch (IOException e) {
- // expected
- }
- tobj.read(readBuf);
- assertEquals("Incorrect bytes read", "5678901234", new String(readBuf));
- underlying.throwExceptionOnNextUse = true;
- try {
- tobj.read(buf2, 15, 10);
- fail("IOException not thrown.");
- } catch (IOException e) {
- // expected
- }
-
- // Test for method void java.io.PushbackReader.unread(char [], int, int)
- try {
- char[] c = new char[5];
- pbr.read(c, 0, 5);
- pbr.unread(c, 0, 2);
- pbr.read(c, 0, 5);
- assertTrue("Failed to unread chars", new String(c).equals(pbString
- .substring(0, 2)
- + pbString.substring(5, 8)));
- } catch (IOException e) {
- fail("IOException during unread test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.PushbackReader#unread(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "unread",
- args = {char[].class, int.class, int.class}
- )
- public void test_unread_$CII_NullPointerException() throws IOException {
- //a pushback reader with one character buffer
- pbr = new PushbackReader(new StringReader(pbString));
-
- try {
- pbr.unread(null, 0, 1);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.PushbackReader#unread(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "unread",
- args = {char[].class, int.class, int.class}
- )
- public void test_unread_$CII_Exception_InsufficientBuffer() throws IOException {
- //a pushback reader with one character buffer
- pbr = new PushbackReader(new StringReader(pbString));
-
- //if count > buffer's size , should throw IOException
- try {
- pbr.unread(new char[pbString.length()], 0, 2);
- fail("should throw IOException");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.PushbackReader#unread(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "unread",
- args = {char[].class, int.class, int.class}
- )
- public void test_unread_$CII_ArrayIndexOutOfBoundsException() throws IOException {
- //a pushback reader with one character buffer
- pbr = new PushbackReader(new StringReader(pbString));
-
- try {
- pbr.unread(new char[pbString.length()], -1 , 1);
- fail("should throw ArrayIndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- pbr.unread(new char[pbString.length()], 0 , -1);
- fail("should throw ArrayIndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- pbr.unread(new char[10], 10 , 1);
- fail("should throw ArrayIndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.io.PushbackReader#unread(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "unread",
- args = {int.class}
- )
- public void test_unreadI() throws IOException {
- PushbackReader tobj;
-
- tobj = new PushbackReader(underlying);
- tobj.unread(23); // Why does this work?!?
- tobj.skip(2);
- tobj.unread(23);
- assertEquals("Wrong value read!", 23, tobj.read());
- tobj.unread(13);
- try {
- tobj.unread(13);
- fail("IOException not thrown (ACTUALLY NOT SURE WHETHER IT REALLY MUST BE THROWN!).");
- } catch (IOException e) {
- // expected
- }
-
- // Test for method void java.io.PushbackReader.unread(int)
- try {
- int c;
- pbr.read();
- c = pbr.read();
- pbr.unread(c);
- assertTrue("Failed to unread char", pbr.read() == c);
- } catch (IOException e) {
- fail("IOException during unread test : " + e.getMessage());
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- pbr = new PushbackReader(new StringReader(pbString), 10);
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- try {
- pbr.close();
- } catch (IOException e) {
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/RandomAccessFileTest.java b/luni/src/test/java/tests/api/java/io/RandomAccessFileTest.java
deleted file mode 100644
index 3b545e3..0000000
--- a/luni/src/test/java/tests/api/java/io/RandomAccessFileTest.java
+++ /dev/null
@@ -1,1504 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.EOFException;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.RandomAccessFile;
-
-import java.nio.channels.FileChannel;
-import java.nio.channels.NonWritableChannelException;
-
-@TestTargetClass(RandomAccessFile.class)
-public class RandomAccessFileTest extends junit.framework.TestCase {
-
- public String fileName;
-
- public boolean ufile = true;
-
- java.io.RandomAccessFile raf;
-
- java.io.File f;
-
- String unihw = "\u0048\u0065\u006C\u0801\u006C\u006F\u0020\u0057\u0081\u006F\u0072\u006C\u0064";
-
- static final String testString = "Lorem ipsum dolor sit amet,\n" +
- "consectetur adipisicing elit,\nsed do eiusmod tempor incididunt ut" +
- "labore et dolore magna aliqua.\n";
- static final int testLength = testString.length();
-
- /**
- * @tests java.io.RandomAccessFile#RandomAccessFile(java.io.File,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "RandomAccessFile",
- args = {java.io.File.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_io_FileLjava_lang_String() throws Exception {
- RandomAccessFile raf = null;
- File tmpFile = new File(fileName);
-
- try {
- raf = new java.io.RandomAccessFile(tmpFile, "r");
- fail("Test 1: FileNotFoundException expected.");
- } catch (FileNotFoundException e) {
- // Expected.
- } catch (IllegalArgumentException e) {
- fail("Test 2: Unexpected IllegalArgumentException: " + e.getMessage());
- }
-
- tmpFile.createNewFile();
-
- try {
- // Checking the remaining valid mode parameters.
- try {
- raf = new java.io.RandomAccessFile(tmpFile, "rwd");
- } catch (IllegalArgumentException e) {
- fail("Test 3: Unexpected IllegalArgumentException: " + e.getMessage());
- }
- raf.close();
- try {
- raf = new java.io.RandomAccessFile(tmpFile, "rws");
- } catch (IllegalArgumentException e) {
- fail("Test 4: Unexpected IllegalArgumentException: " + e.getMessage());
- }
- raf.close();
- try {
- raf = new java.io.RandomAccessFile(tmpFile, "rw");
- } catch (IllegalArgumentException e) {
- fail("Test 5: Unexpected IllegalArgumentException: " + e.getMessage());
- }
- raf.close();
-
- // Checking an invalid mode parameter.
- try {
- raf = new java.io.RandomAccessFile(tmpFile, "i");
- fail("Test 6: IllegalArgumentException expected.");
- } catch (IllegalArgumentException e) {
- // Expected.
- }
- } finally {
- if (raf != null ) raf.close();
- tmpFile.delete();
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#RandomAccessFile(java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "RandomAccessFile",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_String()
- throws IOException {
- RandomAccessFile raf = null;
- File tmpFile = new File(fileName);
-
- try {
- raf = new java.io.RandomAccessFile(fileName, "r");
- fail("Test 1: FileNotFoundException expected.");
- } catch (FileNotFoundException e) {
- // Expected.
- } catch (IllegalArgumentException e) {
- fail("Test 2: Unexpected IllegalArgumentException: " + e.getMessage());
- }
-
- try {
- // Checking the remaining valid mode parameters.
- try {
- raf = new java.io.RandomAccessFile(fileName, "rwd");
- } catch (IllegalArgumentException e) {
- fail("Test 3: Unexpected IllegalArgumentException: " + e.getMessage());
- }
- raf.close();
- try {
- raf = new java.io.RandomAccessFile(fileName, "rws");
- } catch (IllegalArgumentException e) {
- fail("Test 4: Unexpected IllegalArgumentException: " + e.getMessage());
- }
- raf.close();
- try {
- raf = new java.io.RandomAccessFile(fileName, "rw");
- } catch (IllegalArgumentException e) {
- fail("Test 5: Unexpected IllegalArgumentException: " + e.getMessage());
- }
- raf.close();
-
- // Checking an invalid mode parameter.
- try {
- raf = new java.io.RandomAccessFile(fileName, "i");
- fail("Test 6: IllegalArgumentException expected.");
- } catch (IllegalArgumentException e) {
- // Expected.
- }
-
- // Checking for NoWritableChannelException.
- raf = new java.io.RandomAccessFile(fileName, "r");
- FileChannel fcr = raf.getChannel();
-
- try {
- fcr.lock(0L, Long.MAX_VALUE, false);
- fail("Test 7: NonWritableChannelException expected.");
- } catch (NonWritableChannelException e) {
- // Expected.
- }
-
- } finally {
- if (raf != null ) raf.close();
- if (tmpFile.exists()) tmpFile.delete();
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#close()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "No IOException checking, requires native code that can be forced to throw such an exception.",
- method = "close",
- args = {}
- )
- public void test_close() {
- // Test for method void java.io.RandomAccessFile.close()
- try {
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.close();
- raf.write("Test".getBytes(), 0, 4);
- fail("Failed to close file properly.");
- } catch (IOException e) {}
- }
-
- /**
- * @tests java.io.RandomAccessFile#getChannel()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getChannel",
- args = {}
- )
- public void test_getChannel() throws IOException {
-
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- FileChannel fc = raf.getChannel();
-
- // Indirect test: If the file's file pointer moves then the position
- // in the channel has to move accordingly.
- assertTrue("Test 1: Channel position expected to be 0.", fc.position() == 0);
-
- raf.write(testString.getBytes());
- assertEquals("Test 2: Unexpected channel position.",
- testLength, fc.position());
- assertTrue("Test 3: Channel position is not equal to file pointer.",
- fc.position() == raf.getFilePointer());
- raf.close();
- }
-
- /**
- * @tests java.io.RandomAccessFile#getFD()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "No IOException checking since this exception is not thrown.",
- method = "getFD",
- args = {}
- )
- public void test_getFD() throws IOException {
- // Test for method java.io.FileDescriptor
- // java.io.RandomAccessFile.getFD()
-
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- assertTrue("Test 1: Returned invalid fd.", raf.getFD().valid());
-
- raf.close();
- assertFalse("Test 2: Returned valid fd after close", raf.getFD().valid());
- }
-
- /**
- * @tests java.io.RandomAccessFile#getFilePointer()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFilePointer",
- args = {}
- )
- public void test_getFilePointer() throws IOException {
- // Test for method long java.io.RandomAccessFile.getFilePointer()
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.write(testString.getBytes(), 0, testLength);
- assertEquals("Test 1: Incorrect filePointer returned. ", testLength, raf
- .getFilePointer());
- raf.close();
- try {
- raf.getFilePointer();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#length()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "length",
- args = {}
- )
- public void test_length() throws IOException {
- // Test for method long java.io.RandomAccessFile.length()
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.write(testString.getBytes());
- assertEquals("Test 1: Incorrect length returned. ", testLength,
- raf.length());
- raf.close();
- try {
- raf.length();
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#read()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "read",
- args = {}
- )
- })
- public void test_read_write() throws IOException {
- int i;
- byte[] testBuf = testString.getBytes();
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- for (i = 0; i < testString.length(); i++) {
- try {
- raf.write(testBuf[i]);
- } catch (Exception e) {
- fail("Test 1: Unexpected exception while writing: "
- + e.getMessage());
- }
- }
-
- raf.seek(0);
-
- for (i = 0; i < testString.length(); i++) {
- assertEquals(String.format("Test 2: Incorrect value written or read at index %d; ", i),
- testBuf[i], raf.read());
- }
-
- assertTrue("Test 3: End of file indicator (-1) expected.", raf.read() == -1);
-
- raf.close();
- try {
- raf.write(42);
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- try {
- raf.read();
- fail("Test 5: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#read(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "read",
- args = {byte[].class}
- )
- public void test_read$B() throws IOException {
- FileOutputStream fos = new java.io.FileOutputStream(fileName);
- fos.write(testString.getBytes(), 0, testLength);
- fos.close();
-
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r");
- byte[] rbuf = new byte[testLength + 10];
-
- int bytesRead = raf.read(rbuf);
- assertEquals("Test 1: Incorrect number of bytes read. ",
- testLength, bytesRead);
- assertEquals("Test 2: Incorrect bytes read. ", testString,
- new String(rbuf, 0, testLength));
-
- bytesRead = raf.read(rbuf);
- assertTrue("Test 3: EOF (-1) expected. ", bytesRead == -1);
-
- raf.close();
- try {
- bytesRead = raf.read(rbuf);
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII() throws IOException {
- int bytesRead;
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- byte[] rbuf = new byte[4000];
-
- FileOutputStream fos = new java.io.FileOutputStream(fileName);
- fos.write(testString.getBytes(), 0, testLength);
- fos.close();
-
- // Read half of the file contents.
- bytesRead = raf.read(rbuf, 10, testLength / 2);
- assertEquals("Test 1: Incorrect number of bytes read. ",
- testLength / 2, bytesRead);
- assertEquals("Test 2: Incorrect bytes read. ",
- testString.substring(0, testLength / 2),
- new String(rbuf, 10, testLength / 2));
-
- // Read the rest of the file contents.
- bytesRead = raf.read(rbuf, 0, testLength);
- assertEquals("Test 3: Incorrect number of bytes read. ",
- testLength - (testLength / 2), bytesRead);
- assertEquals("Test 4: Incorrect bytes read. ",
- testString.substring(testLength / 2, (testLength / 2) + bytesRead),
- new String(rbuf, 0, bytesRead));
-
- // Try to read even more.
- bytesRead = raf.read(rbuf, 0, 1);
- assertTrue("Test 5: EOF (-1) expected. ", bytesRead == -1);
-
- // Illegal parameter value tests.
- try {
- raf.read(rbuf, -1, 1);
- fail("Test 6: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
- try {
- raf.read(rbuf, 0, -1);
- fail("Test 7: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
- try {
- raf.read(rbuf, 2000, 2001);
- fail("Test 8: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- // IOException test.
- raf.close();
- try {
- bytesRead = raf.read(rbuf, 0, 1);
- fail("Test 9: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#readBoolean()
- * @tests java.io.RandomAccessFile#writeBoolean(boolean)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeBoolean",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readBoolean",
- args = {}
- )
- })
- public void test_read_writeBoolean() throws IOException {
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeBoolean(true);
- raf.writeBoolean(false);
- raf.seek(0);
-
- assertEquals("Test 1: Incorrect value written or read;",
- true, raf.readBoolean());
- assertEquals("Test 2: Incorrect value written or read;",
- false, raf.readBoolean());
-
- try {
- raf.readBoolean();
- fail("Test 3: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- raf.close();
- try {
- raf.writeBoolean(false);
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- try {
- raf.readBoolean();
- fail("Test 5: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#readByte()
- * @tests java.io.RandomAccessFile#writeByte(byte)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeByte",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readByte",
- args = {}
- )
- })
- public void test_read_writeByte() throws IOException {
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeByte(Byte.MIN_VALUE);
- raf.writeByte(11);
- raf.writeByte(Byte.MAX_VALUE);
- raf.writeByte(Byte.MIN_VALUE - 1);
- raf.writeByte(Byte.MAX_VALUE + 1);
- raf.seek(0);
-
- assertEquals("Test 1: Incorrect value written or read;",
- Byte.MIN_VALUE, raf.readByte());
- assertEquals("Test 2: Incorrect value written or read;",
- 11, raf.readByte());
- assertEquals("Test 3: Incorrect value written or read;",
- Byte.MAX_VALUE, raf.readByte());
- assertEquals("Test 4: Incorrect value written or read;",
- 127, raf.readByte());
- assertEquals("Test 5: Incorrect value written or read;",
- -128, raf.readByte());
-
- try {
- raf.readByte();
- fail("Test 6: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- raf.close();
- try {
- raf.writeByte(13);
- fail("Test 7: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- try {
- raf.readByte();
- fail("Test 8: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#readChar()
- * @tests java.io.RandomAccessFile#writeChar(char)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeChar",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readChar",
- args = {}
- )
- })
- public void test_read_writeChar() throws IOException {
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeChar(Character.MIN_VALUE);
- raf.writeChar('T');
- raf.writeChar(Character.MAX_VALUE);
- raf.writeChar(Character.MIN_VALUE - 1);
- raf.writeChar(Character.MAX_VALUE + 1);
- raf.seek(0);
-
- assertEquals("Test 1: Incorrect value written or read;",
- Character.MIN_VALUE, raf.readChar());
- assertEquals("Test 2: Incorrect value written or read;",
- 'T', raf.readChar());
- assertEquals("Test 3: Incorrect value written or read;",
- Character.MAX_VALUE, raf.readChar());
- assertEquals("Test 4: Incorrect value written or read;",
- 0xffff, raf.readChar());
- assertEquals("Test 5: Incorrect value written or read;",
- 0, raf.readChar());
-
- try {
- raf.readChar();
- fail("Test 6: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- raf.close();
- try {
- raf.writeChar('E');
- fail("Test 7: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- try {
- raf.readChar();
- fail("Test 8: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#readDouble()
- * @tests java.io.RandomAccessFile#writeDouble(double)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeDouble",
- args = {double.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readDouble",
- args = {}
- )
- })
- public void test_read_writeDouble() throws IOException {
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeDouble(Double.MAX_VALUE);
- raf.writeDouble(424242.4242);
- raf.seek(0);
-
- assertEquals("Test 1: Incorrect value written or read;",
- Double.MAX_VALUE, raf.readDouble());
- assertEquals("Test 2: Incorrect value written or read;",
- 424242.4242, raf.readDouble());
-
- try {
- raf.readDouble();
- fail("Test 3: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- raf.close();
- try {
- raf.writeDouble(Double.MIN_VALUE);
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- try {
- raf.readDouble();
- fail("Test 5: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#readFloat()
- * @tests java.io.RandomAccessFile#writeFloat(double)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeFloat",
- args = {float.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readFloat",
- args = {}
- )
- })
- public void test_read_writeFloat() throws IOException {
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeFloat(Float.MAX_VALUE);
- raf.writeFloat(555.55f);
- raf.seek(0);
-
- assertEquals("Test 1: Incorrect value written or read. ",
- Float.MAX_VALUE, raf.readFloat());
- assertEquals("Test 2: Incorrect value written or read. ",
- 555.55f, raf.readFloat());
-
- try {
- raf.readFloat();
- fail("Test 3: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- raf.close();
- try {
- raf.writeFloat(Float.MIN_VALUE);
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- try {
- raf.readFloat();
- fail("Test 5: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#readInt()
- * @tests java.io.RandomAccessFile#writeInt(char)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeInt",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readInt",
- args = {}
- )
- })
- public void test_read_writeInt() throws IOException {
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeInt(Integer.MIN_VALUE);
- raf.writeInt('T');
- raf.writeInt(Integer.MAX_VALUE);
- raf.writeInt(Integer.MIN_VALUE - 1);
- raf.writeInt(Integer.MAX_VALUE + 1);
- raf.seek(0);
-
- assertEquals("Test 1: Incorrect value written or read;",
- Integer.MIN_VALUE, raf.readInt());
- assertEquals("Test 2: Incorrect value written or read;",
- 'T', raf.readInt());
- assertEquals("Test 3: Incorrect value written or read;",
- Integer.MAX_VALUE, raf.readInt());
- assertEquals("Test 4: Incorrect value written or read;",
- 0x7fffffff, raf.readInt());
- assertEquals("Test 5: Incorrect value written or read;",
- 0x80000000, raf.readInt());
-
- try {
- raf.readInt();
- fail("Test 6: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- raf.close();
- try {
- raf.writeInt('E');
- fail("Test 7: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- try {
- raf.readInt();
- fail("Test 8: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#readLong()
- * @tests java.io.RandomAccessFile#writeLong(char)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeLong",
- args = {long.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readLong",
- args = {}
- )
- })
- public void test_read_writeLong() throws IOException {
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeLong(Long.MIN_VALUE);
- raf.writeLong('T');
- raf.writeLong(Long.MAX_VALUE);
- raf.writeLong(Long.MIN_VALUE - 1);
- raf.writeLong(Long.MAX_VALUE + 1);
- raf.seek(0);
-
- assertEquals("Test 1: Incorrect value written or read;",
- Long.MIN_VALUE, raf.readLong());
- assertEquals("Test 2: Incorrect value written or read;",
- 'T', raf.readLong());
- assertEquals("Test 3: Incorrect value written or read;",
- Long.MAX_VALUE, raf.readLong());
- assertEquals("Test 4: Incorrect value written or read;",
- 0x7fffffffffffffffl, raf.readLong());
- assertEquals("Test 5: Incorrect value written or read;",
- 0x8000000000000000l, raf.readLong());
-
- try {
- raf.readLong();
- fail("Test 6: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- raf.close();
- try {
- raf.writeLong('E');
- fail("Test 7: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- try {
- raf.readLong();
- fail("Test 8: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#readShort()
- * @tests java.io.RandomAccessFile#writeShort(short)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeShort",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readShort",
- args = {}
- )
- })
- public void test_read_writeShort() throws IOException {
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeShort(Short.MIN_VALUE);
- raf.writeShort('T');
- raf.writeShort(Short.MAX_VALUE);
- raf.writeShort(Short.MIN_VALUE - 1);
- raf.writeShort(Short.MAX_VALUE + 1);
- raf.seek(0);
-
- assertEquals("Test 1: Incorrect value written or read;",
- Short.MIN_VALUE, raf.readShort());
- assertEquals("Test 2: Incorrect value written or read;",
- 'T', raf.readShort());
- assertEquals("Test 3: Incorrect value written or read;",
- Short.MAX_VALUE, raf.readShort());
- assertEquals("Test 4: Incorrect value written or read;",
- 0x7fff, raf.readShort());
- assertEquals("Test 5: Incorrect value written or read;",
- (short) 0x8000, raf.readShort());
-
- try {
- raf.readShort();
- fail("Test 6: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- raf.close();
- try {
- raf.writeShort('E');
- fail("Test 7: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- try {
- raf.readShort();
- fail("Test 8: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#readUTF()
- * @tests java.io.RandomAccessFile#writeShort(char)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeUTF",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readUTF",
- args = {}
- )
- })
- public void test_read_writeUTF() throws IOException {
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeUTF(unihw);
- raf.seek(0);
- assertEquals("Test 1: Incorrect UTF string written or read;",
- unihw, raf.readUTF());
-
- try {
- raf.readUTF();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- raf.close();
- try {
- raf.writeUTF("Already closed.");
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- try {
- raf.readUTF();
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#writeBytes(java.lang.String)
- * @tests java.io.RandomAccessFile#readFully(byte[])
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeBytes",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readFully",
- args = {byte[].class}
- )
- })
- public void test_readFully$B_writeBytesLjava_lang_String() throws IOException {
- byte[] buf = new byte[testLength];
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeBytes(testString);
- raf.seek(0);
-
- try {
- raf.readFully(null);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
-
- raf.readFully(buf);
- assertEquals("Test 2: Incorrect bytes written or read;",
- testString, new String(buf));
-
- try {
- raf.readFully(buf);
- fail("Test 3: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- raf.close();
- try {
- raf.writeBytes("Already closed.");
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- try {
- raf.readFully(buf);
- fail("Test 5: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#writeBytes(java.lang.String)
- * @tests java.io.RandomAccessFile#readFully(byte[], int, int)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeBytes",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readFully",
- args = {byte[].class, int.class, int.class}
- )
- })
- public void test_readFully$BII() throws IOException {
- byte[] buf = new byte[testLength];
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeBytes(testString);
- raf.seek(0);
-
- try {
- raf.readFully(null);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
-
- raf.readFully(buf, 5, testLength - 10);
- for (int i = 0; i < 5; i++) {
- assertEquals("Test 2: Incorrect bytes read;", 0, buf[i]);
- }
- assertEquals("Test 3: Incorrect bytes written or read;",
- testString.substring(0, testLength - 10),
- new String(buf, 5, testLength - 10));
-
- // Reading past the end of the file.
- try {
- raf.readFully(buf, 3, testLength - 6);
- fail("Test 4: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- // Passing invalid arguments.
- try {
- raf.readFully(buf, -1, 1);
- fail("Test 5: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
- try {
- raf.readFully(buf, 0, -1);
- fail("Test 6: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
- try {
- raf.readFully(buf, 2, testLength);
- fail("Test 7: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- }
-
- // Reading from a closed file.
- raf.close();
- try {
- raf.readFully(buf);
- fail("Test 8: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#readUnsignedByte()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readUnsignedByte",
- args = {}
- )
- public void test_readUnsignedByte() throws IOException {
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeByte(-1);
- raf.seek(0);
-
- assertEquals("Test 1: Incorrect value written or read;",
- 255, raf.readUnsignedByte());
-
- try {
- raf.readUnsignedByte();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- raf.close();
- try {
- raf.readUnsignedByte();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#readUnsignedShort()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "readUnsignedShort",
- args = {}
- )
- public void test_readUnsignedShort() throws IOException {
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeShort(-1);
- raf.seek(0);
-
- assertEquals("Test 1: Incorrect value written or read;",
- 65535, raf.readUnsignedShort());
-
- try {
- raf.readUnsignedShort();
- fail("Test 2: EOFException expected.");
- } catch (EOFException e) {
- // Expected.
- }
-
- raf.close();
- try {
- raf.readUnsignedShort();
- fail("Test 3: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#readLine()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "",
- method = "readLine",
- args = {}
- )
- public void test_readLine() throws IOException {
- // Test for method java.lang.String java.io.RandomAccessFile.readLine()
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- String s = "Goodbye\nCruel\nWorld\n";
- raf.write(s.getBytes(), 0, s.length());
- raf.seek(0);
-
- assertEquals("Test 1: Incorrect line read;", "Goodbye", raf.readLine());
- assertEquals("Test 2: Incorrect line read;", "Cruel", raf.readLine());
- assertEquals("Test 3: Incorrect line read;", "World", raf.readLine());
- assertNull("Test 4: Incorrect line read; null expected.", raf.readLine());
-
- raf.close();
- try {
- raf.readLine();
- fail("Test 5: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- }
-
- /**
- * @tests java.io.RandomAccessFile#seek(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "seek",
- args = {long.class}
- )
- public void test_seekJ() throws IOException {
- // Test for method void java.io.RandomAccessFile.seek(long)
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
-
- try {
- raf.seek(-1);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- raf.write(testString.getBytes(), 0, testLength);
- raf.seek(12);
- assertEquals("Test 2: Seek failed to set file pointer.", 12,
- raf.getFilePointer());
-
- raf.close();
- try {
- raf.seek(1);
- fail("Test 1: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#skipBytes(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "skipBytes",
- args = {int.class}
- )
- public void test_skipBytesI() throws IOException {
- byte[] buf = new byte[5];
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeBytes("HelloWorld");
- raf.seek(0);
-
- assertTrue("Test 1: Nothing should be skipped if parameter is less than zero",
- raf.skipBytes(-1) == 0);
-
- assertEquals("Test 4: Incorrect number of bytes skipped; ",
- 5, raf.skipBytes(5));
-
- raf.readFully(buf);
- assertEquals("Test 3: Failed to skip bytes.",
- "World", new String(buf, 0, 5));
-
- raf.seek(0);
- assertEquals("Test 4: Incorrect number of bytes skipped; ",
- 10, raf.skipBytes(20));
-
- raf.close();
- try {
- raf.skipBytes(1);
- fail("Test 5: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#skipBytes(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setLength",
- args = {long.class}
- )
- public void test_setLengthJ() throws IOException {
- int bytesRead;
- long truncLength = (long) (testLength * 0.75);
- byte[] rbuf = new byte[testLength + 10];
-
- // Setup the test file.
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.write(testString.getBytes());
- assertEquals("Test 1: Incorrect file length;",
- testLength, raf.length());
-
- // Truncate the file.
- raf.setLength(truncLength);
- assertTrue("Test 2: File pointer not moved to the end of the truncated file.",
- raf.getFilePointer() == truncLength);
-
- raf.close();
- raf = new java.io.RandomAccessFile(fileName, "rw");
- assertEquals("Test 3: Incorrect file length;",
- truncLength, raf.length());
- bytesRead = raf.read(rbuf);
- assertEquals("Test 4: Incorrect number of bytes read;",
- truncLength, bytesRead);
- assertEquals("Test 5: Incorrect bytes read. ",
- testString.substring(0, bytesRead),
- new String(rbuf, 0, bytesRead));
-
- // Expand the file.
- raf.setLength(testLength + 2);
- assertTrue("Test 6: File pointer incorrectly moved.",
- raf.getFilePointer() == truncLength);
- assertEquals("Test 7: Incorrect file length;",
- testLength + 2, raf.length());
-
- // Exception testing.
- try {
- raf.setLength(-1);
- fail("Test 8: IllegalArgumentException expected.");
- } catch (IllegalArgumentException e) {
- // Expected.
- }
-
- raf.close();
- try {
- raf.setLength(truncLength);
- fail("Test 9: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.RandomAccessFile#write(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {byte[].class}
- )
- public void test_write$B() throws IOException {
- byte[] rbuf = new byte[4000];
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
-
- byte[] nullByteArray = null;
- try {
- raf.write(nullByteArray);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
-
- try {
- raf.write(testString.getBytes());
- } catch (Exception e) {
- fail("Test 2: Unexpected exception: " + e.getMessage());
- }
-
- raf.close();
-
- try {
- raf.write(new byte[0]);
- } catch (IOException e) {
- fail("Test 3: Unexpected IOException: " + e.getMessage());
- }
-
- try {
- raf.write(testString.getBytes());
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- FileInputStream fis = new java.io.FileInputStream(fileName);
- fis.read(rbuf, 0, testLength);
- assertEquals("Incorrect bytes written", testString, new String(rbuf, 0,
- testLength));
- }
-
- /**
- * @tests java.io.RandomAccessFile#write(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {byte[].class, int.class, int.class}
- )
- public void test_write$BII() throws Exception {
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- byte[] rbuf = new byte[4000];
- byte[] testBuf = null;
- int bytesRead;
-
- try {
- raf.write(testBuf, 1, 1);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
-
- testBuf = testString.getBytes();
-
- try {
- raf.write(testBuf, -1, 10);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- assertEquals(
- "Test 2: IndexOutOfBoundsException rather than a subclass expected.",
- IndexOutOfBoundsException.class, e.getClass());
- }
-
- try {
- raf.write(testBuf, 0, -1);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- assertEquals(
- "Test 3: IndexOutOfBoundsException rather than a subclass expected.",
- IndexOutOfBoundsException.class, e.getClass());
- }
-
- try {
- raf.write(testBuf, 5, testLength);
- fail("Test 4: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
- assertEquals(
- "Test 4: IndexOutOfBoundsException rather than a subclass expected.",
- IndexOutOfBoundsException.class, e.getClass());
- }
-
- // Positive test: The following write should not fail.
- try {
- raf.write(testBuf, 3, testLength - 5);
- } catch (Exception e) {
- fail("Test 5: Unexpected exception: " + e.getMessage());
- }
-
- raf.close();
-
- // Writing nothing to a closed file should not fail either.
- try {
- raf.write(new byte[0]);
- } catch (IOException e) {
- fail("Test 6: Unexpected IOException: " + e.getMessage());
- }
-
- // Writing something to a closed file should fail.
- try {
- raf.write(testString.getBytes());
- fail("Test 7: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- FileInputStream fis = new java.io.FileInputStream(fileName);
- bytesRead = fis.read(rbuf, 0, testLength);
- assertEquals("Test 8: Incorrect number of bytes written or read;",
- testLength - 5, bytesRead);
- assertEquals("Test 9: Incorrect bytes written or read; ",
- testString.substring(3, testLength - 2),
- new String(rbuf, 0, bytesRead));
- }
-
- /**
- * @tests java.io.RandomAccessFile#writeChars(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Tests against golden file missing.",
- method = "writeChars",
- args = {java.lang.String.class}
- )
- public void test_writeCharsLjava_lang_String() throws IOException {
- RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
- raf.writeChars(unihw);
- char[] hchars = new char[unihw.length()];
- unihw.getChars(0, unihw.length(), hchars, 0);
- raf.seek(0);
- for (int i = 0; i < hchars.length; i++)
- assertEquals("Test 1: Incorrect character written or read at index " + i + ";",
- hchars[i], raf.readChar());
- raf.close();
- try {
- raf.writeChars("Already closed.");
- fail("Test 2: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() throws Exception {
- super.setUp();
-
- f = File.createTempFile("raf", "tst");
- if (!f.delete()) {
- fail("Unable to delete test file : " + f);
- }
- fileName = f.getAbsolutePath();
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- * @throws Exception
- */
- protected void tearDown() throws Exception {
- if (f.exists()) {
- f.delete();
- }
- super.tearDown();
- }
-
-} \ No newline at end of file
diff --git a/luni/src/test/java/tests/api/java/io/SequenceInputStreamTest.java b/luni/src/test/java/tests/api/java/io/SequenceInputStreamTest.java
deleted file mode 100644
index f05507e..0000000
--- a/luni/src/test/java/tests/api/java/io/SequenceInputStreamTest.java
+++ /dev/null
@@ -1,357 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.SequenceInputStream;
-import java.util.Enumeration;
-
-import tests.support.Support_ASimpleInputStream;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(SequenceInputStream.class)
-public class SequenceInputStreamTest extends junit.framework.TestCase {
-
- Support_ASimpleInputStream simple1, simple2;
- SequenceInputStream si;
- String s1 = "Hello";
- String s2 = "World";
-
- /**
- * @tests SequenceInputStream#SequenceInputStream(java.io.InputStream,
- * java.io.InputStream)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Checks NullPointerException. A positive test of this " +
- "constructor is implicitely done in setUp(); if it would " +
- "fail, all other tests will also fail.",
- method = "SequenceInputStream",
- args = {java.io.InputStream.class, java.io.InputStream.class}
- )
- public void test_Constructor_LInputStreamLInputStream_Null() {
- try {
- si = new SequenceInputStream(null , null);
- fail("Test 1: NullPointerException expected.");
- } catch (NullPointerException e) {
- // Expected.
- }
-
- //will not throw NullPointerException if the first InputStream is not null
- InputStream is = new ByteArrayInputStream(s1.getBytes());
- si = new SequenceInputStream(is , null);
- }
-
- /**
- * @tests java.io.SequenceInputStream#SequenceInputStream(java.util.Enumeration)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SequenceInputStream",
- args = {java.util.Enumeration.class}
- )
- public void test_ConstructorLjava_util_Enumeration() {
- // Test for method java.io.SequenceInputStream(java.util.Enumeration)
- class StreamEnumerator implements Enumeration<InputStream> {
- InputStream streams[] = new InputStream[2];
-
- int count = 0;
-
- public StreamEnumerator() {
- streams[0] = new ByteArrayInputStream(s1.getBytes());
- streams[1] = new ByteArrayInputStream(s2.getBytes());
- }
-
- public boolean hasMoreElements() {
- return count < streams.length;
- }
-
- public InputStream nextElement() {
- return streams[count++];
- }
- }
-
- try {
- si = new SequenceInputStream(new StreamEnumerator());
- byte buf[] = new byte[s1.length() + s2.length()];
- si.read(buf, 0, s1.length());
- si.read(buf, s1.length(), s2.length());
- assertTrue("Read incorrect bytes: " + new String(buf), new String(
- buf).equals(s1 + s2));
- } catch (IOException e) {
- fail("IOException during read test : " + e.getMessage());
- }
-
- }
-
- /**
- * @throws IOException
- * @tests java.io.SequenceInputStream#available()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "available",
- args = {}
- )
- public void test_available() throws IOException {
- assertEquals("Returned incorrect number of bytes!", s1.length(), si.available());
- simple2.throwExceptionOnNextUse = true;
- assertTrue("IOException on second stream should not affect at this time!",
- si.available() == s1.length());
- simple1.throwExceptionOnNextUse = true;
- try {
- si.available();
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.SequenceInputStream#close()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "close",
- args = {}
- )
- public void test_close() throws IOException {
- assertTrue("Something is available!", si.available() > 0);
- si.close();
- //will not throw IOException to close a stream which is closed already
- si.close();
- assertTrue("Nothing is available, now!", si.available() <= 0);
-// assertEquals("And not on the underlying streams either!", 0, simple1.available());
-// assertTrue("And not on the underlying streams either!", simple1.available() <= 0);
-// assertTrue("And not on the underlying streams either!", simple2.available() <= 0);
- }
-
- /**
- * @tests java.io.SequenceInputStream#close()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "close",
- args = {}
- )
- public void test_close2() throws IOException {
- simple1.throwExceptionOnNextUse = true;
- try {
- si.close();
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.SequenceInputStream#read()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "read",
- args = {}
- )
- public void test_read() throws IOException {
- si.read();
- assertEquals("Test 1: Incorrect char read;",
- s1.charAt(1), (char) si.read());
-
- // We are still reading from the first input stream, should be ok.
- simple2.throwExceptionOnNextUse = true;
- try {
- assertEquals("Test 2: Incorrect char read;",
- s1.charAt(2), (char) si.read());
- } catch (IOException e) {
- fail("Test 3: Unexpected IOException.");
- }
-
- simple1.throwExceptionOnNextUse = true;
- try {
- si.read();
- fail("Test 4: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- simple1.throwExceptionOnNextUse = false;
-
- // Reading bytes 4 and 5 of the first input stream should be ok again.
- si.read();
- si.read();
-
- // Reading the first byte of the second input stream should fail.
- try {
- si.read();
- fail("Test 5: IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
-
- // Reading from the second input stream should be ok now.
- simple2.throwExceptionOnNextUse = false;
- try {
- assertEquals("Test 6: Incorrect char read;",
- s2.charAt(0), (char) si.read());
- } catch (IOException e) {
- fail("Test 7: Unexpected IOException.");
- }
-
- si.close();
- assertTrue("Test 8: -1 expected when reading from a closed " +
- "sequence input stream.", si.read() == -1);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read_exc() throws IOException {
- simple2.throwExceptionOnNextUse = true;
- assertEquals("IOException on second stream should not affect at this time!", 72, si.read());
- simple1.throwExceptionOnNextUse = true;
- try {
- si.read();
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.SequenceInputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII() throws IOException {
- // Test for method int java.io.SequenceInputStream.read(byte [], int,
- // int)
- try {
- byte buf[] = new byte[s1.length() + s2.length()];
- si.read(buf, 0, s1.length());
- si.read(buf, s1.length(), s2.length());
- assertTrue("Read incorrect bytes: " + new String(buf), new String(
- buf).equals(s1 + s2));
- } catch (IOException e) {
- fail("IOException during read test : " + e.getMessage());
- }
-
- ByteArrayInputStream bis1 = new ByteArrayInputStream(
- new byte[] { 1, 2, 3, 4 });
- ByteArrayInputStream bis2 = new ByteArrayInputStream(
- new byte[] { 5, 6, 7, 8 });
- SequenceInputStream sis = new SequenceInputStream(bis1, bis2);
-
- try {
- sis.read(null, 0, 2);
- fail("Expected NullPointerException exception");
- } catch (NullPointerException e) {
- // expected
- }
-
- assertEquals(4, sis.read(new byte[10], 0, 8));
- // The call to read will return after the end of the first substream is
- // reached. So the next call to read will close the first substream
- // because the read call to that substream will return -1, and
- // it will continue reading from the second substream.
- assertEquals(5, sis.read());
-
- //returns -1 if the stream is closed , do not throw IOException
- byte[] array = new byte[] { 1 , 2 , 3 ,4 };
- sis.close();
- int result = sis.read(array , 0 , 5);
- assertEquals(-1 , result);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII_Excpetion() throws IOException {
- byte[] buf = new byte[4];
- si.read(buf, 0, 2);
- si.read(buf, 2, 1);
- simple2.throwExceptionOnNextUse = true;
- si.read(buf, 3, 1);
- assertEquals("Wrong stuff read!", "Hell", new String(buf));
- simple1.throwExceptionOnNextUse = true;
- try {
- si.read(buf, 3, 1);
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
-
- buf = new byte[10];
- simple1 = new Support_ASimpleInputStream(s1);
- simple2 = new Support_ASimpleInputStream(s2);
- si = new SequenceInputStream(simple1, simple2);
- try {
- si.read(buf, -1, 1);
- fail("IndexOutOfBoundsException was not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- si.read(buf, 0, -1);
- fail("IndexOutOfBoundsException was not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- si.read(buf, 1, 10);
- fail("IndexOutOfBoundsException was not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- simple1 = new Support_ASimpleInputStream(s1);
- simple2 = new Support_ASimpleInputStream(s2);
- si = new SequenceInputStream(simple1, simple2);
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/SerializablePermissionTest.java b/luni/src/test/java/tests/api/java/io/SerializablePermissionTest.java
deleted file mode 100644
index 5864b04..0000000
--- a/luni/src/test/java/tests/api/java/io/SerializablePermissionTest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.SerializablePermission;
-
-@TestTargetClass(SerializablePermission.class)
-public class SerializablePermissionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.io.SerializablePermission#SerializablePermission(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SerializablePermission",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.io.SerializablePermission(java.lang.String)
- assertEquals("permission ill-formed",
- "enableSubclassImplementation", new SerializablePermission(
- "enableSubclassImplementation").getName());
- }
-
- /**
- * @tests java.io.SerializablePermission#SerializablePermission(java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SerializablePermission",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_String() {
- // Test for method java.io.SerializablePermission(java.lang.String,
- // java.lang.String)
- assertEquals("permission ill-formed",
- "enableSubclassImplementation", new SerializablePermission(
- "enableSubclassImplementation", "").getName());
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/SerializationStressTest.java b/luni/src/test/java/tests/api/java/io/SerializationStressTest.java
deleted file mode 100644
index 7c4d0b1..0000000
--- a/luni/src/test/java/tests/api/java/io/SerializationStressTest.java
+++ /dev/null
@@ -1,1254 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.DataInputStream;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InvalidObjectException;
-import java.io.NotActiveException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.ObjectStreamClass;
-import java.io.ObjectStreamException;
-import java.io.Serializable;
-import java.io.StreamCorruptedException;
-import java.io.WriteAbortedException;
-import java.security.Permission;
-import java.security.PermissionCollection;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.GregorianCalendar;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.IdentityHashMap;
-import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.PropertyPermission;
-import java.util.Set;
-import java.util.SimpleTimeZone;
-import java.util.SortedMap;
-import java.util.SortedSet;
-import java.util.TimeZone;
-import java.util.TreeMap;
-import java.util.TreeSet;
-import java.util.Vector;
-
-/**
- * Automated Test Suite for class java.io.ObjectOutputStream
- *
- */
-@TestTargetClass(Serializable.class)
-public class SerializationStressTest extends junit.framework.TestCase implements
- Serializable {
-
- // protected static final String MODE_XLOAD = "xload";
-
- // protected static final String MODE_XDUMP = "xdump";
-
- static final String FOO = "foo";
-
- static final String MSG_TEST_FAILED = "Failed to write/read/assertion checking: ";
-
- protected static final boolean DEBUG = false;
-
- protected static boolean xload = false;
-
- protected static boolean xdump = false;
-
- protected static String xFileName = null;
-
- protected transient int dumpCount = 0;
-
- protected transient ObjectInputStream ois;
-
- protected transient ObjectOutputStream oos;
-
- protected transient ByteArrayOutputStream bao;
-
- // -----------------------------------------------------------------------------------
-
- private static class ObjectInputStreamSubclass extends ObjectInputStream {
- private Vector resolvedClasses = new Vector();
-
- public ObjectInputStreamSubclass(InputStream in) throws IOException,
- StreamCorruptedException {
- super(in);
- }
-
- public Class resolveClass(ObjectStreamClass osClass)
- throws IOException, ClassNotFoundException {
- Class result = super.resolveClass(osClass);
- resolvedClasses.addElement(result);
- return result;
- }
-
- public Class[] resolvedClasses() {
- return (Class[]) resolvedClasses.toArray(new Class[resolvedClasses
- .size()]);
- }
- }
-
- static final Map TABLE = new Hashtable();
-
- static final Map MAP = new HashMap();
-
- static final SortedMap TREE = new TreeMap();
-
- static final LinkedHashMap LINKEDMAP = new LinkedHashMap();
-
- static final LinkedHashSet LINKEDSET = new LinkedHashSet();
-
- static final IdentityHashMap IDENTITYMAP = new IdentityHashMap();
-
- static final List ALIST = Arrays.asList(new String[] { "a", "list", "of",
- "strings" });
-
- static final List LIST = new ArrayList(ALIST);
-
- static final Set SET = new HashSet(Arrays.asList(new String[] { "one",
- "two", "three" }));
-
- static final Permission PERM = new PropertyPermission("file.encoding",
- "write");
-
- static final PermissionCollection PERMCOL = PERM.newPermissionCollection();
-
- static final SortedSet SORTSET = new TreeSet(Arrays.asList(new String[] {
- "one", "two", "three" }));
-
- static final java.text.DateFormat DATEFORM = java.text.DateFormat
- .getInstance();
-
- static final java.text.ChoiceFormat CHOICE = new java.text.ChoiceFormat(
- "1#one|2#two|3#three");
-
- static final java.text.NumberFormat NUMBERFORM = java.text.NumberFormat
- .getInstance();
-
- static final java.text.MessageFormat MESSAGE = new java.text.MessageFormat(
- "the time: {0,time} and date {0,date}");
-
- static final LinkedList LINKEDLIST = new LinkedList(Arrays
- .asList(new String[] { "a", "linked", "list", "of", "strings" }));
-
- static final SimpleTimeZone TIME_ZONE = new SimpleTimeZone(3600000,
- "S-TEST");
-
- static final Calendar CALENDAR = new GregorianCalendar(TIME_ZONE);
-
- static Exception INITIALIZE_EXCEPTION = null;
-
- static {
- try {
- TABLE.put("one", "1");
- TABLE.put("two", "2");
- TABLE.put("three", "3");
- MAP.put("one", "1");
- MAP.put("two", "2");
- MAP.put("three", "3");
- LINKEDMAP.put("one", "1");
- LINKEDMAP.put("two", "2");
- LINKEDMAP.put("three", "3");
- IDENTITYMAP.put("one", "1");
- IDENTITYMAP.put("two", "2");
- IDENTITYMAP.put("three", "3");
- LINKEDSET.add("one");
- LINKEDSET.add("two");
- LINKEDSET.add("three");
- TREE.put("one", "1");
- TREE.put("two", "2");
- TREE.put("three", "3");
- PERMCOL.add(PERM);
- // To make sure they all use the same Calendar
- CALENDAR.setTimeZone(new SimpleTimeZone(0, "GMT"));
- CALENDAR.set(1999, Calendar.JUNE, 23, 15, 47, 13);
- CALENDAR.set(Calendar.MILLISECOND, 553);
- DATEFORM.setCalendar(CALENDAR);
- java.text.DateFormatSymbols symbols = new java.text.DateFormatSymbols();
- symbols.setZoneStrings(new String[][] { { "a", "b", "c", "d" },
- { "e", "f", "g", "h" } });
- ((java.text.SimpleDateFormat) DATEFORM).setDateFormatSymbols(symbols);
- DATEFORM.setNumberFormat(new java.text.DecimalFormat("#.#;'-'#.#"));
- DATEFORM.setTimeZone(TimeZone.getTimeZone("EST"));
- ((java.text.DecimalFormat) NUMBERFORM).applyPattern("#.#;'-'#.#");
- MESSAGE.setFormat(0, DATEFORM);
- MESSAGE.setFormat(1, DATEFORM);
- } catch (Exception e) {
- INITIALIZE_EXCEPTION = e;
- }
- }
-
- public SerializationStressTest() {
- }
-
- public SerializationStressTest(String name) {
- super(name);
- }
-
- public String getDumpName() {
- return getName() + dumpCount;
- }
-
- protected void dump(Object o) throws IOException, ClassNotFoundException {
- if (dumpCount > 0)
- setUp();
- // Dump the object
- try {
- oos.writeObject(o);
- } finally {
- oos.close();
- }
- }
-
- protected Object dumpAndReload(Object o) throws IOException,
- ClassNotFoundException {
- dump(o);
- return reload();
- }
-
- protected InputStream loadStream() throws IOException {
- // Choose the load stream
- if (xload || xdump) {
- // Load from pre-existing file
- return new FileInputStream(xFileName + "-" + getDumpName() + ".ser");
- } else {
- // Just load from memory, we dumped to memory
- return new ByteArrayInputStream(bao.toByteArray());
- }
- }
-
- protected Object reload() throws IOException, ClassNotFoundException {
- ois = new ObjectInputStream(loadStream());
- dumpCount++;
- try {
- return ois.readObject();
- } finally {
- ois.close();
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- if (INITIALIZE_EXCEPTION != null) {
- throw new ExceptionInInitializerError(INITIALIZE_EXCEPTION);
- }
- try {
- if (xdump) {
- oos = new ObjectOutputStream(new FileOutputStream(xFileName
- + "-" + getDumpName() + ".ser"));
- } else {
- oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
- }
- } catch (Exception e) {
- fail("Exception thrown during setup : " + e.getMessage());
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- if (oos != null) {
- try {
- oos.close();
- } catch (Exception e) {
- }
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_1_Constructor() {
- // Test for method java.io.ObjectOutputStream(java.io.OutputStream)
-
- try {
- oos.close();
- oos = new ObjectOutputStream(new ByteArrayOutputStream());
- oos.close();
- } catch (Exception e) {
- fail("Failed to create ObjectOutputStream : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_2_close() {
- // Test for method void java.io.ObjectOutputStream.close()
- try {
- oos.close();
- oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
- oos.close();
- oos.writeChar('T');
- oos.writeObject(FOO);
- // Writing to a closed stream does not cause problems. This is
- // the expected behavior
- } catch (IOException e) {
- fail("Operation on closed stream threw IOException : "
- + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_3_defaultWriteObject() {
- // Test for method void java.io.ObjectOutputStream.defaultWriteObject()
-
- try {
- oos.defaultWriteObject();
- } catch (NotActiveException e) {
- // Correct
- return;
- } catch (IOException e) {
- }
- fail(
- "Failed to throw NotActiveException when invoked outside readObject");
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_4_flush() {
- // Test for method void java.io.ObjectOutputStream.flush()
- try {
- oos.close();
- oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
- int size = bao.size();
- oos.writeByte(127);
- assertTrue("Data flushed already", bao.size() == size);
- oos.flush();
- assertTrue("Failed to flush data", bao.size() > size);
- // we don't know how many bytes are actually written for 1 byte,
- // so we test > <before>
- oos.close();
- oos = null;
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_5_reset() {
- // Test for method void java.io.ObjectOutputStream.reset()
- try {
- String o = "HelloWorld";
- oos.writeObject(o);
- oos.writeObject(o);
- oos.reset();
- oos.writeObject(o);
- ois = new ObjectInputStream(loadStream());
- ois.close();
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_6_write() {
- // Test for method void java.io.ObjectOutputStream.write(byte [], int,
- // int)
- try {
- byte[] buf = new byte[255];
- byte[] output = new byte[255];
- for (int i = 0; i < output.length; i++)
- output[i] = (byte) i;
- oos.write(output, 0, output.length);
- oos.close();
- ois = new ObjectInputStream(loadStream());
- ois.readFully(buf);
- ois.close();
- for (int i = 0; i < output.length; i++)
- if (buf[i] != output[i])
- fail("Read incorrect byte: " + i);
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_6a_write() {
- // Test for method void java.io.ObjectOutputStream.write(byte [], int,
- // int)
- try {
- byte[] buf = new byte[256];
- byte[] output = new byte[256];
- for (int i = 0; i < output.length; i++)
- output[i] = (byte) (i & 0xff);
- oos.write(output, 0, output.length);
- oos.close();
- ois = new ObjectInputStream(loadStream());
- ois.readFully(buf);
- ois.close();
- for (int i = 0; i < output.length; i++)
- if (buf[i] != output[i])
- fail("Read incorrect byte: " + i);
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_7_write() {
- // Test for method void java.io.ObjectOutputStream.write(int)
- try {
- byte[] buf = new byte[10];
- oos.write('T');
- oos.close();
- ois = new ObjectInputStream(loadStream());
- assertEquals("Read incorrect byte", 'T', ois.read());
- ois.close();
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_8_write() {
- // Test for method void java.io.ObjectOutputStream.write(byte [])
- try {
- byte[] buf = new byte[10];
- oos.write("HelloWorld".getBytes());
- oos.close();
- ois = new ObjectInputStream(loadStream());
- ois.read(buf, 0, 10);
- ois.close();
- assertEquals("Read incorrect bytes", "HelloWorld", new String(buf, 0, 10)
- );
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_9_writeBoolean() {
- // Test for method void java.io.ObjectOutputStream.writeBoolean(boolean)
- try {
- oos.writeBoolean(true);
- oos.close();
- ois = new ObjectInputStream(loadStream());
- assertTrue("Wrote incorrect byte value", ois.readBoolean());
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_10_writeByte() {
- // Test for method void java.io.ObjectOutputStream.writeByte(int)
- try {
- oos.writeByte(127);
- oos.close();
- ois = new ObjectInputStream(loadStream());
- assertEquals("Wrote incorrect byte value", 127, ois.readByte());
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_11_writeBytes() {
- // Test for method void
- // java.io.ObjectOutputStream.writeBytes(java.lang.String)
- try {
- byte[] buf = new byte[10];
- oos.writeBytes("HelloWorld");
- oos.close();
- ois = new ObjectInputStream(loadStream());
- ois.readFully(buf);
- ois.close();
- assertEquals("Wrote incorrect bytes value", "HelloWorld", new String(buf, 0, 10)
- );
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_12_writeChar() {
- // Test for method void java.io.ObjectOutputStream.writeChar(int)
- try {
- oos.writeChar('T');
- oos.close();
- ois = new ObjectInputStream(loadStream());
- assertEquals("Wrote incorrect char value", 'T', ois.readChar());
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_13_writeChars() {
- // Test for method void
- // java.io.ObjectOutputStream.writeChars(java.lang.String)
- try {
- int avail = 0;
- char[] buf = new char[10];
- oos.writeChars("HelloWorld");
- oos.close();
- ois = new ObjectInputStream(loadStream());
- // Number of prim data bytes in stream / 2 to give char index
- avail = ois.available() / 2;
- for (int i = 0; i < avail; ++i)
- buf[i] = ois.readChar();
- ois.close();
- assertEquals("Wrote incorrect chars", "HelloWorld", new String(buf, 0, 10)
- );
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_14_writeDouble() {
- // Test for method void java.io.ObjectOutputStream.writeDouble(double)
- try {
- oos.writeDouble(Double.MAX_VALUE);
- oos.close();
- ois = new ObjectInputStream(loadStream());
- assertTrue("Wrote incorrect double value",
- ois.readDouble() == Double.MAX_VALUE);
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_15_writeFloat() {
- // Test for method void java.io.ObjectOutputStream.writeFloat(float)
- try {
- oos.writeFloat(Float.MAX_VALUE);
- oos.close();
- ois = new ObjectInputStream(loadStream());
- assertTrue("Wrote incorrect double value",
- ois.readFloat() == Float.MAX_VALUE);
- ois.close();
- ois = null;
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_16_writeInt() {
- // Test for method void java.io.ObjectOutputStream.writeInt(int)
- try {
- oos.writeInt(Integer.MAX_VALUE);
- oos.close();
- ois = new ObjectInputStream(loadStream());
- assertTrue("Wrote incorrect double value",
- ois.readInt() == Integer.MAX_VALUE);
- ois.close();
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_17_writeLong() {
- // Test for method void java.io.ObjectOutputStream.writeLong(long)
- try {
- oos.writeLong(Long.MAX_VALUE);
- oos.close();
- ois = new ObjectInputStream(loadStream());
- assertTrue("Wrote incorrect double value",
- ois.readLong() == Long.MAX_VALUE);
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_19_writeShort() {
- // Test for method void java.io.ObjectOutputStream.writeShort(int)
- try {
- oos.writeShort(127);
- oos.close();
- ois = new ObjectInputStream(loadStream());
- assertEquals("Wrote incorrect short value", 127, ois.readShort());
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_20_writeUTF() {
- // Test for method void
- // java.io.ObjectOutputStream.writeUTF(java.lang.String)
- try {
- oos.writeUTF("HelloWorld");
- oos.close();
- ois = new ObjectInputStream(loadStream());
- assertEquals("Wrote incorrect UTF value",
- "HelloWorld", ois.readUTF());
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_25_available() {
- try {
- oos.writeObject(FOO);
- oos.writeObject(FOO);
- oos.flush();
- int available1 = 0;
- int available2 = 0;
- Object obj1 = null;
- Object obj2 = null;
- ObjectInputStream ois = new ObjectInputStream(loadStream());
- available1 = ois.available();
- obj1 = ois.readObject();
- available2 = ois.available();
- obj2 = ois.readObject();
-
- assertEquals("available returned incorrect value", 0, available1);
- assertEquals("available returned incorrect value", 0, available2);
-
- assertTrue("available caused incorrect reading", FOO.equals(obj1));
- assertTrue("available returned incorrect value", FOO.equals(obj2));
-
- } catch (IOException e) {
- fail("IOException serializing object : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("Unable to read Object type : " + e.toString());
- } catch (Error err) {
- System.out.println("Error " + err);
- throw err;
- }
-
- }
-
- protected void t_MixPrimitivesAndObjects() throws IOException,
- ClassNotFoundException {
- int i = 7;
- String s1 = "string 1";
- String s2 = "string 2";
- byte[] bytes = { 1, 2, 3 };
-
- oos.writeInt(i);
- oos.writeObject(s1);
- oos.writeUTF(s2);
- oos.writeObject(bytes);
- oos.close();
- try {
- ois = new ObjectInputStream(loadStream());
-
- int j = ois.readInt();
- assertTrue("Wrong int :" + j, i == j);
-
- String l1 = (String) ois.readObject();
- assertTrue("Wrong obj String :" + l1, s1.equals(l1));
-
- String l2 = (String) ois.readUTF();
- assertTrue("Wrong UTF String :" + l2, s2.equals(l2));
-
- byte[] bytes2 = (byte[]) ois.readObject();
- assertTrue("Wrong byte[]", Arrays.equals(bytes, bytes2));
-
- } finally {
- ois.close();
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_resolveClass() {
- try {
- oos.writeObject(new Object[] { Integer.class, new Integer(1) });
- oos.close();
-
- ois = new ObjectInputStreamSubclass(loadStream());
- ois.readObject();
- ois.close();
- } catch (IOException e1) {
- fail("IOException : " + e1.getMessage());
- } catch (ClassNotFoundException e2) {
- fail("ClassNotFoundException : " + e2.getMessage());
- }
-
- Class[] resolvedClasses = ((ObjectInputStreamSubclass) ois)
- .resolvedClasses();
- assertEquals("missing resolved", 3, resolvedClasses.length);
- assertTrue("resolved class 1", resolvedClasses[0] == Object[].class);
- assertTrue("resolved class 2", resolvedClasses[1] == Integer.class);
- assertTrue("resolved class 3", resolvedClasses[2] == Number.class);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_reset() {
- try {
- oos.reset();
- oos.writeObject("R");
- oos.reset();
- oos.writeByte(24);
- oos.close();
-
- DataInputStream dis = new DataInputStream(loadStream());
- byte[] input = new byte[dis.available()];
- dis.readFully(input);
- byte[] result = new byte[] { (byte) 0xac, (byte) 0xed, (byte) 0,
- (byte) 5, (byte) 0x79, (byte) 0x74, (byte) 0, (byte) 1,
- (byte) 'R', (byte) 0x79, (byte) 0x77, (byte) 1, (byte) 24 };
- assertTrue("incorrect output", Arrays.equals(input, result));
-
- ois = new ObjectInputStreamSubclass(loadStream());
- assertEquals("Wrong result from readObject()", "R", ois.readObject()
- );
- assertEquals("Wrong result from readByte()", 24, ois.readByte());
- ois.close();
- } catch (IOException e1) {
- fail("IOException : " + e1.getMessage());
- } catch (ClassNotFoundException e2) {
- fail("ClassNotFoundException : " + e2.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_serialVersionUID(Class clazz, long svUID) {
- final String idWrong = "serialVersionUID is wrong for: ";
- long reflectedSvUID = 0L;
- try {
- reflectedSvUID = clazz.getField("serialVersionUID").getLong(null);
- } catch (Exception e) {
- fail("Unable to determine serialVersionUID of " + clazz);
- }
- assertTrue(idWrong + clazz + ": " + reflectedSvUID + " does not equal "
- + svUID, reflectedSvUID == svUID);
- }
-
- private static class ResolveObjectTest implements Serializable {
- Object field1, field2;
- }
-
- private static class ResolveObjectInputStream extends ObjectInputStream {
- ResolveObjectInputStream(InputStream in)
- throws StreamCorruptedException, IOException {
- super(in);
- }
-
- public void enableResolve() {
- enableResolveObject(true);
- }
-
- public Object resolveObject(Object obj) {
- if (obj instanceof Vector) // test_1_resolveObject()
- return new Hashtable();
- else if ("abc".equals(obj)) // test_2_resolveObject()
- return "ABC";
- else if (obj instanceof String) // test_3_resolveObject()
- return String.valueOf(((String) obj).length());
- else if (obj instanceof int[]) // test_4_resolveObject()
- return new Object[1];
- else if (obj instanceof Object[] && ((Object[]) obj).length == 2) // test_5_resolveObject()
- return new char[1];
- return obj;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_1_resolveObject() {
- try {
- ResolveObjectTest obj = new ResolveObjectTest();
- obj.field1 = new Vector();
- obj.field2 = obj.field1;
- oos.writeObject(obj);
- oos.close();
- ois = new ResolveObjectInputStream(loadStream());
- ((ResolveObjectInputStream) ois).enableResolve();
- ResolveObjectTest result = null;
- try {
- result = (ResolveObjectTest) ois.readObject();
- } catch (ClassNotFoundException e) {
- fail(e.toString());
- }
- assertTrue("Object not resolved",
- result.field1 instanceof Hashtable);
- assertTrue("Second reference not resolved",
- result.field1 == result.field2);
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_2_resolveObject() {
- try {
- ResolveObjectTest obj = new ResolveObjectTest();
- obj.field1 = "abc";
- obj.field2 = obj.field1;
- oos.writeObject(obj);
- oos.close();
- ois = new ResolveObjectInputStream(loadStream());
- ((ResolveObjectInputStream) ois).enableResolve();
- ResolveObjectTest result = null;
- try {
- result = (ResolveObjectTest) ois.readObject();
- } catch (ClassNotFoundException e) {
- fail(e.toString());
- }
- assertEquals("String not resolved", "ABC", result.field1);
- assertTrue("Second reference not resolved",
- result.field1 == result.field2);
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_3_resolveObject() {
- try {
- ResolveObjectTest obj = new ResolveObjectTest();
- char[] lchars = new char[70000];
- obj.field1 = new String(lchars);
- obj.field2 = obj.field1;
- oos.writeObject(obj);
- oos.close();
- ois = new ResolveObjectInputStream(loadStream());
- ((ResolveObjectInputStream) ois).enableResolve();
- ResolveObjectTest result = null;
- try {
- result = (ResolveObjectTest) ois.readObject();
- } catch (ClassNotFoundException e) {
- fail(e.toString());
- }
- assertTrue("Long String not resolved", "70000"
- .equals(result.field1));
- assertTrue("Second reference not resolved",
- result.field1 == result.field2);
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_4_resolveObject() {
- try {
- ResolveObjectTest obj = new ResolveObjectTest();
- obj.field1 = new int[5];
- obj.field2 = obj.field1;
- oos.writeObject(obj);
- oos.close();
- ois = new ResolveObjectInputStream(loadStream());
- ((ResolveObjectInputStream) ois).enableResolve();
- ResolveObjectTest result = null;
- try {
- result = (ResolveObjectTest) ois.readObject();
- } catch (ClassNotFoundException e) {
- fail(e.toString());
- }
- Class cl = new Object[0].getClass();
- assertTrue("int[] not resolved", result.field1.getClass() == cl);
- assertTrue("Second reference not resolved",
- result.field1 == result.field2);
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_5_resolveObject() {
- try {
- ResolveObjectTest obj = new ResolveObjectTest();
- obj.field1 = new Object[2];
- obj.field2 = obj.field1;
- oos.writeObject(obj);
- oos.close();
- ois = new ResolveObjectInputStream(loadStream());
- ((ResolveObjectInputStream) ois).enableResolve();
- ResolveObjectTest result = null;
- try {
- result = (ResolveObjectTest) ois.readObject();
- } catch (ClassNotFoundException e) {
- fail(e.toString());
- }
- Class cl = new char[0].getClass();
- assertTrue("int[] not resolved", result.field1.getClass() == cl);
- assertTrue("Second reference not resolved",
- result.field1 == result.field2);
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- }
- }
-
- static class WriteReplaceTestA implements Serializable {
- public Object writeReplace() throws ObjectStreamException {
- return new ReadResolveTestB();
- }
- }
-
- static class WriteReplaceTestB extends WriteReplaceTestA {
- }
-
- static class WriteReplaceTestC extends WriteReplaceTestA {
- public Object writeReplace() throws ObjectStreamException {
- return new ReadResolveTestC();
- }
- }
-
- static class WriteReplaceTestD implements Serializable {
- private Object writeReplace() throws ObjectStreamException {
- return new ReadResolveTestD();
- }
- }
-
- static class WriteReplaceTestE extends WriteReplaceTestD {
- }
-
- static class WriteReplaceTestF implements Serializable {
- int type, readType;
-
- public WriteReplaceTestF(int type, int readType) {
- this.type = type;
- this.readType = readType;
- }
-
- public Object writeReplace() throws ObjectStreamException {
- switch (type) {
- case 0:
- throw new InvalidObjectException("invalid");
- case 1:
- throw new RuntimeException("runtime");
- case 2:
- throw new Error("error");
- default:
- return new ReadResolveTestE(readType);
- }
- }
- }
-
- static class ReadResolveTestA implements Serializable {
- public Object readResolve() throws ObjectStreamException {
- return new ReadResolveTestA();
- }
- }
-
- static class ReadResolveTestB extends ReadResolveTestA {
- }
-
- static class ReadResolveTestC implements Serializable {
- private Object readResolve() throws ObjectStreamException {
- return new ReadResolveTestB();
- }
- }
-
- static class ReadResolveTestD extends ReadResolveTestC {
- }
-
- static class ReadResolveTestE implements Serializable {
- int type;
-
- public ReadResolveTestE(int type) {
- this.type = type;
- }
-
- public Object readResolve() throws ObjectStreamException {
- switch (type) {
- case 0:
- throw new InvalidObjectException("invalid");
- case 1:
- throw new RuntimeException("runtime");
- case 2:
- throw new Error("error");
- case 3:
- return this;
- default:
- return new ReadResolveTestF();
- }
- }
- }
-
- static class ReadResolveTestF implements Serializable {
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_1_writeReplace() {
- try {
- Vector v = new Vector();
- v.addElement(new WriteReplaceTestA());
- v.addElement(new WriteReplaceTestB());
- v.addElement(new WriteReplaceTestB());
- v.addElement(new WriteReplaceTestC());
- v.addElement(new WriteReplaceTestD());
- v.addElement(new WriteReplaceTestE());
- oos.writeObject(v);
- oos.close();
- ois = new ObjectInputStream(loadStream());
- Vector result = (Vector) ois.readObject();
- assertTrue("invalid 0 : " + result.elementAt(0), result
- .elementAt(0).getClass() == ReadResolveTestA.class);
- assertTrue("invalid 1 : " + result.elementAt(1), result
- .elementAt(1).getClass() == ReadResolveTestA.class);
- assertTrue("invalid 2 : " + result.elementAt(2), result
- .elementAt(2).getClass() == ReadResolveTestA.class);
- assertTrue("invalid 3 : " + result.elementAt(3), result
- .elementAt(3).getClass() == ReadResolveTestB.class);
- assertTrue("invalid 4 : " + result.elementAt(4), result
- .elementAt(4).getClass() == ReadResolveTestD.class);
- assertTrue("invalid 5 : " + result.elementAt(5), result
- .elementAt(5).getClass() == WriteReplaceTestE.class);
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException serializing data : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_2_writeReplace() {
- try {
- boolean exception = false;
- try {
- oos.writeObject(new WriteReplaceTestF(0, -1));
- } catch (ObjectStreamException e) {
- exception = true;
- }
- assertTrue("Should throw ObjectStreamException", exception);
- exception = false;
- try {
- oos.writeObject(new WriteReplaceTestF(1, -1));
- } catch (RuntimeException e) {
- exception = true;
- }
- assertTrue("Should throw RuntimeException", exception);
- exception = false;
- try {
- oos.writeObject(new WriteReplaceTestF(2, -1));
- } catch (Error e) {
- exception = true;
- }
- assertTrue("Should throw Error", exception);
-
- oos.writeObject(new WriteReplaceTestF(3, 0));
- oos.writeObject(new WriteReplaceTestF(3, 1));
- oos.writeObject(new WriteReplaceTestF(3, 2));
- WriteReplaceTestF test = new WriteReplaceTestF(3, 3);
- oos.writeObject(test);
- oos.writeObject(test);
- WriteReplaceTestF test2 = new WriteReplaceTestF(3, 4);
- oos.writeObject(test2);
- oos.writeObject(test2);
- oos.close();
- ois = new ObjectInputStream(loadStream());
- try {
- ois.readObject();
- } catch (WriteAbortedException e) {
- }
-
- exception = false;
- try {
- ois.readObject();
- } catch (ObjectStreamException e) {
- exception = true;
- }
- assertTrue("Expected ObjectStreamException", exception);
- exception = false;
- try {
- ois.readObject();
- } catch (RuntimeException e) {
- exception = true;
- }
- assertTrue("Expected RuntimeException", exception);
- exception = false;
- try {
- ois.readObject();
- } catch (Error e) {
- exception = true;
- }
- assertTrue("Expected Error", exception);
-
- Object readE1 = ois.readObject();
- Object readE2 = ois.readObject();
- assertTrue("Replaced objects should be identical", readE1 == readE2);
- Object readF1 = ois.readObject();
- Object readF2 = ois.readObject();
- assertTrue("Replaced resolved objects should be identical: "
- + readF1 + " " + readF2, readF1 == readF2);
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException serializing data : " + e.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/SerializationStressTest1.java b/luni/src/test/java/tests/api/java/io/SerializationStressTest1.java
deleted file mode 100644
index b4d8677..0000000
--- a/luni/src/test/java/tests/api/java/io/SerializationStressTest1.java
+++ /dev/null
@@ -1,1894 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.IOException;
-import java.io.NotSerializableException;
-import java.io.Serializable;
-import java.util.Arrays;
-
-@TestTargetClass(Serializable.class)
-public class SerializationStressTest1 extends SerializationStressTest {
-
- // The purpose of these two classes is to test if serialization, when
- // loading, runs the object's constructor (wrong) or the constructor defined
- // at the topmost Serializable superclass(correct).
- static final int INIT_INT_VALUE = 7;
-
- // HAS to be static class so that our constructor signature will remain
- // untouched (no synthetic param)
- private static class SerializationTest implements java.io.Serializable {
- int anInt = INIT_INT_VALUE;
-
- public SerializationTest() {
- super();
- }
- }
-
- static final String INIT_STR_VALUE = "a string that is blortz";
-
- // HAS to be static class so that our constructor signature will remain
- // untouched (no synthetic param)
- private static class SerializationTestSubclass1 extends SerializationTest {
- String aString = INIT_STR_VALUE;
-
- public SerializationTestSubclass1() {
- super();
- // Just to change default superclass init value
- anInt = INIT_INT_VALUE / 2;
- }
- }
-
- // -----------------------------------------------------------------------------------
-
- private static class SpecTestSuperClass implements Runnable {
- protected java.lang.String instVar;
-
- public void run() {
- }
- }
-
- private static class SpecTest extends SpecTestSuperClass implements
- Cloneable, Serializable {
- public java.lang.String instVar1;
-
- public static java.lang.String staticVar1;
-
- public static java.lang.String staticVar2;
- {
- instVar1 = "NonStaticInitialValue";
- }
- static {
- staticVar1 = "StaticInitialValue";
- staticVar1 = new String(staticVar1);
- }
-
- public Object method(Object objParam, Object objParam2) {
- return new Object();
- }
-
- public boolean method(boolean bParam, Object objParam) {
- return true;
- }
-
- public boolean method(boolean bParam, Object objParam, Object objParam2) {
- return true;
- }
-
- }
-
- private static class SpecTestSubclass extends SpecTest {
- public transient java.lang.String transientInstVar = "transientValue";
- }
-
- // -----------------------------------------------------------------------------------
-
- // This one tests what happens if the read/writeObject methods are defined
- // Serialization should work fine.
- private static class ReadWriteObject implements java.io.Serializable {
- public boolean calledWriteObject = false;
-
- public boolean calledReadObject = false;
-
- public ReadWriteObject() {
- super();
- }
-
- private void readObject(java.io.ObjectInputStream in)
- throws java.io.IOException, ClassNotFoundException {
- calledReadObject = true;
- String s = ((String) in.readObject());
- }
-
- private void writeObject(java.io.ObjectOutputStream out)
- throws java.io.IOException {
- calledWriteObject = true;
- out.writeObject(FOO);
- }
- }
-
- // This one tests what happens if the read/writeObject methods are not
- // private.
- // Serialization should fail.
- private static class PublicReadWriteObject implements java.io.Serializable {
- public boolean calledWriteObject = false;
-
- public boolean calledReadObject = false;
-
- public PublicReadWriteObject() {
- super();
- }
-
- public void readObject(java.io.ObjectInputStream in)
- throws java.io.IOException, ClassNotFoundException {
- calledReadObject = true;
- String s = ((String) in.readObject());
- }
-
- public void writeObject(java.io.ObjectOutputStream out)
- throws java.io.IOException {
- calledWriteObject = true;
- out.writeObject(FOO);
- }
- }
-
- // This one tests if field names are serialized in the same way (sorting)
- // across different VMs
- private static class FieldOrder implements Serializable {
- String aaa1NonPrimitive = "aaa1";
-
- int bbb1PrimitiveInt = 5;
-
- boolean aaa2PrimitiveBoolean = true;
-
- String bbb2NonPrimitive = "bbb2";
- }
-
- // This one tests what happens if you define just readObject, but not
- // writeObject.
- // Does it run or not ?
- private static class JustReadObject implements java.io.Serializable {
- public boolean calledReadObject = false;
-
- public JustReadObject() {
- super();
- }
-
- private void readObject(java.io.ObjectInputStream in)
- throws java.io.IOException, ClassNotFoundException {
- calledReadObject = true;
- in.defaultReadObject();
- }
- }
-
- // This one tests what happens if you define just writeObject, but not
- // readObject.
- // Does it run or not ?
- private static class JustWriteObject implements java.io.Serializable {
- public boolean calledWriteObject = false;
-
- public JustWriteObject() {
- super();
- }
-
- private void writeObject(java.io.ObjectOutputStream out)
- throws java.io.IOException, ClassNotFoundException {
- calledWriteObject = true;
- out.defaultWriteObject();
- }
- }
-
- // This one tests class-based replacement when dumping
- private static class ClassBasedReplacementWhenDumping implements
- java.io.Serializable {
- public boolean calledReplacement = false;
-
- public ClassBasedReplacementWhenDumping() {
- super();
- }
-
- private Object writeReplace() {
- calledReplacement = true;
- return FOO; // Replacement is a String
- }
- }
-
- // This one tests whether class-based replacement supports multiple levels.
- // MultipleClassBasedReplacementWhenDumping -> C1 -> C2 -> C3 -> FOO
- private static class MultipleClassBasedReplacementWhenDumping implements
- java.io.Serializable {
- private static class C1 implements java.io.Serializable {
- private Object writeReplace() {
- return new C2();
- }
- }
-
- private static class C2 implements java.io.Serializable {
- private Object writeReplace() {
- return new C3();
- }
- }
-
- private static class C3 implements java.io.Serializable {
- private Object writeReplace() {
- return FOO;
- }
- }
-
- public MultipleClassBasedReplacementWhenDumping() {
- super();
- }
-
- private Object writeReplace() {
- return new C1();
- }
- }
-
- // This one tests class-based replacement when loading
- private static class ClassBasedReplacementWhenLoading implements
- java.io.Serializable {
- public ClassBasedReplacementWhenLoading() {
- super();
- }
-
- private Object readResolve() {
- return FOO; // Replacement is a String
- }
- }
-
- // This one tests what happens if a loading-replacement is not
- // type-compatible with the original object
- private static class ClassBasedReplacementWhenLoadingViolatesFieldType
- implements java.io.Serializable {
- public ClassBasedReplacementWhenLoading classBasedReplacementWhenLoading = new ClassBasedReplacementWhenLoading();
-
- public ClassBasedReplacementWhenLoadingViolatesFieldType() {
- super();
- }
- }
-
- // What happens if dumping causes an error and you try to reload ?
- // Should the load throw the same exception ?
- private static class MyExceptionWhenDumping1 implements
- java.io.Serializable {
- private static class MyException extends java.io.IOException {
- };
-
- // A primitive instance variable exposes a bug in the serialization
- // spec.
- // Primitive instance variables are written without primitive data tags
- // and so are read without checking for tags. If an exception is
- // written, reading primitive data will just read bytes from the stream
- // which may be tags
- public boolean anInstanceVar = false;
-
- public MyExceptionWhenDumping1() {
- super();
- }
-
- private void readObject(java.io.ObjectInputStream in)
- throws java.io.IOException, ClassNotFoundException {
- in.defaultReadObject();
- }
-
- private void writeObject(java.io.ObjectOutputStream out)
- throws java.io.IOException, ClassNotFoundException {
- throw new MyException();
- }
- }
-
- // What happens if dumping causes an error and you try to reload ?
- // Should the load throw the same exception ?
- private static class MyExceptionWhenDumping2 implements
- java.io.Serializable {
- private static class MyException extends java.io.IOException {
- };
-
- public Integer anInstanceVar = new Integer(0xA1);
-
- public MyExceptionWhenDumping2() {
- super();
- }
-
- private void readObject(java.io.ObjectInputStream in)
- throws java.io.IOException, ClassNotFoundException {
- in.defaultReadObject();
- }
-
- private void writeObject(java.io.ObjectOutputStream out)
- throws java.io.IOException, ClassNotFoundException {
- throw new MyException();
- }
- }
-
- // What happens if dumping causes an error (NonSerializable inst var) and
- // you try to reload ?
- // Should the load throw the same exception ?
- private static class NonSerializableExceptionWhenDumping implements
- java.io.Serializable {
- public Object anInstanceVar = new Object();
-
- public NonSerializableExceptionWhenDumping() {
- super();
- }
- }
-
- // What happens if dumping causes an error (which is not serializable) and
- // you try to reload ?
- // Should the load throw the same exception ?
- private static class MyUnserializableExceptionWhenDumping implements
- java.io.Serializable {
- private static class MyException extends java.io.IOException {
- private Object notSerializable = new Object();
- };
-
- public boolean anInstanceVar = false;
-
- public MyUnserializableExceptionWhenDumping() {
- super();
- }
-
- private void readObject(java.io.ObjectInputStream in)
- throws java.io.IOException, ClassNotFoundException {
- in.defaultReadObject();
- }
-
- private void writeObject(java.io.ObjectOutputStream out)
- throws java.io.IOException, ClassNotFoundException {
- throw new MyException();
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_1_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = "HelloWorld";
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue(MSG_TEST_FAILED + objToSave, (((String) objLoaded)
- .equals((String) objToSave)));
-
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_2_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = null;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue(MSG_TEST_FAILED + objToSave, objLoaded == objToSave);
-
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_3_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- byte[] bytes = { 0, 1, 2, 3 };
- objToSave = bytes;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
- (byte[]) objLoaded, (byte[]) objToSave));
-
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_4_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- int[] ints = { 0, 1, 2, 3 };
- objToSave = ints;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
- (int[]) objLoaded, (int[]) objToSave));
-
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_5_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
-
- short[] shorts = { 0, 1, 2, 3 };
- objToSave = shorts;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
- (short[]) objLoaded, (short[]) objToSave));
-
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_6_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- long[] longs = { 0, 1, 2, 3 };
- objToSave = longs;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
- (long[]) objLoaded, (long[]) objToSave));
-
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_7_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- float[] floats = { 0.0f, 1.1f, 2.2f, 3.3f };
- objToSave = floats;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
- (float[]) objLoaded, (float[]) objToSave));
-
- } catch (IOException e) {
- fail("IOException serializing data: " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_8_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- double[] doubles = { 0.0, 1.1, 2.2, 3.3 };
- objToSave = doubles;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
- (double[]) objLoaded, (double[]) objToSave));
-
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_9_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- boolean[] booleans = { true, false, false, true };
- objToSave = booleans;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
- (boolean[]) objLoaded, (boolean[]) objToSave));
-
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : " + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_10_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
-
- String[] strings = { "foo", "bar", "java" };
- objToSave = strings;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
- (Object[]) objLoaded, (Object[]) objToSave));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("Unable to read Object type: " + e.toString());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_11_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
-
- objToSave = new Object(); // Not serializable
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- boolean passed = false;
- Throwable t = null;
- try {
- objLoaded = dumpAndReload(objToSave);
- } catch (NotSerializableException ns) {
- passed = true;
- t = ns;
- } catch (Exception wrongExc) {
- passed = false;
- t = wrongExc;
- }
- assertTrue(
- "Failed to throw NotSerializableException when serializing "
- + objToSave + " Threw(if non-null) this: " + t,
- passed);
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_12_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- try {
- if (DEBUG)
- System.out.println("Obj = <mixed>");
- t_MixPrimitivesAndObjects();
- } catch (IOException e) {
- fail("IOException serializing data : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when dumping mixed types");
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_13_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- SerializationTestSubclass1 st = new SerializationTestSubclass1();
- // Just change the default ivar values
- st.anInt = Integer.MAX_VALUE;
- st.aString = FOO;
- objToSave = st;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // non-serializable inst var has to be initialized from top
- // constructor
- assertTrue(
- MSG_TEST_FAILED + objToSave,
- ((SerializationTestSubclass1) objLoaded).anInt == Integer.MAX_VALUE);
- // but serialized var has to be restored as it was in the object
- // when dumped
- assertTrue(MSG_TEST_FAILED + objToSave,
- ((SerializationTestSubclass1) objLoaded).aString
- .equals(FOO));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + "\t->"
- + e.toString());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void _test_18_14_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- SpecTest specTest = new SpecTest();
- // Just change the default ivar values
- specTest.instVar = FOO;
- specTest.instVar1 = specTest.instVar;
- objToSave = specTest;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // non-serializable inst var has to be initialized from top
- // constructor
- assertNull(MSG_TEST_FAILED + objToSave,
- ((SpecTest) objLoaded).instVar);
- // instVar from non-serialized class, cant be saved/restored
- // by serialization but serialized ivar has to be restored as it
- // was in the object when dumped
- assertTrue(MSG_TEST_FAILED + objToSave,
- ((SpecTest) objLoaded).instVar1.equals(FOO));
-
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + "\t->"
- + e.toString());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void _test_18_15_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- SpecTestSubclass specTestSubclass = new SpecTestSubclass();
- // Just change the default ivar values
- specTestSubclass.transientInstVar = FOO;
- objToSave = specTestSubclass;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // non-serializable inst var cant be saved, and it is not init'ed
- // from top constructor in this case
- assertNull(MSG_TEST_FAILED + objToSave,
- ((SpecTestSubclass) objLoaded).transientInstVar);
- // transient slot, cant be saved/restored by serialization
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + "\t->"
- + e.toString());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_16_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
-
- String[] strings = new String[2];
- strings[0] = FOO;
- strings[1] = (" " + FOO + " ").trim(); // Safe way to get a copy
- // that is not ==
- objToSave = strings;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- String[] stringsLoaded = (String[]) objLoaded;
- // Serialization has to use identity-based table for assigning IDs
- assertTrue(MSG_TEST_FAILED + objToSave,
- !(stringsLoaded[0] == stringsLoaded[1]));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + "\t->"
- + e.toString());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_17_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
-
- ReadWriteObject readWrite = new ReadWriteObject();
- objToSave = readWrite;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // has to have called the writeObject on the instance to dump
- assertTrue(MSG_TEST_FAILED + objToSave, readWrite.calledWriteObject);
- // has to have called the readObject on the instance loaded
- assertTrue(MSG_TEST_FAILED + objToSave,
- ((ReadWriteObject) objLoaded).calledReadObject);
-
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + "\t->"
- + e.toString());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_18_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- PublicReadWriteObject publicReadWrite = new PublicReadWriteObject();
- objToSave = publicReadWrite;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Can't have called the writeObject on the instance to dump
- assertTrue(MSG_TEST_FAILED + objToSave,
- !publicReadWrite.calledWriteObject);
- // Can't have called the readObject on the instance loaded
- assertTrue(MSG_TEST_FAILED + objToSave,
- !((PublicReadWriteObject) objLoaded).calledReadObject);
-
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + "\t->"
- + e.toString());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_19_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- FieldOrder fieldOrder = new FieldOrder();
- objToSave = fieldOrder;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // This test is only useful for X-loading, so if it managed to
- // dump&load, we passed the test
- assertTrue(MSG_TEST_FAILED + objToSave, true);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_20_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = Class.forName("java.lang.Integer");
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Classes with the same name are unique, so test for ==
- assertTrue(MSG_TEST_FAILED + objToSave, objLoaded == objToSave);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_21_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- // Even though instances of java.lang.Object are not Serializable,
- // instances of java.lang.Class are. So, the object
- // java.lang.Object.class
- // should be serializable
- objToSave = Class.forName("java.lang.Object");
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Classes with the same name are unique, so test for ==
- assertTrue(MSG_TEST_FAILED + objToSave, objLoaded == objToSave);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_22_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- java.net.URL url = new java.net.URL("http://localhost/a.txt");
- objToSave = url;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue("URLs are not the same: " + url + "\t,\t" + objLoaded,
- url.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_23_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
-
- JustReadObject justReadObject = new JustReadObject();
- objToSave = justReadObject;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Only calls readObject on the instance loaded if writeObject was
- // also defined
- assertTrue("Called readObject on an object without a writeObject",
- !((JustReadObject) objLoaded).calledReadObject);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_24_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
-
- JustWriteObject justWriteObject = new JustWriteObject();
- objToSave = justWriteObject;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Call writeObject on the instance even if it does not define
- // readObject
- assertTrue(MSG_TEST_FAILED + objToSave,
- justWriteObject.calledWriteObject);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_25_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- java.util.Vector vector = new java.util.Vector(1);
- vector.add(FOO);
- objToSave = vector;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have the string there
- assertTrue(MSG_TEST_FAILED + objToSave, FOO
- .equals(((java.util.Vector) objLoaded).elementAt(0)));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_26_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- java.util.Hashtable hashTable = new java.util.Hashtable(5);
- hashTable.put(FOO, FOO);
- objToSave = hashTable;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- java.util.Hashtable loadedHashTable = (java.util.Hashtable) objLoaded;
- // Has to have the key/value there (FOO -> FOO)
- assertTrue(MSG_TEST_FAILED + objToSave, FOO.equals(loadedHashTable
- .get(FOO)));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_27_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- ClassBasedReplacementWhenDumping classBasedReplacementWhenDumping = new ClassBasedReplacementWhenDumping();
- objToSave = classBasedReplacementWhenDumping;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have run the replacement method
- assertTrue("Did not run writeReplace",
- classBasedReplacementWhenDumping.calledReplacement);
-
- // Has to have loaded a String (replacement object)
- assertTrue("Did not replace properly", FOO.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_28_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- MultipleClassBasedReplacementWhenDumping multipleClassBasedReplacementWhenDumping = new MultipleClassBasedReplacementWhenDumping();
- objToSave = multipleClassBasedReplacementWhenDumping;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have loaded a String (replacement object)
- assertTrue(
- "Executed multiple levels of replacement (see PR 1F9RNT1), loaded= "
- + objLoaded,
- objLoaded instanceof MultipleClassBasedReplacementWhenDumping.C1);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.toString());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_29_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- ClassBasedReplacementWhenLoading classBasedReplacementWhenLoading = new ClassBasedReplacementWhenLoading();
- objToSave = classBasedReplacementWhenLoading;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have loaded a String (replacement object)
- assertTrue("Did not run readResolve", FOO.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_30_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- ClassBasedReplacementWhenLoadingViolatesFieldType classBasedReplacementWhenLoadingViolatesFieldType = new ClassBasedReplacementWhenLoadingViolatesFieldType();
- objToSave = classBasedReplacementWhenLoadingViolatesFieldType;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // We cannot gere here, the load replacement must have caused a
- // field type violation
- fail(
- "Loading replacements can cause field type violation in this implementation");
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (ClassCastException e) {
- assertTrue(
- "Loading replacements can NOT cause field type violation in this implementation",
- true);
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_31_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- MyExceptionWhenDumping1 exceptionWhenDumping = new MyExceptionWhenDumping1();
- objToSave = exceptionWhenDumping;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- boolean causedException = false;
- try {
- dump(objToSave);
- } catch (MyExceptionWhenDumping1.MyException e) {
- causedException = true;
- }
- ;
- assertTrue("Should have caused an exception when dumping",
- causedException);
- causedException = false;
- try {
- objLoaded = reload();
- // Although the spec says we should get a WriteAbortedException,
- // the serialization format handle an Exception when reading
- // primitive data so we get ClassCastException instead
- } catch (ClassCastException e) {
- causedException = true;
- }
- ;
- assertTrue("Should have caused a ClassCastException when loading",
- causedException);
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_32_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- MyExceptionWhenDumping2 exceptionWhenDumping = new MyExceptionWhenDumping2();
- objToSave = exceptionWhenDumping;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- boolean causedException = false;
- try {
- dump(objToSave);
- } catch (MyExceptionWhenDumping2.MyException e) {
- causedException = true;
- }
- ;
- assertTrue("Should have caused an exception when dumping",
- causedException);
- causedException = false;
- try {
- objLoaded = reload();
- } catch (java.io.WriteAbortedException e) {
- causedException = true;
- }
- ;
- assertTrue(
- "Should have caused a java.io.WriteAbortedException when loading",
- causedException);
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (ClassCastException e) {
- fail("ClassCastException : " + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_NonSerializableExceptionWhenDumping() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- NonSerializableExceptionWhenDumping nonSerializableExceptionWhenDumping = new NonSerializableExceptionWhenDumping();
- objToSave = nonSerializableExceptionWhenDumping;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- boolean causedException = false;
- try {
- dump(objToSave);
- } catch (java.io.NotSerializableException e) {
- causedException = true;
- }
- ;
- assertTrue("Should have caused an exception when dumping",
- causedException);
- causedException = false;
- try {
- objLoaded = reload();
- } catch (java.io.WriteAbortedException e) {
- causedException = true;
- }
- ;
- assertTrue(
- "Should have caused a java.io.WriteAbortedException when loading",
- causedException);
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_33_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- MyUnserializableExceptionWhenDumping exceptionWhenDumping = new MyUnserializableExceptionWhenDumping();
- objToSave = exceptionWhenDumping;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- boolean causedException = false;
- try {
- dump(objToSave);
- } catch (java.io.StreamCorruptedException e) {
- causedException = true;
- }
- ;
- assertTrue("Should have caused an exception when dumping",
- causedException);
- // As the stream is corrupted, reading the stream will have
- // undefined results
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_34_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- java.io.IOException ioe = new java.io.IOException();
- objToSave = ioe;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to be able to save/load an exception
- assertTrue(MSG_TEST_FAILED + objToSave, true);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_35_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = Class.forName("java.util.Hashtable");
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Classes with the same name are unique, so test for ==
- assertTrue(MSG_TEST_FAILED + objToSave, objLoaded == objToSave);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_36_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- java.io.IOException ex = new java.io.InvalidClassException(FOO);
- objToSave = ex;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to be able to save/load an exception
- assertTrue(MSG_TEST_FAILED + objToSave, true);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_37_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- java.io.IOException ex = new java.io.InvalidObjectException(FOO);
- objToSave = ex;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to be able to save/load an exception
- assertTrue(MSG_TEST_FAILED + objToSave, true);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_38_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- java.io.IOException ex = new java.io.NotActiveException(FOO);
- objToSave = ex;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to be able to save/load an exception
- assertTrue(MSG_TEST_FAILED + objToSave, true);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_39_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- java.io.IOException ex = new java.io.NotSerializableException(FOO);
- objToSave = ex;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to be able to save/load an exception
- assertTrue(MSG_TEST_FAILED + objToSave, true);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_40_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- java.io.IOException ex = new java.io.StreamCorruptedException(FOO);
- objToSave = ex;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to be able to save/load an exception
- assertTrue(MSG_TEST_FAILED + objToSave, true);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/SerializationStressTest2.java b/luni/src/test/java/tests/api/java/io/SerializationStressTest2.java
deleted file mode 100644
index 989469c..0000000
--- a/luni/src/test/java/tests/api/java/io/SerializationStressTest2.java
+++ /dev/null
@@ -1,2412 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.io.InvalidClassException;
-import java.io.NotActiveException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.ObjectStreamClass;
-import java.io.ObjectStreamConstants;
-import java.io.ObjectStreamField;
-import java.io.OptionalDataException;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.Locale;
-
-@TestTargetClass(Serializable.class)
-public class SerializationStressTest2 extends SerializationStressTest {
-
- private static class ReadWriteObjectAndPrimitiveData implements
- java.io.Serializable {
- transient long milliseconds;
-
- public boolean calledWriteObject = false;
-
- public boolean calledReadObject = false;
-
- public ReadWriteObjectAndPrimitiveData() {
- super();
- }
-
- private void readObject(java.io.ObjectInputStream in)
- throws java.io.IOException, ClassNotFoundException {
- in.defaultReadObject();
- // This *has* to come after the call to defaultReadObject or the
- // value from the stream will override
- calledReadObject = true;
- milliseconds = in.readLong();
- }
-
- private void writeObject(java.io.ObjectOutputStream out)
- throws java.io.IOException {
- calledWriteObject = true;
- out.defaultWriteObject();
- out.writeLong(milliseconds);
- }
- }
-
- // What happens if a class defines serialPersistentFields that do not match
- // real fields but does not override read/writeObject
- private static class WithUnmatchingSerialPersistentFields implements
- java.io.Serializable {
- private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
- "value", String.class) };
-
- public int anInstanceVar = 5;
-
- public WithUnmatchingSerialPersistentFields() {
- super();
- }
- }
-
- // What happens if a class defines serialPersistentFields which match actual
- // fields
- private static class WithMatchingSerialPersistentFields implements
- java.io.Serializable {
- private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
- "anInstanceVar", String.class) };
-
- public String anInstanceVar = FOO + FOO;
-
- public WithMatchingSerialPersistentFields() {
- super();
- }
- }
-
- // Tests the oficial behavior for serialPersistentFields
- private static class SerialPersistentFields implements java.io.Serializable {
- private static final String SIMULATED_FIELD_NAME = "text";
-
- private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
- SIMULATED_FIELD_NAME, String.class) };
-
- public int anInstanceVar = 5;
-
- public SerialPersistentFields() {
- super();
- }
-
- private void readObject(java.io.ObjectInputStream in)
- throws java.io.IOException, ClassNotFoundException {
- ObjectInputStream.GetField fields = in.readFields();
- anInstanceVar = Integer.parseInt((String) fields.get(
- SIMULATED_FIELD_NAME, "-5"));
- }
-
- private void writeObject(java.io.ObjectOutputStream out)
- throws java.io.IOException, ClassNotFoundException {
- ObjectOutputStream.PutField fields = out.putFields();
- fields.put(SIMULATED_FIELD_NAME, Integer.toString(anInstanceVar));
- out.writeFields();
- }
- }
-
- // Tests the behavior for serialPersistentFields when no fields are actually
- // set
- private static class WriteFieldsWithoutFetchingPutFields implements
- java.io.Serializable {
- private static final String SIMULATED_FIELD_NAME = "text";
-
- private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
- SIMULATED_FIELD_NAME, String.class) };
-
- public int anInstanceVar = 5;
-
- public WriteFieldsWithoutFetchingPutFields() {
- super();
- }
-
- private void readObject(java.io.ObjectInputStream in)
- throws java.io.IOException, ClassNotFoundException {
- ObjectInputStream.GetField fields = in.readFields();
- }
-
- private void writeObject(java.io.ObjectOutputStream out)
- throws java.io.IOException, ClassNotFoundException {
- out.writeFields();
- }
- }
-
- // Tests what happens if one asks for PutField/getField when the class does
- // not declare one
- private static class SerialPersistentFieldsWithoutField implements
- java.io.Serializable {
- public int anInstanceVar = 5;
-
- public SerialPersistentFieldsWithoutField() {
- super();
- }
-
- private void readObject(java.io.ObjectInputStream in)
- throws java.io.IOException, ClassNotFoundException {
- ObjectInputStream.GetField fields = in.readFields();
- }
-
- private void writeObject(java.io.ObjectOutputStream out)
- throws java.io.IOException, ClassNotFoundException {
- ObjectOutputStream.PutField fields = out.putFields();
- out.writeFields();
- }
- }
-
- // -----------------------------------------------------------------------------------
-
- // writeObject writes extra primitive types and objects which readObject
- // does not consume. Have to make sure we can load object properly AND
- // object after it (to show the extra byte[] is consumed)
- private static class OptionalDataNotRead implements java.io.Serializable {
- private int field1, field2;
-
- public OptionalDataNotRead() {
- }
-
- private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("field1", Integer.TYPE),
- new ObjectStreamField("field2", Integer.TYPE),
- new ObjectStreamField("monthLength", byte[].class), };
-
- private void writeObject(ObjectOutputStream stream) throws IOException {
- ObjectOutputStream.PutField fields = stream.putFields();
- fields.put("field1", 1);
- fields.put("field2", 2);
- fields.put("monthLength", new byte[] { 7, 8, 9 });
- stream.writeFields();
- stream.writeInt(4);
- byte[] values = new byte[4];
- values[0] = (byte) 16;
- values[1] = (byte) 17;
- values[2] = (byte) 18;
- values[3] = (byte) 19;
- stream.writeObject(values);
- }
-
- private void readObject(ObjectInputStream stream) throws IOException,
- ClassNotFoundException {
- ObjectInputStream.GetField fields = stream.readFields();
- field1 = fields.get("field1", 0);
- field2 = fields.get("field1", 0);
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class NestedPutField implements java.io.Serializable {
- public OptionalDataNotRead field1;
-
- public NestedPutField() {
- }
-
- private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
- "field1", OptionalDataNotRead.class), };
-
- private void writeObject(ObjectOutputStream stream) throws IOException {
- ObjectOutputStream.PutField fields = stream.putFields();
- fields.put("field1", new OptionalDataNotRead());
- stream.writeFields();
- }
-
- private void readObject(ObjectInputStream stream) throws IOException,
- ClassNotFoundException {
- ObjectInputStream.GetField fields = stream.readFields();
- field1 = (OptionalDataNotRead) fields.get("field1", null);
- }
- }
-
- // -----------------------------------------------------------------------------------
-
- // This one tests stream-based replacement when dumping
- private static class StreamBasedReplacementWhenDumping extends
- java.io.ObjectOutputStream {
- public boolean calledArrayReplacement = false;
-
- public boolean calledStringReplacement = false;
-
- public boolean calledClassReplacement = false;
-
- public boolean calledObjectStreamClassReplacement = false;
-
- public StreamBasedReplacementWhenDumping(java.io.OutputStream output)
- throws java.io.IOException {
- super(output);
- enableReplaceObject(true);
- }
-
- protected Object replaceObject(Object obj) throws IOException {
- Class objClass = obj.getClass();
- if (objClass == String.class)
- calledStringReplacement = true;
-
- if (objClass == Class.class)
- calledClassReplacement = true;
-
- if (objClass == ObjectStreamClass.class)
- calledObjectStreamClassReplacement = true;
-
- if (objClass.isArray())
- calledArrayReplacement = true;
-
- return obj;
- }
- }
-
- // -----------------------------------------------------------------------------------
-
- private static class ArrayOfSerializable implements Serializable {
- private Serializable[] testField = null;
-
- public ArrayOfSerializable() {
- testField = new Serializable[2];
- testField[0] = "Hi";
- testField[1] = "there!";
- }
- }
-
- // -----------------------------------------------------------------------------------
-
- private static class ClassSubClassTest0 extends java.lang.Object implements
- java.io.Serializable {
- String stringVar;
-
- public ClassSubClassTest0(String init) {
- stringVar = init;
- }
- }
-
- private static class ClassSubClassTest1 extends ClassSubClassTest0 {
- String subStringVar;
-
- public ClassSubClassTest1(String superString, String subString) {
- super(superString);
- subStringVar = subString;
- }
-
- public boolean equals(Object obj) {
- if (obj == null)
- return false;
- if (!(obj instanceof ClassSubClassTest1))
- return false;
-
- ClassSubClassTest1 inst = (ClassSubClassTest1) obj;
- return inst.subStringVar.equals(this.subStringVar)
- && inst.stringVar.equals(this.stringVar);
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class ConstructorTestA {
- public String instVar_classA;
-
- public final static String ConstrA = "Init in Constructor Class A";
-
- public final static String ConstrB = "Init in Constructor Class B";
-
- public final static String ConstrC = "Init in Constructor Class C";
-
- public final static String ChangedC = "Changed before Serialize - Class C";
-
- public ConstructorTestA() {
- instVar_classA = ConstrA;
- }
- }
-
- private static class ConstructorTestB extends ConstructorTestA implements
- java.io.Serializable {
- public String instVar_classB;
-
- public ConstructorTestB() {
- instVar_classA = ConstrB;
- instVar_classB = ConstrB;
- }
- }
-
- private static class ConstructorTestC extends ConstructorTestB {
- public String instVar_classC;
-
- public ConstructorTestC() {
- instVar_classA = ConstrC;
- instVar_classB = ConstrC;
- instVar_classC = ConstrC;
- }
-
- public boolean verify(Object obj) {
- if (obj == null)
- return false;
- if (!(obj instanceof ConstructorTestC))
- return false;
-
- ConstructorTestC inst = (ConstructorTestC) obj;
- return inst.instVar_classC.equals(this.instVar_classC)
- && inst.instVar_classB.equals(this.instVar_classB)
- && inst.instVar_classA.equals(ConstrA);
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class HashCodeTest implements java.io.Serializable {
- private boolean serializationUsesHashCode = false;
-
- public int hashCode() {
- serializationUsesHashCode = true;
- return super.hashCode();
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class InitializerFieldsTest implements java.io.Serializable {
- public java.lang.String toBeSerialized;
-
- public static java.lang.String toBeNotSerialized;
-
- public static java.lang.String toBeNotSerialized2;
-
- {
- toBeSerialized = "NonStaticInitialValue";
- }
-
- static {
- toBeNotSerialized = "StaticInitialValue";
- toBeNotSerialized2 = new String(toBeNotSerialized);
- }
-
- public boolean equals(Object obj) {
- /*
- * This method is not answering it the objs is equal. It is
- * answering if the vars have the value that it have to have after
- * dumping and loading
- */
-
- if (obj == null)
- return false;
- if (!(obj instanceof InitializerFieldsTest))
- return false;
-
- InitializerFieldsTest inst = (InitializerFieldsTest) obj;
- return inst.toBeSerialized.equals(this.toBeSerialized)
- && inst.toBeNotSerialized.equals(this.toBeNotSerialized2);
- }
- }
-
- private static class InitializerFieldsTest2 implements java.io.Serializable {
- public java.lang.String toBeSerialized;
-
- public static java.lang.String toBeNotSerialized;
-
- public static java.lang.String toBeNotSerialized2;
-
- {
- toBeSerialized = "NonStaticInitialValue";
- }
-
- public java.lang.String toBeSerialized3;
-
- public java.lang.String toBeSerialized4;
- static {
- toBeNotSerialized = "StaticInitialValue";
- toBeNotSerialized2 = new String(toBeNotSerialized);
- }
-
- public java.lang.String toBeSerialized5;
-
- public boolean equals(Object obj) {
- /*
- * This method is not answering it the objs is equal. It is
- * answering if the vars have the value that it have to have after
- * dumping and loading
- */
-
- if (obj == null)
- return false;
- if (!(obj instanceof InitializerFieldsTest2))
- return false;
-
- InitializerFieldsTest2 inst = (InitializerFieldsTest2) obj;
- return inst.toBeSerialized.equals(this.toBeSerialized)
- && inst.toBeSerialized3.equals(this.toBeSerialized3)
- && inst.toBeSerialized4.equals(this.toBeSerialized4)
- && inst.toBeSerialized5.equals(this.toBeSerialized5)
- && inst.toBeNotSerialized.equals(this.toBeNotSerialized2);
- }
- }
-
- private static class InitializerFieldsTest3 extends InitializerFieldsTest2
- implements java.io.Serializable {
- public java.lang.String sub_toBeSerialized;
-
- public static java.lang.String sub_toBeNotSerialized;
-
- public static java.lang.String sub_toBeNotSerialized2;
-
- {
- sub_toBeSerialized = "NonStaticInitialValue";
- }
-
- public java.lang.String sub_toBeSerialized3;
-
- public java.lang.String sub_toBeSerialized4;
- static {
- sub_toBeNotSerialized = "StaticInitialValue";
- sub_toBeNotSerialized2 = new String(sub_toBeNotSerialized);
- }
-
- public java.lang.String sub_toBeSerialized5;
-
- public boolean equals(Object obj) {
- /*
- * This method is not answering it the objs is equal. It is
- * answering if the vars have the value that it have to have after
- * dumping and loading
- */
-
- if (!super.equals(obj))
- return false;
- if (!(obj instanceof InitializerFieldsTest3))
- return false;
-
- InitializerFieldsTest3 inst = (InitializerFieldsTest3) obj;
- return inst.sub_toBeSerialized.equals(this.sub_toBeSerialized)
- && inst.sub_toBeSerialized3
- .equals(this.sub_toBeSerialized3)
- && inst.sub_toBeSerialized4
- .equals(this.sub_toBeSerialized4)
- && inst.sub_toBeSerialized5
- .equals(this.sub_toBeSerialized5)
- && inst.sub_toBeNotSerialized
- .equals(this.sub_toBeNotSerialized2);
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class DeepNesting implements java.io.Serializable {
- public float id;
-
- public DeepNesting next;
-
- public boolean dump;
-
- public boolean load;
-
- public DeepNesting(float id) {
- this.id = id;
- next = null;
- dump = false;
- load = false;
- }
-
- public DeepNesting(int howMany) {
- DeepNesting prev = new DeepNesting(0.0F);
- next(prev);
- for (int i = 1; i < howMany; i++) {
- prev = prev.next(new DeepNesting(i * 1.0F));
- }
- }
-
- public boolean equals(Object obj) {
- if (obj == null)
- return false;
- if (!(obj instanceof DeepNesting))
- return false;
-
- DeepNesting inst = (DeepNesting) obj;
- if (inst.dump != this.dump || inst.load != this.load)
- return false;
-
- if (inst.next == null || this.next == null)
- return inst.next == this.next; // both null
- return this.next.equals(inst.next);
- }
-
- public DeepNesting next(DeepNesting ivt) {
- next = ivt;
- return ivt;
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class DeepNestingWithWriteObject implements
- java.io.Serializable {
- public float id;
-
- public DeepNestingWithWriteObject next;
-
- public boolean dump;
-
- public boolean load;
-
- public DeepNestingWithWriteObject(float id) {
- this.id = id;
- next = null;
- dump = false;
- load = false;
- }
-
- public DeepNestingWithWriteObject(int howMany) {
- DeepNestingWithWriteObject prev = new DeepNestingWithWriteObject(
- 0.0F);
- next(prev);
- for (int i = 1; i < howMany; i++) {
- prev = prev.next(new DeepNestingWithWriteObject(i * 1.0F));
- }
- }
-
- public boolean equals(Object obj) {
- if (obj == null)
- return false;
- if (!(obj instanceof DeepNestingWithWriteObject))
- return false;
-
- DeepNestingWithWriteObject inst = (DeepNestingWithWriteObject) obj;
- if (inst.dump != this.dump || inst.load != this.load)
- return false;
-
- if (inst.next == null || this.next == null)
- return inst.next == this.next; // both null;
- return this.next.equals(inst.next);
- }
-
- public DeepNestingWithWriteObject next(DeepNestingWithWriteObject ivt) {
- next = ivt;
- return ivt;
- }
-
- private void writeObject(java.io.ObjectOutputStream s)
- throws IOException {
- s.defaultWriteObject();
- }
-
- private void readObject(java.io.ObjectInputStream s)
- throws IOException, ClassNotFoundException {
- s.defaultReadObject();
- }
- }
-
- // -----------------------------------------------------------------------------------
- static class NonPublicClassTest extends java.lang.Object implements
- java.io.Serializable {
- int field = 1;
-
- public NonPublicClassTest() {
- field = 10;
- }
-
- public boolean equals(Object o) {
- if (o instanceof NonPublicClassTest)
- return field == ((NonPublicClassTest) o).field;
- return false;
- }
-
- public void x10() {
- field *= 10;
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class SameInstVarNameSuperClass {
- private int foo;
-
- public SameInstVarNameSuperClass() {
- super();
- }
-
- public SameInstVarNameSuperClass(int fooValue) {
- foo = fooValue;
- }
-
- public String toString() {
- return "foo = " + foo;
- }
- }
-
- private static class SameInstVarNameSubClass extends
- SameInstVarNameSuperClass implements java.io.Serializable {
- protected int foo;
-
- public SameInstVarNameSubClass() {
- super();
- }
-
- public SameInstVarNameSubClass(int fooValue) {
- super(-fooValue);
- foo = fooValue;
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class SInterfaceTest implements java.io.Serializable {
- public static int staticVar = 5;
-
- public transient int[] transVar = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
-
- public int instanceVar = 7;
-
- public boolean equals(Object obj) {
- if (obj == null)
- return false;
- if (!(obj instanceof SInterfaceTest))
- return false;
-
- SInterfaceTest inst = (SInterfaceTest) obj;
- if (this.instanceVar != inst.instanceVar)
- return false;
- if (inst.transVar == null || this.transVar == null)
- return inst.transVar == this.transVar; // both null
- for (int i = 0; i < transVar.length; i++)
- if (inst.transVar[i] != this.transVar[i])
- return false;
- return true;
- }
-
- private void readObject(java.io.ObjectInputStream s)
- throws IOException, ClassNotFoundException {
- Object arr;
- s.defaultReadObject();
- arr = s.readObject();
- transVar = (int[]) arr;
- }
-
- private void writeObject(java.io.ObjectOutputStream s)
- throws IOException {
- s.defaultWriteObject();
- s.writeObject(transVar);
- }
-
- public void x10() {
- for (int i = 0; i < transVar.length; i++)
- transVar[i] = transVar[i] * 10;
- instanceVar = instanceVar * 10;
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class SInterfaceTest2 extends SInterfaceTest {
- private void readObject(java.io.ObjectInputStream s)
- throws IOException, ClassNotFoundException {
- Object arr;
- instanceVar = s.readInt();
- arr = s.readObject();
- transVar = (int[]) arr;
- }
-
- private void writeObject(java.io.ObjectOutputStream s)
- throws IOException {
- s.writeInt(instanceVar);
- s.writeObject(transVar);
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class SuperclassTest extends java.lang.Object implements
- java.io.Serializable {
- int superfield = 1;
-
- public SuperclassTest() {
- superfield = 10;
- }
-
- public boolean equals(Object o) {
- if (o.getClass() == this.getClass())
- return superfield == ((SuperclassTest) o).superfield;
- return false;
- }
-
- private void readObject(java.io.ObjectInputStream s)
- throws IOException, ClassNotFoundException {
- superfield = s.readInt();
- }
-
- private void writeObject(java.io.ObjectOutputStream s)
- throws IOException {
- s.writeInt(superfield);
- }
-
- public void x10() {
- superfield *= 10;
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class SuperclassTest2 extends SuperclassTest {
- int subfield = 5;
-
- public SuperclassTest2() {
- subfield = 50;
- }
-
- public boolean equals(Object o) {
- if (o instanceof SuperclassTest2)
- if (subfield == ((SuperclassTest2) o).subfield)
- return super.equals(o);
- return false;
- }
-
- private void readObject(java.io.ObjectInputStream s)
- throws IOException, ClassNotFoundException {
- subfield = s.readInt();
- }
-
- private void writeObject(java.io.ObjectOutputStream s)
- throws IOException {
- s.writeInt(subfield);
- }
-
- public void x10() {
- subfield *= 10;
- super.x10();
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class SyntheticFieldTest implements java.io.Serializable {
- public boolean equals(Object obj) {
- /*
- * This method is not answering it the objs is equal. It is
- * answering if the vars have the value that it have to have after
- * dumping and loading
- */
- if (obj == null)
- return false;
- return obj instanceof SyntheticFieldTest;
- }
-
- public int hashCode() {
- // Insert code to generate a hash code for the receiver here.
- // This implementation forwards the message to super. You may
- // replace or supplement this.
- // NOTE: if two objects are equal (equals Object) returns true) they
- // must have the same hash code
- Class[] c = { String.class }; // *** synthetic field
- return super.hashCode();
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_41_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- java.io.IOException ex = new java.io.WriteAbortedException(FOO,
- null);
- objToSave = ex;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to be able to save/load an exception
- assertTrue(MSG_TEST_FAILED + objToSave, true);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_42_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- WithUnmatchingSerialPersistentFields spf = new WithUnmatchingSerialPersistentFields();
- objToSave = spf;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- boolean causedException = false;
- try {
- objLoaded = dumpAndReload(objToSave);
- } catch (InvalidClassException ce) {
- causedException = true;
- }
- assertTrue("serialPersistentFields do not match real fields",
- causedException);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_43_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- WithMatchingSerialPersistentFields spf = new WithMatchingSerialPersistentFields();
- spf.anInstanceVar = FOO;
- objToSave = spf;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue(
- "serialPersistentFields do not work properly in this implementation",
- FOO
- .equals(((WithMatchingSerialPersistentFields) objLoaded).anInstanceVar));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_44_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- SerialPersistentFields spf = new SerialPersistentFields();
- final int CONST = -500;
- spf.anInstanceVar = CONST;
- objToSave = spf;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue(
- "serialPersistentFields do not work properly in this implementation",
- ((SerialPersistentFields) objLoaded).anInstanceVar == CONST);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_45_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- WriteFieldsWithoutFetchingPutFields spf = new WriteFieldsWithoutFetchingPutFields();
- objToSave = spf;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- boolean causedException = false;
- try {
- objLoaded = dumpAndReload(objToSave);
- } catch (NotActiveException ce) {
- causedException = true;
- }
- assertTrue("WriteFieldsWithoutFetchingPutFields", causedException);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_46_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = SerialPersistentFields.class; // Test for 1FA7TA6
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to be able to save/load an exception
- assertTrue(MSG_TEST_FAILED + objToSave, true);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_47_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = ObjectStreamClass.lookup(SerialPersistentFields.class); // Test
- // for
- // 1FA7TA6
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to be able to save/load an exception
- assertTrue(MSG_TEST_FAILED + objToSave, true);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_48_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- SerialPersistentFieldsWithoutField spf = new SerialPersistentFieldsWithoutField();
- final int CONST = -500;
- spf.anInstanceVar = CONST;
- objToSave = spf;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue(
- "serialPersistentFields do not work properly in this implementation",
- ((SerialPersistentFieldsWithoutField) objLoaded).anInstanceVar != CONST);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_49_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- java.net.SocketPermission p = new java.net.SocketPermission(
- "www.yahoo.com", "connect");
- objToSave = p;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue("SocketPermissions are not the same: " + p + "\t,\t"
- + objLoaded, p.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_50_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- java.net.SocketPermission p = new java.net.SocketPermission(
- "www.yahoo.com", "ReSoLVe, ConNecT");
- objToSave = p;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue("SocketPermissions are not the same: " + p + "\t,\t"
- + objLoaded, p.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_51_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
-
- ReadWriteObjectAndPrimitiveData readWrite = new ReadWriteObjectAndPrimitiveData();
- objToSave = readWrite;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // has to have called the writeObject on the instance to dump
- assertTrue(MSG_TEST_FAILED + objToSave, readWrite.calledWriteObject);
- // has to have called the readObject on the instance loaded
- assertTrue(
- MSG_TEST_FAILED + objToSave,
- ((ReadWriteObjectAndPrimitiveData) objLoaded).calledReadObject);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_52_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
-
- ArrayList list = new ArrayList(Arrays.asList(new String[] { "a",
- "list", "of", "strings" }));
- objToSave = list;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, true);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_53_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
-
- objToSave = Locale.CHINESE;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, true);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_OptionalDataNotRead() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- OptionalDataNotRead test = new OptionalDataNotRead();
- // Have to save an object after the one above, and when we read it,
- // it cannot be a byte[]
- Date now = new Date();
- Object[] twoObjects = new Object[2];
- twoObjects[0] = test;
- twoObjects[1] = now;
- objToSave = twoObjects;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- Object[] twoLoadedObjects = (Object[]) objLoaded;
- assertTrue(MSG_TEST_FAILED + objToSave, twoLoadedObjects[0]
- .getClass() == OptionalDataNotRead.class);
- assertTrue(MSG_TEST_FAILED + objToSave, twoLoadedObjects[1]
- .getClass() == Date.class);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_55_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- Object[] threeObjects = new Object[3];
- threeObjects[0] = new Integer(2);
- threeObjects[1] = Date.class;
- threeObjects[2] = threeObjects[0]; // has to be the same
- objToSave = threeObjects;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- Object[] threeLoadedObjects = (Object[]) objLoaded;
- assertTrue(MSG_TEST_FAILED + objToSave, threeLoadedObjects[0]
- .getClass() == Integer.class);
- assertTrue(MSG_TEST_FAILED + objToSave,
- threeLoadedObjects[1] == Date.class);
- assertTrue(MSG_TEST_FAILED + objToSave,
- threeLoadedObjects[0] == threeLoadedObjects[2]);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_56_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- // Test for 1FD24BY
- NestedPutField test = new NestedPutField();
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertNotNull(MSG_TEST_FAILED + objToSave,
- ((NestedPutField) objLoaded).field1);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void _test_18_57_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- ByteArrayOutputStream out;
- StreamBasedReplacementWhenDumping streamBasedReplacementWhenDumping;
-
- out = new ByteArrayOutputStream();
- streamBasedReplacementWhenDumping = new StreamBasedReplacementWhenDumping(
- out);
- ;
- objToSave = FOO.getClass();
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- streamBasedReplacementWhenDumping.writeObject(objToSave);
- // Has to have run the replacement method
- assertTrue("Executed replacement when it should not: " + objToSave,
- !streamBasedReplacementWhenDumping.calledClassReplacement);
-
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + "\t->"
- + e.toString());
- } catch (Error err) {
- System.out.println("Error " + err + " when obj = " + objToSave);
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void _test_18_58_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- ByteArrayOutputStream out;
- StreamBasedReplacementWhenDumping streamBasedReplacementWhenDumping;
-
- out = new ByteArrayOutputStream();
- streamBasedReplacementWhenDumping = new StreamBasedReplacementWhenDumping(
- out);
- ;
- objToSave = ObjectStreamClass.lookup(FOO.getClass());
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- streamBasedReplacementWhenDumping.writeObject(objToSave);
- // Has to have run the replacement method
- assertTrue(
- "Executed replacement when it should not: " + objToSave,
- !streamBasedReplacementWhenDumping.calledObjectStreamClassReplacement);
-
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + "\t->"
- + e.toString());
- } catch (Error err) {
- System.out.println("Error " + err + " when obj = " + objToSave);
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_59_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- ByteArrayOutputStream out;
- StreamBasedReplacementWhenDumping streamBasedReplacementWhenDumping;
-
- out = new ByteArrayOutputStream();
- streamBasedReplacementWhenDumping = new StreamBasedReplacementWhenDumping(
- out);
- ;
- objToSave = new int[3];
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- streamBasedReplacementWhenDumping.writeObject(objToSave);
- // Has to have run the replacement method
- assertTrue("DId not execute replacement when it should: "
- + objToSave,
- streamBasedReplacementWhenDumping.calledArrayReplacement);
-
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + "\t->"
- + e.toString());
- } catch (Error err) {
- System.out.println("Error " + err + " when obj = " + objToSave);
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_60_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- ByteArrayOutputStream out;
- StreamBasedReplacementWhenDumping streamBasedReplacementWhenDumping;
-
- out = new ByteArrayOutputStream();
- streamBasedReplacementWhenDumping = new StreamBasedReplacementWhenDumping(
- out);
- ;
- objToSave = FOO;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- streamBasedReplacementWhenDumping.writeObject(objToSave);
- // Has to have run the replacement method
- assertTrue("Did not execute replacement when it should: "
- + objToSave,
- streamBasedReplacementWhenDumping.calledStringReplacement);
-
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + "\t->"
- + e.toString());
- } catch (Error err) {
- System.out.println("Error " + err + " when obj = " + objToSave);
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_61_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- ArrayOfSerializable test = new ArrayOfSerializable();
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, true);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_62_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- ClassSubClassTest1 test = new ClassSubClassTest1(
- "SuperInitialString", "SubInitialString");
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_63_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- ConstructorTestC test = new ConstructorTestC();
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, test.verify(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_64_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- HashCodeTest test = new HashCodeTest();
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave,
- !((HashCodeTest) objLoaded).serializationUsesHashCode);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_65_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- InitializerFieldsTest test = new InitializerFieldsTest();
- test.toBeSerialized = "serializing";
- InitializerFieldsTest.toBeNotSerialized = "It should not have this value after loaded from a File";
- InitializerFieldsTest.toBeNotSerialized2 = "Good-This is the rigth value.";
-
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- dump(objToSave);
- InitializerFieldsTest.toBeNotSerialized = new String(
- InitializerFieldsTest.toBeNotSerialized2);
- objLoaded = reload();
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, (test.equals(objLoaded)));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_66_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- InitializerFieldsTest2 test = new InitializerFieldsTest2();
- test.toBeSerialized = "serializing";
- test.toBeSerialized3 = "serializing3";
- test.toBeSerialized4 = "serializing4";
- test.toBeSerialized5 = "serializing5";
- InitializerFieldsTest2.toBeNotSerialized = "It should not have this value after loaded from a File";
- InitializerFieldsTest2.toBeNotSerialized2 = "Good-This is the rigth value.";
-
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- dump(objToSave);
- InitializerFieldsTest2.toBeNotSerialized = new String(
- InitializerFieldsTest2.toBeNotSerialized2);
- objLoaded = reload();
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, (test.equals(objLoaded)));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_67_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- InitializerFieldsTest3 test = new InitializerFieldsTest3();
- test.toBeSerialized = "serializing";
- test.toBeSerialized3 = "serializing3";
- test.toBeSerialized4 = "serializing4";
- test.toBeSerialized5 = "serializing5";
- InitializerFieldsTest2.toBeNotSerialized = "It should not have this value after loaded from a File";
- InitializerFieldsTest2.toBeNotSerialized2 = "Good-This is the rigth value.";
- test.sub_toBeSerialized = "serializingSub";
- test.sub_toBeSerialized3 = "serializing3sub";
- test.sub_toBeSerialized4 = "serializing4sub";
- test.sub_toBeSerialized5 = "serializing5sub";
- InitializerFieldsTest3.sub_toBeNotSerialized = "(Subclass) It should not have this value after loaded from a File";
- InitializerFieldsTest3.sub_toBeNotSerialized2 = "(Subclass) Good-This is the rigth value.";
- // Before dumping the two static vars are differents.
- // After dumping the value of toBeNotSerialized2 is put in
- // toBeNotSerialized
- // After loading it must be the same.
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- dump(objToSave);
- InitializerFieldsTest2.toBeNotSerialized = new String(
- InitializerFieldsTest2.toBeNotSerialized2);
- InitializerFieldsTest3.sub_toBeNotSerialized = new String(
- InitializerFieldsTest3.sub_toBeNotSerialized2);
- objLoaded = reload();
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, (test.equals(objLoaded)));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_DeepNesting() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- DeepNesting test = new DeepNesting(11);
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, (test.equals(objLoaded)));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- // err.printStackTrace();
- System.out.println("Error " + err + " when obj = " + objToSave);
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void _test_DeepNestingWithWriteObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- DeepNestingWithWriteObject test = new DeepNestingWithWriteObject(50);
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, (test.equals(objLoaded)));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- // err.printStackTrace();
- System.out.println("Error " + err + " when obj = " + objToSave);
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_69_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- NonPublicClassTest test = new NonPublicClassTest();
- test.x10();
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, (test.equals(objLoaded)));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_70_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- int[] test = new int[1];
- int intValue = 0;
- test[0] = intValue;
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(test,
- (int[]) objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_71_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- int i, j, maxJ = 3, maxI = 200;
- byte[][] obj = new byte[maxJ][maxI];
- for (j = 0; j < maxJ; j++) {
- for (i = 0; i < maxI; i++)
- obj[j][i] = (byte) (i - 100);
- }
- objToSave = obj;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- byte[][] toCompare = (byte[][]) objLoaded;
-
- boolean ok = true;
- // Has to have worked
- for (j = 0; j < maxJ; j++) {
- for (i = 0; i < maxI; i++)
- if (obj[j][i] != toCompare[j][i]) {
- ok = false;
- break;
- }
- }
-
- assertTrue(MSG_TEST_FAILED + objToSave, ok);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_72_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- int i, j, maxJ = 3, maxI = 200;
- int[][] obj = new int[maxJ][maxI];
- for (j = 0; j < maxJ; j++) {
- for (i = 0; i < maxI; i++)
- obj[j][i] = (i - 100);
- }
- objToSave = obj;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- int[][] toCompare = (int[][]) objLoaded;
-
- boolean ok = true;
- // Has to have worked
- for (j = 0; j < maxJ; j++) {
- for (i = 0; i < maxI; i++)
- if (obj[j][i] != toCompare[j][i]) {
- ok = false;
- break;
- }
- }
-
- assertTrue(MSG_TEST_FAILED + objToSave, ok);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_73_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- String org = "abcdefghijklmnopqrstuvxyz1234567890abcdefghijklmnopqrstuvxyz1234567890";
- int i, j, maxJ = 3, maxI = 70;
- String[][] obj = new String[maxJ][maxI];
- for (j = 0; j < maxJ; j++) {
- for (i = 0; i < maxI; i++)
- obj[j][i] = org.substring(0, i);
- }
- objToSave = obj;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- String[][] toCompare = (String[][]) objLoaded;
-
- boolean ok = true;
- // Has to have worked
- for (j = 0; j < maxJ; j++) {
- for (i = 0; i < maxI; i++)
- if (!obj[j][i].equals(toCompare[j][i])) {
- ok = false;
- break;
- }
- }
-
- assertTrue(MSG_TEST_FAILED + objToSave, ok);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_74_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- SameInstVarNameSubClass test = new SameInstVarNameSubClass(100);
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave,
- ((SameInstVarNameSubClass) objLoaded).foo == 100);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_75_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- SInterfaceTest test = new SInterfaceTest();
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_76_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- SInterfaceTest2 test = new SInterfaceTest2();
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_77_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- SuperclassTest test = new SuperclassTest();
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_78_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- SuperclassTest2 test = new SuperclassTest2();
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_79_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- SyntheticFieldTest test = new SyntheticFieldTest();
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_80_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- try {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- DataOutputStream dos = new DataOutputStream(out);
- new ObjectOutputStream(dos); // just to make sure we get a header
- dos.writeByte(ObjectStreamConstants.TC_BLOCKDATA);
- int length = 99;
- dos.writeByte(length);
- for (int i = 0; i < length; i++) {
- dos.writeByte(0); // actual value does not matter
- }
- dos.flush();
- int lengthRead = 0;
- try {
- ObjectInputStream ois = new ObjectInputStream(
- new ByteArrayInputStream(out.toByteArray()));
- Object obj = ois.readObject();
- } catch (OptionalDataException e) {
- lengthRead = e.length;
- }
- assertTrue("Did not throw exception with optional data size ",
- length == lengthRead);
- } catch (ClassNotFoundException e) {
- fail("Unable to read BLOCKDATA: " + e.getMessage());
- } catch (IOException e) {
- fail("IOException testing BLOCKDATA : " + e.getMessage());
- } catch (Error err) {
- System.out.println("Error " + err + " when testing BLOCKDATA");
- throw err;
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/SerializationStressTest3.java b/luni/src/test/java/tests/api/java/io/SerializationStressTest3.java
deleted file mode 100644
index f3617a3..0000000
--- a/luni/src/test/java/tests/api/java/io/SerializationStressTest3.java
+++ /dev/null
@@ -1,2065 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.ObjectStreamConstants;
-import java.io.ObjectStreamField;
-import java.io.OptionalDataException;
-import java.math.BigInteger;
-import java.security.PermissionCollection;
-import java.util.Arrays;
-import java.util.BitSet;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.Locale;
-import java.util.PropertyPermission;
-import java.util.TimeZone;
-import java.util.Vector;
-
-@TestTargetClass(java.io.Serializable.class)
-public class SerializationStressTest3 extends SerializationStressTest {
-
- // -----------------------------------------------------------------------------------
- private static class DefaultConstructor implements java.io.Serializable {
- int f1;
-
- static int valueAfterConstructor = 5;
-
- DefaultConstructor() {
- f1 = valueAfterConstructor;
- }
-
- public boolean equals(Object obj) {
- /*
- * This method is not answering it the objs is equal. It is
- * answering if the vars have the value that it have to have after
- * dumping and loading
- */
-
- if (obj == null)
- return false;
- if (!(obj instanceof DefaultConstructor))
- return false;
-
- DefaultConstructor inst = (DefaultConstructor) obj;
- return inst.f1 == valueAfterConstructor;
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class NonSerDefaultConstructor {
- public int f1;
-
- public static int valueAfterConstructor = 5;
-
- NonSerDefaultConstructor() {
- f1 = valueAfterConstructor;
- }
-
- public NonSerDefaultConstructor(String notUsed) {
- }
- }
-
- private static class NonSerPrivateConstructor {
- public int f1;
-
- public static int valueAfterConstructor = 5;
-
- private NonSerPrivateConstructor() {
- f1 = valueAfterConstructor;
- }
-
- public NonSerPrivateConstructor(String notUsed) {
- }
- }
-
- private static class NonSerProtectedConstructor {
- public int f1;
-
- public static int valueAfterConstructor = 5;
-
- protected NonSerProtectedConstructor() {
- f1 = valueAfterConstructor;
- }
- }
-
- private static class NonSerPublicConstructor {
- public int f1;
-
- public static int valueAfterConstructor = 5;
-
- public NonSerPublicConstructor() {
- f1 = valueAfterConstructor;
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class DefaultConstructorSub extends NonSerDefaultConstructor
- implements java.io.Serializable {
- int fsub;
-
- static int subValueAfterConstructor = 11;
-
- public DefaultConstructorSub() {
- f1 = 7;
- fsub = subValueAfterConstructor;
- }
-
- public boolean equals(Object obj) {
- /*
- * This method is not answering it the objs is equal. It is
- * answering if the vars have the value that it have to have after
- * dumping and loading
- */
-
- if (obj == null)
- return false;
- if (!(obj instanceof DefaultConstructorSub))
- return false;
-
- DefaultConstructorSub inst = (DefaultConstructorSub) obj;
- if (inst.f1 != valueAfterConstructor)
- return false;
- return inst.fsub == subValueAfterConstructor;
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class PrivateConstructor implements java.io.Serializable {
- int f1;
-
- static int valueAfterConstructor = 5;
-
- private PrivateConstructor() {
- f1 = valueAfterConstructor;
- }
-
- public boolean equals(Object obj) {
- /*
- * This method is not answering it the objs is equal. Is is
- * answering if the vars have the value that it have to have after
- * dumping and loading
- */
-
- if (obj == null)
- return false;
- if (!(obj instanceof PrivateConstructor))
- return false;
-
- PrivateConstructor inst = (PrivateConstructor) obj;
- return inst.f1 == valueAfterConstructor;
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class PrivateConstructorSub extends NonSerPrivateConstructor
- implements java.io.Serializable {
- int fsub;
-
- static int subValueAfterConstructor = 11;
-
- public PrivateConstructorSub() {
- super("notUsed");
- f1 = 7;
- fsub = subValueAfterConstructor;
- }
-
- public boolean equals(Object obj) {
- /*
- * This method is not answering it the objs is equal. Is is
- * answering if the vars have the value that it have to have after
- * dumping and loading
- */
-
- if (obj == null)
- return false;
- if (!(obj instanceof PrivateConstructorSub))
- return false;
-
- PrivateConstructorSub inst = (PrivateConstructorSub) obj;
- return inst.f1 == valueAfterConstructor
- && inst.fsub == subValueAfterConstructor;
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class ProtectedConstructor implements java.io.Serializable {
- int f1;
-
- static int valueAfterConstructor = 5;
-
- protected ProtectedConstructor() {
- f1 = valueAfterConstructor;
- }
-
- public boolean equals(Object obj) {
- /*
- * This method is not answering it the objs is equal. Is is
- * answering if the vars have the value that it have to have after
- * dumping and loading
- */
-
- if (obj == null)
- return false;
- if (!(obj instanceof ProtectedConstructor))
- return false;
-
- ProtectedConstructor inst = (ProtectedConstructor) obj;
- return inst.f1 == valueAfterConstructor;
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class ProtectedConstructorSub extends
- NonSerProtectedConstructor implements java.io.Serializable {
- int fsub;
-
- static int subValueAfterConstructor = 11;
-
- public ProtectedConstructorSub() {
- f1 = 7;
- fsub = subValueAfterConstructor;
- }
-
- public boolean equals(Object obj) {
- /*
- * This method is not answering it the objs is equal. Is is
- * answering if the vars have the value that it have to have after
- * dumping and loading
- */
-
- if (obj == null)
- return false;
- if (!(obj instanceof ProtectedConstructorSub))
- return false;
-
- ProtectedConstructorSub inst = (ProtectedConstructorSub) obj;
- return inst.f1 == valueAfterConstructor
- && inst.fsub == subValueAfterConstructor;
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class PublicConstructor implements java.io.Serializable {
- int f1;
-
- static int valueAfterConstructor = 5;
-
- public PublicConstructor() {
- f1 = valueAfterConstructor;
- }
-
- public boolean equals(Object obj) {
- /*
- * This method is not answering it the objs is equal. Is is
- * answering if the vars have the value that it have to have after
- * dumping and loading
- */
-
- if (obj == null)
- return false;
- if (!(obj instanceof PublicConstructor))
- return false;
-
- PublicConstructor inst = (PublicConstructor) obj;
- return inst.f1 == valueAfterConstructor;
- }
- }
-
- // -----------------------------------------------------------------------------------
- private static class PublicConstructorSub extends NonSerPublicConstructor
- implements java.io.Serializable {
- int fsub;
-
- static final int subValueAfterConstructor = 11;
-
- public PublicConstructorSub() {
- f1 = 7;
- fsub = subValueAfterConstructor;
- }
-
- public boolean equals(Object obj) {
- /*
- * This method is not answering it the objs is equal. It is
- * answering if the vars have the value that it have to have after
- * dumping and loading
- */
-
- if (obj == null)
- return false;
- if (!(obj instanceof PublicConstructorSub))
- return false;
-
- PublicConstructorSub inst = (PublicConstructorSub) obj;
- return inst.f1 == valueAfterConstructor
- && inst.fsub == subValueAfterConstructor;
- }
- }
-
- // Tests the behavior of ObjectOutputStream.PutField.write()
- private static class WriteFieldsUsingPutFieldWrite implements
- java.io.Serializable {
- private static final ObjectStreamField[] serialPersistentFields = {
- new ObjectStreamField("object1", Vector.class),
- new ObjectStreamField("int1", Integer.TYPE) };
-
- private static Vector v1 = new Vector(Arrays.asList(new String[] {
- "1st", "2nd" }));
-
- private boolean passed = false;
-
- public WriteFieldsUsingPutFieldWrite() {
- super();
- }
-
- public boolean passed() {
- return passed;
- }
-
- private void readObject(java.io.ObjectInputStream in)
- throws java.io.IOException, ClassNotFoundException {
- int int1 = in.readInt();
- Vector object1 = (Vector) in.readObject();
- passed = int1 == 0xA9 && object1.equals(v1);
- }
-
- private void writeObject(java.io.ObjectOutputStream out)
- throws java.io.IOException, ClassNotFoundException {
- ObjectOutputStream.PutField fields = out.putFields();
- fields.put("object1", v1);
- fields.put("int1", 0xA9);
- // Use fields.write() instead of out.writeFields();
- fields.write(out);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_81_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- try {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- DataOutputStream dos = new DataOutputStream(out);
- new ObjectOutputStream(dos); // just to make sure we get a header
- dos.writeByte(ObjectStreamConstants.TC_BLOCKDATALONG);
- int length = 333; // Bigger than 1 byte
- dos.writeInt(length);
- for (int i = 0; i < length; i++) {
- dos.writeByte(0); // actual value does not matter
- }
- dos.flush();
- int lengthRead = 0;
- try {
- ObjectInputStream ois = new ObjectInputStream(
- new ByteArrayInputStream(out.toByteArray()));
- Object obj = ois.readObject();
- } catch (OptionalDataException e) {
- lengthRead = e.length;
- }
- assertTrue("Did not throw exception with optional data size ",
- length == lengthRead);
- } catch (ClassNotFoundException e) {
- fail("Unable to read BLOCKDATA : " + e.getMessage());
- } catch (IOException e) {
- fail("IOException testing BLOCKDATALONG : " + e.getMessage());
- } catch (Error err) {
- System.out.println("Error " + err + " when testing BLOCKDATALONG");
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_82_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- DefaultConstructor test = new DefaultConstructor();
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_83_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- DefaultConstructorSub test = new DefaultConstructorSub();
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_84_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- PrivateConstructor test = new PrivateConstructor();
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void _test_18_85_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- PrivateConstructorSub test = new PrivateConstructorSub();
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_86_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- ProtectedConstructor test = new ProtectedConstructor();
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_87_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- ProtectedConstructorSub test = new ProtectedConstructorSub();
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_88_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- PublicConstructor test = new PublicConstructor();
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_89_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- PublicConstructorSub test = new PublicConstructorSub();
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_90_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = TABLE;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, TABLE.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_91_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- Object col = Collections.synchronizedMap(TABLE);
- objToSave = col;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_92_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- Object col = Collections.unmodifiableMap(TABLE);
- objToSave = col;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_93_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = MAP;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, MAP.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_94_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- Object col = Collections.synchronizedMap(MAP);
- objToSave = col;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_95_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- Object col = Collections.unmodifiableMap(MAP);
- objToSave = col;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_96_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = ALIST;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, ALIST.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_97_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = LIST;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, LIST.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_98_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- Object col = Collections.synchronizedList(LIST);
- objToSave = col;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_99_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- Object col = Collections.unmodifiableList(LIST);
- objToSave = col;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_100_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = SET;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, SET.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_101_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- Object col = Collections.synchronizedSet(SET);
- objToSave = col;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_102_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- Object col = Collections.unmodifiableSet(SET);
- objToSave = col;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_103_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = TREE;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, TREE.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_104_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- Object col = Collections.synchronizedSortedMap(TREE);
- objToSave = col;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_105_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- Object col = Collections.unmodifiableSortedMap(TREE);
- objToSave = col;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_106_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = SORTSET;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, SET.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_107_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- Object col = Collections.synchronizedSortedSet(SORTSET);
- objToSave = col;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_108_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- Object col = Collections.unmodifiableSortedSet(SORTSET);
- objToSave = col;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, col.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void _test_18_109_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = CALENDAR;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, CALENDAR.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void _test_18_110_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- TimeZone test = TimeZone.getTimeZone("EST");
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void _test_18_111_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- TimeZone test = TimeZone.getTimeZone("EST");
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void _test_18_112_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- TimeZone test = TimeZone.getTimeZone("GMT");
- objToSave = test;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, test.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void _test_18_113_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = DATEFORM;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, DATEFORM.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_114_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = CHOICE;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, CHOICE.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void _test_18_115_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = NUMBERFORM;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, NUMBERFORM
- .equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_116_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = MESSAGE;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, MESSAGE.toPattern().equals(
- ((java.text.MessageFormat) objLoaded).toPattern()));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_117_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = PERM;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, PERM.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_118_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = PERMCOL;
- Enumeration elementsBefore = PERMCOL.elements();
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- Enumeration elementsAfter = ((PermissionCollection) objLoaded)
- .elements();
- boolean equals = true;
- while (elementsBefore.hasMoreElements()) {
- // To make sure elements are the same
- Object oBefore = elementsBefore.nextElement();
- Object oAfter = elementsAfter.nextElement();
- equals &= oBefore.equals(oAfter);
-
- }
- // To make sure sizes are the same
- equals &= elementsBefore.hasMoreElements() == elementsAfter
- .hasMoreElements();
-
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_119_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = Locale.CHINESE;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, Locale.CHINESE
- .equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_120_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = LINKEDLIST;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, LINKEDLIST
- .equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_121_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = java.text.AttributedCharacterIterator.Attribute.INPUT_METHOD_SEGMENT;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(
- MSG_TEST_FAILED + objToSave,
- java.text.AttributedCharacterIterator.Attribute.INPUT_METHOD_SEGMENT == objLoaded);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_122_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = java.text.AttributedCharacterIterator.Attribute.LANGUAGE;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(
- MSG_TEST_FAILED + objToSave,
- java.text.AttributedCharacterIterator.Attribute.LANGUAGE == objLoaded);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_123_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = java.text.AttributedCharacterIterator.Attribute.READING;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(
- MSG_TEST_FAILED + objToSave,
- java.text.AttributedCharacterIterator.Attribute.READING == objLoaded);
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_124_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = new Object[] { Integer.class, new Integer(1) };
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Classes with the same name are unique, so test for ==
- assertTrue(MSG_TEST_FAILED + objToSave,
- ((Object[]) objLoaded)[0] == ((Object[]) objToSave)[0]
- && ((Object[]) objLoaded)[1]
- .equals(((Object[]) objToSave)[1]));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_125_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = new BigInteger[] { BigInteger.ZERO, BigInteger.ONE,
- BigInteger.valueOf(-1), BigInteger.valueOf(255),
- BigInteger.valueOf(-255),
- new BigInteger("75881644843307850793466070"),
- new BigInteger("-636104487142732527326202462") };
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
- (BigInteger[]) objLoaded, (BigInteger[]) objToSave));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_126_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = new WriteFieldsUsingPutFieldWrite();
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue(MSG_TEST_FAILED + objToSave,
- ((WriteFieldsUsingPutFieldWrite) objLoaded).passed());
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_127_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- BitSet bs = new BitSet(64);
- bs.set(1);
- bs.set(10);
- bs.set(100);
- bs.set(1000);
- objToSave = bs;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue(MSG_TEST_FAILED + objToSave, bs.equals(objLoaded));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_18_128_writeObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- PropertyPermission test = new PropertyPermission("java.*",
- "read,write");
- PermissionCollection p = test.newPermissionCollection();
- p.add(new PropertyPermission("java.*", "read"));
- p.add(new PropertyPermission("java.*", "write"));
- // System.out.println("Does implies work? " + p.implies(test));
-
- objToSave = p;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- assertTrue(MSG_TEST_FAILED + objToSave,
- ((PermissionCollection) objLoaded).implies(test));
-
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/SerializationStressTest4.java b/luni/src/test/java/tests/api/java/io/SerializationStressTest4.java
deleted file mode 100644
index 1ec1211..0000000
--- a/luni/src/test/java/tests/api/java/io/SerializationStressTest4.java
+++ /dev/null
@@ -1,3130 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.File;
-import java.io.FilePermission;
-import java.io.IOException;
-import java.io.Serializable;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.security.AllPermission;
-import java.security.PermissionCollection;
-import java.security.cert.Certificate;
-import java.text.DateFormat;
-import java.text.MessageFormat;
-import java.text.NumberFormat;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.Date;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.IdentityHashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-import java.util.TimeZone;
-
-import tests.support.Support_Configuration;
-import tests.support.Support_Proxy_I1;
-
-@TestTargetClass(java.io.Serializable.class)
-public class SerializationStressTest4 extends SerializationStressTest {
- // -----------------------------------------------------------------------------------
- private static class GuardImplementation implements java.security.Guard,
- java.io.Serializable {
- public GuardImplementation() {
- }
-
- public void checkGuard(Object o) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_EventObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.EventObject)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.util.EventObject("Source");
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- equals = true;
- // The the only data in EventObject that
- // differentiates between instantiations is transient
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_PermissionCollection() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.security.PermissionCollection)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = null;
- objToSave = new java.security.PermissionCollection() {
- boolean added = false;
-
- public void add(java.security.Permission p1) {
- added = true;
- }
-
- public java.util.Enumeration elements() {
- return (new java.util.Vector()).elements();
- }
-
- public boolean implies(java.security.Permission p1) {
- return added;
- }
-
- public boolean equals(Object obj) {
- if (!(obj instanceof java.security.PermissionCollection))
- return false;
- return implies(null) == ((PermissionCollection) obj)
- .implies(null);
- }
- };
-
- ((java.security.PermissionCollection) objToSave).add(null);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Collections_EmptySet() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.Collections.EmptySet)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = java.util.Collections.EMPTY_SET;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- equals = objToSave.equals(objLoaded);
- if (equals)
- equals = ((Set) objLoaded).size() == 0;
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Collections_EmptyMap() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.Collections.EmptySet)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = java.util.Collections.EMPTY_MAP;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- equals = objToSave.equals(objLoaded);
- if (equals)
- equals = ((Map) objLoaded).size() == 0;
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_BasicPermissionCollection() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.security.BasicPermissionCollection)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = (new RuntimePermission("test"))
- .newPermissionCollection();
- ((java.security.PermissionCollection) objToSave)
- .add(new RuntimePermission("test"));
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- Enumeration enum1 = ((java.security.PermissionCollection) objToSave)
- .elements(), enum2 = ((java.security.PermissionCollection) objLoaded)
- .elements();
-
- equals = true;
- while (enum1.hasMoreElements() && equals) {
- if (enum2.hasMoreElements())
- equals = enum1.nextElement().equals(enum2.nextElement());
- else
- equals = false;
- }
-
- if (equals)
- equals = !enum2.hasMoreElements();
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_UnresolvedPermission() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.security.UnresolvedPermission)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.security.UnresolvedPermission("type", "name",
- "actions", null);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- equals = objToSave.toString().equals(objLoaded.toString());
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Character() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Character)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.lang.Character('c');
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Collections_UnmodifiableCollection() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.Collections.UnmodifiableCollection)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = java.util.Collections.unmodifiableCollection(SET);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- equals = ((java.util.Collection) objToSave).size() == ((java.util.Collection) objLoaded)
- .size();
- if (equals) {
- java.util.Iterator iter1 = ((java.util.Collection) objToSave)
- .iterator(), iter2 = ((java.util.Collection) objLoaded)
- .iterator();
- while (iter1.hasNext())
- equals = equals && iter1.next().equals(iter2.next());
- }
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Format() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.text.Format)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = null;
- objToSave = new java.text.Format() {
- String save = "default";
-
- public StringBuffer format(Object p1, StringBuffer p2,
- java.text.FieldPosition p3) {
- return new StringBuffer();
- }
-
- public Object parseObject(String p1, java.text.ParsePosition p2) {
- if (p1 != null)
- save = p1;
- return save;
- }
-
- public boolean equals(Object obj) {
- if (!(obj instanceof java.text.Format))
- return false;
- return save.equals(((java.text.Format) obj).parseObject(
- null, null));
- }
- };
-
- ((java.text.Format) objToSave).parseObject("Test", null);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_BigDecimal() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.math.BigDecimal)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.math.BigDecimal("1.2345");
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_UnresolvedPermissionCollection() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.security.UnresolvedPermissionCollection)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = (new java.security.UnresolvedPermission("type", "name",
- "actions", null)).newPermissionCollection();
- ((java.security.PermissionCollection) objToSave)
- .add(new java.security.UnresolvedPermission("type", "name",
- "actions", null));
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- Enumeration enum1 = ((java.security.PermissionCollection) objToSave)
- .elements(), enum2 = ((java.security.PermissionCollection) objLoaded)
- .elements();
-
- equals = true;
- while (enum1.hasMoreElements() && equals) {
- if (enum2.hasMoreElements())
- equals = enum1.nextElement().toString().equals(
- enum2.nextElement().toString());
- else
- equals = false;
- }
-
- if (equals)
- equals = !enum2.hasMoreElements();
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_SecureRandomSpi() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.security.SecureRandomSpi)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = null;
- objToSave = new java.security.SecureRandomSpi() {
- protected byte[] engineGenerateSeed(int p1) {
- return new byte[0];
- }
-
- protected void engineNextBytes(byte[] p1) {
- }
-
- protected void engineSetSeed(byte[] p1) {
- }
-
- public boolean equals(Object obj) {
- return true;
- }
- };
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Short() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Short)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.lang.Short((short) 107);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Byte() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Byte)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.lang.Byte((byte) 107);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_String_CaseInsensitiveComparator() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.String.CaseInsensitiveComparator)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = java.lang.String.CASE_INSENSITIVE_ORDER;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- equals = ((Comparator) objToSave).compare("apple", "Banana") == ((Comparator) objLoaded)
- .compare("apple", "Banana");
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void _test_writeObject_Calendar() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.Calendar)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.util.Calendar(TimeZone.getTimeZone("EST"),
- Locale.CANADA) {
- public void add(int p1, int p2) {
- }
-
- protected void computeFields() {
- }
-
- protected void computeTime() {
- }
-
- public int getGreatestMinimum(int p1) {
- return 0;
- }
-
- public int getLeastMaximum(int p1) {
- return 0;
- }
-
- public int getMaximum(int p1) {
- return 0;
- }
-
- public int getMinimum(int p1) {
- return 0;
- }
-
- public void roll(int p1, boolean p2) {
- }
- };
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + "Calendar", objToSave
- .equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_ReflectPermission() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.reflect.ReflectPermission)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.lang.reflect.ReflectPermission(
- "TestSerialization", "test");
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_StringBuffer() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.StringBuffer)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.lang.StringBuffer("This is a test.");
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- equals = ((java.lang.StringBuffer) objToSave).toString().equals(
- ((java.lang.StringBuffer) objLoaded).toString());
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_File() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.io.File)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new File("afile.txt");
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_AllPermissionCollection() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.security.AllPermissionCollection)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = (new java.security.AllPermission())
- .newPermissionCollection();
- ((java.security.PermissionCollection) objToSave)
- .add(new java.security.AllPermission());
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- Enumeration enum1 = ((java.security.PermissionCollection) objToSave)
- .elements(), enum2 = ((java.security.PermissionCollection) objLoaded)
- .elements();
-
- equals = true;
- while (enum1.hasMoreElements() && equals) {
- if (enum2.hasMoreElements())
- equals = enum1.nextElement().equals(enum2.nextElement());
- else
- equals = false;
- }
-
- if (equals)
- equals = !enum2.hasMoreElements();
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_BitSet() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.BitSet)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.util.BitSet();
- ((java.util.BitSet) objToSave).set(3);
- ((java.util.BitSet) objToSave).set(5);
- ((java.util.BitSet) objToSave).set(61, 89);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_DateFormat() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.text.DateFormat)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = null;
- objToSave = new java.text.DateFormat() {
- // Thu Feb 01 01:01:01 EST 2001
- java.util.Date save = new java.util.Date(981007261000L);
-
- public StringBuffer format(Date p1, StringBuffer p2,
- java.text.FieldPosition p3) {
- if (p1 != null)
- save = p1;
- return new StringBuffer(Long.toString(save.getTime()));
- }
-
- public Date parse(String p1, java.text.ParsePosition p2) {
- return save;
- }
-
- public String toString() {
- return save.toString();
- }
-
- public boolean equals(Object obj) {
- if (!(obj instanceof java.text.DateFormat))
- return false;
- return save.equals(((java.text.DateFormat) obj).parse(null,
- null));
- }
- };
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Collections_CopiesList() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.Collections.CopiesList)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = java.util.Collections.nCopies(2, new Integer(2));
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- equals = ((List) objToSave).get(0)
- .equals(((List) objLoaded).get(0));
- if (equals)
- equals = ((List) objToSave).get(1).equals(
- ((List) objLoaded).get(1));
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_SerializablePermission() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.io.SerializablePermission)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.io.SerializablePermission("TestSerialization",
- "Test");
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Properties() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.Properties)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.util.Properties();
- ((java.util.Properties) objToSave).put("key1", "value1");
- ((java.util.Properties) objToSave).put("key2", "value2");
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- Enumeration enum1 = ((java.util.Properties) objToSave).elements(), enum2 = ((java.util.Properties) objLoaded)
- .elements();
-
- equals = true;
- while (enum1.hasMoreElements() && equals) {
- if (enum2.hasMoreElements())
- equals = enum1.nextElement().equals(enum2.nextElement());
- else
- equals = false;
- }
-
- if (equals)
- equals = !enum2.hasMoreElements();
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- // TODO : requires working security implementation
- // public void test_writeObject_BasicPermission() {
- // // Test for method void
- // //
- // java.io.ObjectOutputStream.writeObject(tests.java.security.Test_BasicPermission.BasicPermissionSubclass)
- //
- // Object objToSave = null;
- // Object objLoaded = null;
- //
- // try {
- // objToSave = new
- // tests.java.security.Test_BasicPermission.BasicPermissionSubclass(
- // "TestSerialization");
- // if (DEBUG)
- // System.out.println("Obj = " + objToSave);
- // objLoaded = dumpAndReload(objToSave);
- //
- // // Has to have worked
- // assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- // } catch (IOException e) {
- // fail("Exception serializing " + objToSave + " : "
- // + e.getMessage());
- // } catch (ClassNotFoundException e) {
- // fail("ClassNotFoundException reading Object type : " + e.getMessage());
- // } catch (Error err) {
- // System.out.println("Error when obj = " + objToSave);
- // // err.printStackTrace();
- // throw err;
- // }
- //
- // }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void _test_writeObject_Collections_UnmodifiableMap_UnmodifiableEntrySet() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.Collections.UnmodifiableMap.UnmodifiableEntrySet)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = java.util.Collections.unmodifiableMap(MAP).entrySet();
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- equals = ((java.util.Collection) objToSave).size() == ((java.util.Collection) objLoaded)
- .size();
- if (equals) {
- java.util.Iterator iter1 = ((java.util.Collection) objToSave)
- .iterator(), iter2 = ((java.util.Collection) objLoaded)
- .iterator();
- while (iter1.hasNext())
- equals = equals && iter1.next().equals(iter2.next());
- }
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_NumberFormat() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.text.NumberFormat)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = null;
- objToSave = new java.text.NumberFormat() {
- long save = 107;
-
- public StringBuffer format(double p1, StringBuffer p2,
- java.text.FieldPosition p3) {
- return new StringBuffer();
- }
-
- public StringBuffer format(long p1, StringBuffer p2,
- java.text.FieldPosition p3) {
- if (p1 != 0)
- save = p1;
- return new StringBuffer(Long.toString(save));
- }
-
- public Number parse(String p1, java.text.ParsePosition p2) {
- return new Long(save);
- }
-
- public boolean equals(Object obj) {
- if (!(obj instanceof java.text.NumberFormat))
- return false;
- return save == ((Long) ((java.text.NumberFormat) obj)
- .parse(null, null)).longValue();
- }
- };
-
- ((java.text.NumberFormat) objToSave).format(63L, null, null);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_TimeZone() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.TimeZone)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = null;
- objToSave = new java.util.TimeZone() {
- int save = 0;
-
- public int getOffset(int p1, int p2, int p3, int p4, int p5,
- int p6) {
- return 0;
- }
-
- public int getRawOffset() {
- return save;
- }
-
- public boolean inDaylightTime(java.util.Date p1) {
- return false;
- }
-
- public void setRawOffset(int p1) {
- save = p1;
- }
-
- public boolean useDaylightTime() {
- return false;
- }
-
- public boolean equals(Object obj) {
- if (obj instanceof TimeZone)
- return save == ((TimeZone) obj).getRawOffset();
- return false;
- }
- };
-
- ((java.util.TimeZone) objToSave).setRawOffset(48);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Double() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Double)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.lang.Double(1.23);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Number() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Number)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = null;
- objToSave = new Number() {
- int numCalls = 0;
-
- public double doubleValue() {
- return ++numCalls;
- }
-
- public float floatValue() {
- return ++numCalls;
- }
-
- public int intValue() {
- return numCalls;
- }
-
- public long longValue() {
- return ++numCalls;
- }
-
- public boolean equals(Object obj) {
- if (!(obj instanceof java.lang.Number))
- return false;
- return intValue() == ((Number) obj).intValue();
- }
- };
- ((java.lang.Number) objToSave).doubleValue();
- ((java.lang.Number) objToSave).floatValue();
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_AllPermission() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.security.AllPermission)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.security.AllPermission();
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Collections_ReverseComparator() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.Collections.ReverseComparator)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = java.util.Collections.reverseOrder();
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- equals = ((Comparator) objToSave).compare("Hello", "Jello") == ((Comparator) objLoaded)
- .compare("Hello", "Jello");
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("IOException serializing " + objToSave + " : "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type : "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_DateFormatSymbols() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.text.DateFormatSymbols)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.text.DateFormatSymbols(Locale.CHINESE);
- ((java.text.DateFormatSymbols) objToSave)
- .setZoneStrings(new String[][] { { "a", "b", "c", "d" },
- { "e", "f", "g", "h" } });
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Collections_EmptyList() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.Collections.EmptyList)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = java.util.Collections.EMPTY_LIST;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- equals = objToSave.equals(objLoaded);
- if (equals)
- equals = ((List) objLoaded).size() == 0;
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Boolean() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Boolean)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.lang.Boolean(true);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Collections_SingletonSet() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.Collections.SingletonSet)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = java.util.Collections.singleton(new Byte((byte) 107));
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- java.util.Iterator iter = ((Set) objLoaded).iterator();
- equals = iter.hasNext();
- if (equals)
- equals = iter.next().equals(new Byte((byte) 107));
- if (equals)
- equals = !iter.hasNext();
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Collections_SingletonList() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.Collections.SingletonSet)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = java.util.Collections
- .singletonList(new Byte((byte) 107));
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- java.util.Iterator iter = ((List) objLoaded).iterator();
- equals = objLoaded.equals(objToSave) && iter.hasNext()
- && iter.next().equals(new Byte((byte) 107))
- && !iter.hasNext();
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Collections_SingletonMap() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.Collections.SingletonSet)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = java.util.Collections.singletonMap("key", new Byte(
- (byte) 107));
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- java.util.Iterator iter = ((Map) objLoaded).entrySet().iterator();
- equals = objLoaded.equals(objToSave) && iter.hasNext();
- Map.Entry entry = (Map.Entry) iter.next();
- equals = equals && entry.getKey().equals("key")
- && entry.getValue().equals(new Byte((byte) 107))
- && !iter.hasNext();
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_FilePermission_FilePermissionCollection() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.io.FilePermission.FilePermissionCollection)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = (new java.io.FilePermission("<<ALL FILES>>", "read"))
- .newPermissionCollection();
- ((java.security.PermissionCollection) objToSave)
- .add(new FilePermission("<<ALL FILES>>", "read"));
- ((java.security.PermissionCollection) objToSave)
- .add(new FilePermission("d:\\", "read"));
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- java.util.Enumeration enum1 = ((java.security.PermissionCollection) objToSave)
- .elements(), enum2 = ((java.security.PermissionCollection) objLoaded)
- .elements();
-
- equals = true;
- while (enum1.hasMoreElements() && equals) {
- if (enum2.hasMoreElements())
- equals = enum1.nextElement().equals(enum2.nextElement());
- else
- equals = false;
- }
-
- if (equals)
- equals = !enum2.hasMoreElements();
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_SecureRandom() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.security.SecureRandom)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.security.SecureRandom();
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- equals = true; // assume fine because of the nature of the class,
- // it is difficult to determine if they are the same
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_FilePermission() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.io.FilePermission)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.io.FilePermission("<<ALL FILES>>", "read");
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_InetAddress() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.net.InetAddress)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = java.net.InetAddress
- .getByName(Support_Configuration.InetTestIP);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Inet6Address() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.net.Inet6Address)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = java.net.Inet6Address
- .getByName(Support_Configuration.InetTestIP6);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
-
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_RuntimePermission() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.RuntimePermission)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.lang.RuntimePermission("TestSerialization",
- "Test");
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Permissions() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.security.Permissions)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.security.Permissions();
- ((java.security.Permissions) objToSave).add(new AllPermission());
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- Enumeration enum1 = ((java.security.PermissionCollection) objToSave)
- .elements(), enum2 = ((java.security.PermissionCollection) objLoaded)
- .elements();
- java.util.Vector vec1 = new java.util.Vector(), vec2 = new java.util.Vector();
-
- while (enum1.hasMoreElements())
- vec1.add(enum1.nextElement());
- while (enum2.hasMoreElements())
- vec2.add(enum2.nextElement());
-
- equals = vec1.size() == vec2.size();
- if (equals) {
- int length = vec1.size();
- Object[] perms1 = new Object[length], perms2 = new Object[length];
- for (int i = 0; i < length; ++i) {
- perms1[i] = vec1.elementAt(i);
- perms2[i] = vec2.elementAt(i);
- }
-
- Comparator comparator = new Comparator() {
- public int compare(Object o1, Object o2) {
- return o1.toString().compareTo(o2.toString());
- }
-
- public boolean equals(Object o1, Object o2) {
- return o1.toString().equals(o2.toString());
- }
- };
-
- java.util.Arrays.sort(perms1, comparator);
- java.util.Arrays.sort(perms2, comparator);
-
- for (int i = 0; i < length && equals; ++i)
- equals = perms1[i].equals(perms2[i]);
- }
-
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Date() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.Date)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- // Thu Feb 01 01:01:01 EST 2001
- objToSave = new java.util.Date(981007261000L);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Float() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Float)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.lang.Float(1.23f);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_SecurityPermission() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.security.SecurityPermission)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.security.SecurityPermission(
- "TestSerialization", "Test");
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_SocketPermission_SocketPermissionCollection() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.net.SocketPermission.SocketPermissionCollection)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = (new java.net.SocketPermission("www.yahoo.com",
- "connect")).newPermissionCollection();
- ((java.security.PermissionCollection) objToSave)
- .add(new java.net.SocketPermission("www.yahoo.com",
- "connect"));
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- Enumeration enum1 = ((java.security.PermissionCollection) objToSave)
- .elements(), enum2 = ((java.security.PermissionCollection) objLoaded)
- .elements();
-
- equals = true;
- while (enum1.hasMoreElements() && equals) {
- if (enum2.hasMoreElements())
- equals = enum1.nextElement().equals(enum2.nextElement());
- else
- equals = false;
- }
-
- if (equals)
- equals = !enum2.hasMoreElements();
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Stack() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.Stack)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.util.Stack();
- ((java.util.Stack) objToSave).push("String 1");
- ((java.util.Stack) objToSave).push("String 2");
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- equals = true;
- while (!((java.util.Stack) objToSave).empty() && equals) {
- if (!((java.util.Stack) objLoaded).empty())
- equals = ((java.util.Stack) objToSave).pop().equals(
- ((java.util.Stack) objLoaded).pop());
- else
- equals = false;
- }
-
- if (equals)
- equals = ((java.util.Stack) objLoaded).empty();
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_DecimalFormatSymbols() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.text.DecimalFormatSymbols)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.text.DecimalFormatSymbols(Locale.CHINESE);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_NetPermission() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.net.NetPermission)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.net.NetPermission("TestSerialization", "Test");
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_AttributedCharacterIterator_Attribute() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.text.AttributedCharacterIterator.Attribute)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = java.text.AttributedCharacterIterator.Attribute.LANGUAGE;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Long() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Long)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.lang.Long(107L);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_CodeSource() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.security.CodeSource)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = null;
- try {
- objToSave = new java.security.CodeSource(new java.net.URL(
- "http://localhost/a.txt"),
- (Certificate[])null);
- } catch (Exception e) {
- fail("Exception creating object : " + e.getMessage());
- }
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Collections_SynchronizedCollection() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.Collections.SynchronizedCollection)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = java.util.Collections.synchronizedCollection(SET);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- equals = ((java.util.Collection) objToSave).size() == ((java.util.Collection) objLoaded)
- .size();
- if (equals) {
- java.util.Iterator iter1 = ((java.util.Collection) objToSave)
- .iterator(), iter2 = ((java.util.Collection) objLoaded)
- .iterator();
- while (iter1.hasNext())
- equals = equals && iter1.next().equals(iter2.next());
- }
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Permission() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.security.Permission)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = null;
- objToSave = new java.security.Permission("test") {
- public boolean equals(Object p1) {
- if (!(p1 instanceof java.security.Permission))
- return false;
- return getName().equals(
- ((java.security.Permission) p1).getName());
- }
-
- public int hashCode() {
- return 0;
- }
-
- public String getActions() {
- return null;
- }
-
- public boolean implies(java.security.Permission p1) {
- return false;
- }
- };
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave.equals(objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Random() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.Random)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.util.Random(107L);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- equals = ((java.util.Random) objToSave).nextInt() == ((java.util.Random) objLoaded)
- .nextInt();
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_GuardedObject() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.security.GuardedObject)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = new java.security.GuardedObject("Test Object",
- new GuardImplementation());
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- boolean equals;
- equals = ((java.security.GuardedObject) objToSave).getObject()
- .equals(
- ((java.security.GuardedObject) objLoaded)
- .getObject());
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- // TODO : Reintroduce when we have a working security implementation
- // public void test_writeObject_KeyPair() {
- // // Test for method void
- // // java.io.ObjectOutputStream.writeObject(java.security.GuardedObject)
- //
- // Object objToSave = null;
- // Object objLoaded = null;
- //
- // try {
- // objToSave = new java.security.KeyPair(null, null);
- // if (DEBUG)
- // System.out.println("Obj = " + objToSave);
- // objLoaded = dumpAndReload(objToSave);
- //
- // // Has to have worked
- // boolean equals;
- // equals = true;
- // assertTrue(MSG_TEST_FAILED + objToSave, equals);
- // } catch (IOException e) {
- // fail("IOException serializing " + objToSave + " : "
- // + e.getMessage());
- // } catch (ClassNotFoundException e) {
- // fail("ClassNotFoundException reading Object type : " + e.getMessage());
- // } catch (Error err) {
- // System.out.println("Error when obj = " + objToSave);
- // // err.printStackTrace();
- // throw err;
- // }
- // }
-
- static class MyInvocationHandler implements InvocationHandler, Serializable {
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- if (method.getName().equals("equals"))
- return new Boolean(proxy == args[0]);
- if (method.getName().equals("array"))
- return new int[] { (int) ((long[]) args[0])[1], -1 };
- if (method.getName().equals("string")) {
- if ("error".equals(args[0]))
- throw new ArrayStoreException();
- if ("any".equals(args[0]))
- throw new IllegalAccessException();
- }
- return null;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void _test_writeObject_Proxy() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.security.GuardedObject)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = Proxy.getProxyClass(Support_Proxy_I1.class
- .getClassLoader(), new Class[] { Support_Proxy_I1.class });
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- assertTrue(MSG_TEST_FAILED + "not a proxy class", Proxy
- .isProxyClass((Class) objLoaded));
- Class[] interfaces = ((Class) objLoaded).getInterfaces();
- assertTrue(MSG_TEST_FAILED + "wrong interfaces length",
- interfaces.length == 1);
- assertTrue(MSG_TEST_FAILED + "wrong interface",
- interfaces[0] == Support_Proxy_I1.class);
-
- InvocationHandler handler = new MyInvocationHandler();
- objToSave = Proxy.newProxyInstance(Support_Proxy_I1.class
- .getClassLoader(), new Class[] { Support_Proxy_I1.class },
- handler);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- boolean equals = Proxy.getInvocationHandler(objLoaded).getClass() == MyInvocationHandler.class;
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
-
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_URI() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.net.URI)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- try {
- objToSave = new URI[] {
- // single arg constructor
- new URI(
- "http://user%60%20info@host/a%20path?qu%60%20ery#fr%5E%20ag"),
- // escaped octets for illegal chars
- new URI(
- "http://user%C3%9F%C2%A3info@host:80/a%E2%82%ACpath?qu%C2%A9%C2%AEery#fr%C3%A4%C3%A8g"),
- // escaped octets for unicode chars
- new URI(
- "ascheme://user\u00DF\u00A3info@host:0/a\u20ACpath?qu\u00A9\u00AEery#fr\u00E4\u00E8g"),
- // multiple arg constructors
- new URI("http", "user%60%20info", "host", 80,
- "/a%20path", "qu%60%20ery", "fr%5E%20ag"),
- // escaped octets for illegal
- new URI("http", "user%C3%9F%C2%A3info", "host", -1,
- "/a%E2%82%ACpath", "qu%C2%A9%C2%AEery",
- "fr%C3%A4%C3%A8g"),
- // escaped octets for unicode
- new URI("ascheme", "user\u00DF\u00A3info", "host", 80,
- "/a\u20ACpath", "qu\u00A9\u00AEery",
- "fr\u00E4\u00E8g"),
- new URI("http", "user` info", "host", 81, "/a path",
- "qu` ery", "fr^ ag"), // illegal chars
- new URI("http", "user%info", "host", 0, "/a%path",
- "que%ry", "f%rag"),
- // % as illegal char, not escaped octet urls with
- // undefined components
- new URI("mailto", "user@domain.com", null),
- // no host, path, query or fragment
- new URI("../adirectory/file.html#"),
- // relative path with empty fragment;
- new URI("news", "comp.infosystems.www.servers.unix",
- null),
- new URI(null, null, null, "fragment"),
- // only fragment
- new URI("telnet://server.org"), // only host
- new URI("http://reg:istry?query"),
- // malformed hostname, therefore registry-based,
- // with query
- new URI("file:///c:/temp/calculate.pl?")
- // empty authority, non empty path, empty query
- };
- } catch (URISyntaxException e) {
- fail("Unexpected Exception:" + e);
- }
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, Arrays.equals(
- (URI[]) objToSave, (URI[]) objLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_URISyntaxException() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.net.URISyntaxException)
-
- URISyntaxException objToSave = null;
- URISyntaxException objLoaded = null;
-
- try {
- objToSave = new URISyntaxException("str", "problem", 4);
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = (URISyntaxException) dumpAndReload(objToSave);
-
- boolean equals = objToSave.getMessage().equals(
- objLoaded.getMessage())
- && objToSave.getInput().equals(objLoaded.getInput())
- && objToSave.getIndex() == objLoaded.getIndex()
- && objToSave.getReason().equals(objLoaded.getReason());
-
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_Currency() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.util.Currency)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = java.util.Currency.getInstance("AMD");
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- // we need same instance for the same currency code
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave == objToSave);
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_DateFormat_Field() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.text.DateFormat.Field)
-
- DateFormat.Field[] objToSave = null;
- DateFormat.Field[] objLoaded = null;
-
- try {
- objToSave = new DateFormat.Field[] { DateFormat.Field.AM_PM,
- DateFormat.Field.DAY_OF_MONTH, DateFormat.Field.ERA,
- DateFormat.Field.HOUR0, DateFormat.Field.HOUR1,
- DateFormat.Field.HOUR_OF_DAY0,
- DateFormat.Field.HOUR_OF_DAY1, DateFormat.Field.TIME_ZONE,
- DateFormat.Field.YEAR,
- DateFormat.Field.DAY_OF_WEEK_IN_MONTH };
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
-
- objLoaded = (DateFormat.Field[]) dumpAndReload(objToSave);
-
- // Has to have worked
- // we need same instances for the same field names
- for (int i = 0; i < objToSave.length; i++) {
- assertTrue(MSG_TEST_FAILED + objToSave[i],
- objToSave[i] == objLoaded[i]);
- }
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_NumberFormat_Field() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.text.NumberFormat.Field)
-
- NumberFormat.Field[] objToSave = null;
- NumberFormat.Field[] objLoaded = null;
-
- try {
- objToSave = new NumberFormat.Field[] { NumberFormat.Field.CURRENCY,
- NumberFormat.Field.DECIMAL_SEPARATOR,
- NumberFormat.Field.EXPONENT,
- NumberFormat.Field.EXPONENT_SIGN,
- NumberFormat.Field.EXPONENT_SYMBOL,
- NumberFormat.Field.FRACTION,
- NumberFormat.Field.GROUPING_SEPARATOR,
- NumberFormat.Field.INTEGER, NumberFormat.Field.PERCENT,
- NumberFormat.Field.PERMILLE, NumberFormat.Field.SIGN };
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
-
- objLoaded = (NumberFormat.Field[]) dumpAndReload(objToSave);
-
- // Has to have worked
- // we need same instances for the same field names
- for (int i = 0; i < objToSave.length; i++) {
- assertTrue(MSG_TEST_FAILED + objToSave[i],
- objToSave[i] == objLoaded[i]);
- }
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_MessageFormat_Field() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.text.MessageFormat.Field)
-
- Object objToSave = null;
- Object objLoaded = null;
-
- try {
- objToSave = MessageFormat.Field.ARGUMENT;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
-
- objLoaded = dumpAndReload(objToSave);
-
- // Has to have worked
- // we need same instance for the same field name
- assertTrue(MSG_TEST_FAILED + objToSave, objToSave == objLoaded);
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_LinkedHashMap() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = LINKEDMAP;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, LINKEDMAP.equals(objLoaded));
-
- Map mapLoaded = (Map) objLoaded;
- Iterator loadedIterator = mapLoaded.keySet().iterator();
- Iterator iterator = LINKEDMAP.keySet().iterator();
- while (loadedIterator.hasNext()) {
- assertTrue("invalid iterator order", loadedIterator.next()
- .equals(iterator.next()));
- }
- assertTrue("invalid iterator size", !iterator.hasNext());
-
- loadedIterator = mapLoaded.entrySet().iterator();
- iterator = LINKEDMAP.entrySet().iterator();
- while (loadedIterator.hasNext()) {
- assertTrue("invalid entry set iterator order", loadedIterator
- .next().equals(iterator.next()));
- }
- assertTrue("invalid entry set iterator size", !iterator.hasNext());
-
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_LinkedHashSet() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- Object objToSave = null;
- Object objLoaded;
-
- try {
- objToSave = LINKEDSET;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = dumpAndReload(objToSave);
- // Has to have worked
- assertTrue(MSG_TEST_FAILED + objToSave, LINKEDSET.equals(objLoaded));
-
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!Serialization",
- args = {}
- )
- public void test_writeObject_IdentityHashMap() {
- // Test for method void
- // java.io.ObjectOutputStream.writeObject(java.lang.Object)
-
- IdentityHashMap objToSave = null;
- IdentityHashMap objLoaded;
-
- try {
- objToSave = IDENTITYMAP;
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- objLoaded = (IdentityHashMap) dumpAndReload(objToSave);
- // Has to have worked
-
- // a serialized identity hash map will not be equal to its original
- // because it is an "identity" mapping,
- // so we simply check for the usual meaning of equality
-
- assertEquals(
- "Loaded IdentityHashMap is not of the same size as the saved one.",
- objToSave.size(), objLoaded.size());
- HashMap duplicateSaved = new HashMap();
- duplicateSaved.putAll(objToSave);
- HashMap duplicateLoaded = new HashMap();
- duplicateLoaded.putAll(objLoaded);
- assertTrue(MSG_TEST_FAILED + duplicateSaved, duplicateSaved
- .equals(duplicateLoaded));
- } catch (IOException e) {
- fail("Exception serializing " + objToSave + " : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException reading Object type: "
- + e.getMessage());
- } catch (Error err) {
- System.out.println("Error when obj = " + objToSave);
- // err.printStackTrace();
- throw err;
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/SerializationStressTest5.java b/luni/src/test/java/tests/api/java/io/SerializationStressTest5.java
deleted file mode 100644
index 7b515d9..0000000
--- a/luni/src/test/java/tests/api/java/io/SerializationStressTest5.java
+++ /dev/null
@@ -1,390 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.util.Vector;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-
-@TestTargetClass(java.io.Serializable.class)
-public class SerializationStressTest5 extends SerializationStressTest {
-
- transient Throwable current;
-
- // Use this for retrieving a list of any Throwable Classes that did not get
- // tested.
- transient Vector missedV = new Vector();
-
- transient Class[][] params = new Class[][] { { String.class },
- { Throwable.class }, { Exception.class },
- { String.class, Exception.class }, { String.class, int.class },
- { String.class, String.class, String.class },
- { String.class, Error.class },
- { int.class, boolean.class, boolean.class, int.class, int.class },
- {} };
-
- transient Object[][] args = new Object[][] {
- { "message" },
- { new Throwable() },
- { new Exception("exception") },
- { "message", new Exception("exception") },
- { "message", new Integer(5) },
- { "message", "message", "message" },
- { "message", new Error("error") },
- { new Integer(5), new Boolean(false), new Boolean(false),
- new Integer(5), new Integer(5) }, {} };
-
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- notes = "",
- method = "!Serialization:test ThrowableClasses",
- args = {}
- )
- public void _test_writeObject_Throwables() {
- try {
- oos.close();
- } catch (IOException e) {
- }
-
- File javaDir = findJavaDir();
-
- Vector classFilesVector = new Vector();
- if (javaDir != null)
- findClassFiles(javaDir, classFilesVector);
- else
- findClassFilesFromZip(classFilesVector);
-
- if (classFilesVector.size() == 0) {
- fail("No Class Files Found.");
- }
-
- File[] classFilesArray = new File[classFilesVector.size()];
- classFilesVector.copyInto(classFilesArray);
-
- Class[] throwableClasses = findThrowableClasses(classFilesArray);
- findParam(throwableClasses);
-
- // Use this to print out the list of Throwable classes that weren't
- // tested.
- /*
- * System.out.println(); Class[] temp = new Class[missedV.size()];
- * missedV.copyInto(temp); for (int i = 0; i < temp.length; i++)
- * System.out.println(i+1 + ": " + temp[i].getName());
- */
- }
-
- private File[] makeClassPathArray() {
- String classPath;
- // if (System.getProperty("java.vendor").startsWith("IBM"))
- // classPath = System.getProperty("org.apache.harmony.boot.class.path");
- // else
- // classPath = System.getProperty("sun.boot.class.path");
- classPath = System.getProperty("java.boot.class.path");
- int instanceOfSep = -1;
- int nextInstance = classPath.indexOf(File.pathSeparatorChar,
- instanceOfSep + 1);
- Vector elms = new Vector();
- while (nextInstance != -1) {
- elms.add(new File(classPath.substring(instanceOfSep + 1,
- nextInstance)));
- instanceOfSep = nextInstance;
- nextInstance = classPath.indexOf(File.pathSeparatorChar,
- instanceOfSep + 1);
- }
- elms.add(new File(classPath.substring(instanceOfSep + 1)));
- File[] result = new File[elms.size()];
- elms.copyInto(result);
- return result;
- }
-
- private File findJavaDir() {
- File[] files = makeClassPathArray();
- for (int i = 0; i < files.length; i++) {
- if (files[i].isDirectory()) {
- String[] tempFileNames = files[i].list();
- for (int j = 0; j < tempFileNames.length; j++) {
- File tempfile = new File(files[i], tempFileNames[j]);
- if (tempfile.isDirectory()
- && tempFileNames[j].equals("java")) {
- String[] subdirNames = tempfile.list();
- for (int k = 0; k < subdirNames.length; k++) {
- File subdir = new File(tempfile, subdirNames[k]);
- if (subdir.isDirectory()
- && subdirNames[k].equals("lang")) {
- return tempfile;
- }
- }
- }
- }
- }
- }
- return null;
- }
-
- private void findClassFiles(File dir, Vector v) {
- String[] classFileNames = dir.list();
- for (int i = 0; i < classFileNames.length; i++) {
- File file = new File(dir, classFileNames[i]);
- if (file.isDirectory())
- findClassFiles(file, v);
- else if (classFileNames[i].endsWith(".class"))
- v.add(file);
- }
- }
-
- private Class[] findThrowableClasses(File[] files) {
- Class thrClass = Throwable.class;
- Vector resultVector = new Vector();
- String slash = System.getProperty("file.separator");
- String begTarget = slash + "java" + slash;
- String endTarget = ".class";
- for (int i = 0; i < files.length; i++) {
- String fileName = files[i].getPath();
- int instOfBegTarget = fileName.indexOf(begTarget);
- int instOfEndTarget = fileName.indexOf(endTarget);
- fileName = fileName.substring(instOfBegTarget + 1, instOfEndTarget);
- fileName = fileName.replace(slash.charAt(0), '.');
- try {
- Class theClass = Class.forName(fileName, false, ClassLoader
- .getSystemClassLoader());
- if (thrClass.isAssignableFrom(theClass)) {
- // java.lang.VirtualMachineError is abstract.
- // java.io.ObjectStreamException is abstract
- // java.beans.PropertyVetoException needs a
- // java.beans.PropertyChangeEvent as a parameter
- if (!fileName.equals("java.lang.VirtualMachineError")
- && !fileName
- .equals("java.io.ObjectStreamException")
- && !fileName
- .equals("java.beans.PropertyVetoException"))
- resultVector.add(theClass);
- }
- } catch (ClassNotFoundException e) {
- fail("ClassNotFoundException : " + fileName);
- }
- }
- Class[] result = new Class[resultVector.size()];
- resultVector.copyInto(result);
- return result;
- }
-
- private void initClass(Class thrC, int num) {
- Constructor[] cons = thrC.getConstructors();
- for (int i = 0; i < cons.length; i++) {
- try {
- Throwable obj = (Throwable) cons[i].newInstance(args[num]);
- t_Class(obj, num);
- break;
- } catch (IllegalArgumentException e) {
- // This error should be caught until the correct args is hit.
- } catch (IllegalAccessException e) {
- fail(
- "IllegalAccessException while creating instance of: "
- + thrC.getName());
- } catch (InstantiationException e) {
- fail(
- "InstantiationException while creating instance of: "
- + thrC.getName());
- } catch (InvocationTargetException e) {
- fail(
- "InvocationTargetException while creating instance of: "
- + thrC.getName());
- }
- if (i == cons.length - 1) {
- fail(
- "Failed to create newInstance of: " + thrC.getName());
- }
- }
- }
-
- public String getDumpName() {
- if (current == null) {
- dumpCount++;
- return getName();
- }
- return getName() + "_" + current.getClass().getName();
- }
-
- private void t_Class(Throwable objToSave, int argsNum) {
- current = objToSave;
- Object objLoaded = null;
- try {
- if (DEBUG)
- System.out.println("Obj = " + objToSave);
- try {
- objLoaded = dumpAndReload(objToSave);
- } catch (FileNotFoundException e) {
- // Must be using xload, ignore missing Throwables
- System.out.println("Ignoring: "
- + objToSave.getClass().getName());
- return;
- }
-
- // Has to have worked
- boolean equals;
- equals = objToSave.getClass().equals(objLoaded.getClass());
- assertTrue(MSG_TEST_FAILED + objToSave, equals);
- if (argsNum == 0 || (argsNum >= 3 && argsNum <= 7)) {
- equals = ((Throwable) objToSave).getMessage().equals(
- ((Throwable) objLoaded).getMessage());
- assertTrue("Message Test: " + MSG_TEST_FAILED + objToSave,
- equals);
- } else {
- // System.out.println(((Throwable)objToSave).getMessage());
- equals = ((Throwable) objToSave).getMessage() == null;
- assertTrue("Null Test 1: (args=" + argsNum + ") "
- + MSG_TEST_FAILED + objToSave, equals);
- equals = ((Throwable) objLoaded).getMessage() == null;
- assertTrue("Null Test 2: (args=" + argsNum + ") "
- + MSG_TEST_FAILED + objToSave, equals);
- }
- } catch (IOException e) {
- fail("Unexpected IOException in checkIt() : " + e.getMessage());
- } catch (ClassNotFoundException e) {
- fail(e.toString() + " - testing " + objToSave.getClass().getName());
- }
- }
-
- private void findParam(Class[] thrC) {
- for (int i = 0; i < thrC.length; i++) {
- Constructor con = null;
- for (int j = 0; j < params.length; j++) {
- try {
- con = thrC[i].getConstructor(params[j]);
- } catch (NoSuchMethodException e) {
- // This Error will be caught until the right param is found.
- }
-
- if (con != null) {
- // If the param was found, initialize the Class
- initClass(thrC[i], j);
- break;
- }
- // If the param not found then add to missed Vector.
- if (j == params.length - 1)
- missedV.add(thrC[i]);
- }
- }
- }
-
- private void findClassFilesFromZip(Vector v) {
- String slash = System.getProperty("file.separator");
- String javaHome = System.getProperty("java.home");
- if (!javaHome.endsWith(slash))
- javaHome += slash;
-
- String[] wanted = { "java" + slash + "io", "java" + slash + "lang",
- "java" + slash + "math", "java" + slash + "net",
- "java" + slash + "security", "java" + slash + "text",
- "java" + slash + "util", "java" + slash + "beans",
- "java" + slash + "rmi",
- // One or more class files in awt make the VM hang after being
- // loaded.
- // "java" + slash + "awt",
- "java" + slash + "sql",
- // These are (possibly) all of the throwable classes in awt
- /*
- * "java\\awt\\AWTError", "java\\awt\\AWTException",
- * "java\\awt\\color\\CMMException",
- * "java\\awt\\color\\ProfileDataException",
- * "java\\awt\\datatransfer\\MimeTypeParseException",
- * "java\\awt\\datatransfer\\UnsupportedFlavorException",
- * "java\\awt\\dnd\\InvalidDnDOperationException",
- * "java\\awt\\FontFormatException",
- * "java\\awt\\geom\\IllegalPathStateException",
- * "java\\awt\\geom\\NoninvertibleTransformException",
- * "java\\awt\\IllegalComponentStateException",
- * "java\\awt\\image\\ImagingOpException",
- * "java\\awt\\image\\RasterFormatException",
- * "java\\awt\\print\\PrinterAbortException",
- * "java\\awt\\print\\PrinterException",
- * "java\\awt\\print\\PrinterIOException"
- */
- };
-
- File[] files = makeClassPathArray();
- FileInputStream fis = null;
- ZipInputStream zis = null;
- ZipEntry ze = null;
- for (int i = 0; i < files.length; i++) {
- String fileName = files[i].getPath();
- if (files[i].exists() && files[i].isFile()
- && fileName.endsWith(".jar") || fileName.endsWith(".zip")) {
- try {
- fis = new FileInputStream(files[i].getPath());
- } catch (FileNotFoundException e) {
- fail("FileNotFoundException trying to open "
- + files[i].getPath());
- }
- zis = new ZipInputStream(fis);
- while (true) {
- try {
- ze = zis.getNextEntry();
- } catch (IOException e) {
- fail("IOException while getting next zip entry: "
- + e);
- }
- if (ze == null)
- break;
- String zeName = ze.getName();
- if (zeName.endsWith(".class")) {
- zeName = zeName.replace('/', slash.charAt(0));
- for (int j = 0; j < wanted.length; j++) {
- if (zeName.startsWith(wanted[j])) {
- // When finding class files from directories the
- // program saves them as files.
- // To stay consistent we will turn the ZipEntry
- // classes into instances of files.
- File tempF = new File(javaHome + zeName);
- // Making sure that the same class is not added
- // twice.
- boolean duplicate = false;
- for (int k = 0; k < v.size(); k++) {
- if (v.get(k).equals(tempF))
- duplicate = true;
- }
- if (!duplicate)
- v.add(tempF);
- break;
- }
- }
- }
- }
- ;
- try {
- zis.close();
- fis.close();
- } catch (IOException e) {
- fail(
- "IOException while trying to close InputStreams: "
- + e);
- }
- }
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/SerializationTestClass.java b/luni/src/test/java/tests/api/java/io/SerializationTestClass.java
deleted file mode 100644
index 32c4d0b..0000000
--- a/luni/src/test/java/tests/api/java/io/SerializationTestClass.java
+++ /dev/null
@@ -1,335 +0,0 @@
-package tests.api.java.io;
-
-public class SerializationTestClass implements java.io.Serializable {
-
- // Test class names
- public class TestClassName1 implements java.io.Serializable {
- }
-
- public class TestClassName2T_T$T implements java.io.Serializable {
- }
-
- // Test Modifiers
- public class TestClassModifierPublic implements java.io.Serializable {
- }
-
- interface TestClassModifierInterfaceHelper extends java.io.Serializable {
- }
-
- public class TestClassModifierInterface implements
- TestClassModifierInterfaceHelper {
- }
-
- final class TestClassModifierFinal implements java.io.Serializable {
- }
-
- abstract class TestClassModifierAbstractHelper implements
- java.io.Serializable {
- }
-
- public class TestClassModifierAbstract extends
- TestClassModifierAbstractHelper {
- }
-
-
- // TODO Arrays always are abstract
-
- // TODO Non public interface has no abstract modifier
-
-
- // Test interfaces
- interface A extends java.io.Serializable {
- }
-
- interface B extends java.io.Serializable {
- }
-
- interface C extends A {
- }
-
- public class TestIntefaces implements java.io.Serializable {
- }
-
- public class TestIntefacesA implements A {
- }
-
- public class TestIntefacesAB implements A, B {
- }
-
- public class TestIntefacesBA implements B, A {
- }
-
- public class TestIntefacesC implements C {
- }
-
- public class TestIntefacesAC implements A, C {
- }
-
- public class TestIntefacesCA implements C, A {
- }
-
- public class TestIntefacesABC implements A, B, C {
- }
-
- public class TestIntefacesACB implements A, C, B {
- }
-
- public class TestIntefacesBAC implements B, A, C {
- }
-
- public class TestIntefacesBCA implements B, C, A {
- }
-
- public class TestIntefacesCAB implements C, A, B {
- }
-
- public class TestIntefacesCBA implements C, B, A {
- }
-
- /**
- * Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED | Modifier.STATIC |
- * Modifier.FINAL | Modifier.VOLATILE | Modifier.TRANSIENT
- */
- // Test Fields
- public class TestFieldsNone implements java.io.Serializable {
- }
-
- public class TestFieldsOnePublic implements java.io.Serializable {
- public int one;
- }
-
- public class TestFieldsTwoPublic implements java.io.Serializable {
- public int one;
- public int two;
- }
-
- @SuppressWarnings("unused")
- public class TestFieldsOnePrivate implements java.io.Serializable {
- private int one;
- }
-
- @SuppressWarnings("unused")
- public class TestFieldsTwoPrivate implements java.io.Serializable {
- private int one;
- private int two;
- }
-
- public class TestFieldsOneProtected implements java.io.Serializable {
- protected int one;
- }
-
- public class TestFieldsTwoProtected implements java.io.Serializable {
- protected int one;
- protected int two;
- }
-
- public static class TestFieldsOneStatic implements java.io.Serializable {
- static int one;
- }
-
- public static class TestFieldsTwoStatic implements java.io.Serializable {
- static int one;
- static int two;
- }
-
- public class TestFieldsOneFinal implements java.io.Serializable {
- final int one = 0;
- }
-
- public class TestFieldsTwoFinal implements java.io.Serializable {
- final int one = 0;
- final int two = 0;
- }
-
- public class TestFieldsOneVolatile implements java.io.Serializable {
- volatile int one;
- }
-
- public class TestFieldsTwoVolatile implements java.io.Serializable {
- volatile int one;
- volatile int two;
- }
-
- public class TestFieldsOneTransient implements java.io.Serializable {
- transient int one;
- }
-
- public class TestFieldsTwoTransient implements java.io.Serializable {
- transient int one;
- transient int two;
- }
-
- public class TestFieldSignatures implements java.io.Serializable {
- Object l;
- int i;
- short s;
- long j;
- boolean z;
- char c;
- double d;
- float f;
- byte b;
- }
-
-
- // Test Constructors
- public class TestConstructorNone implements java.io.Serializable {
- }
-
- public class TestConstructorOne implements java.io.Serializable {
- public TestConstructorOne() {
- }
- }
-
- public class TestConstructorTwo implements java.io.Serializable {
- public TestConstructorTwo(byte b) {
- }
-
- public TestConstructorTwo(char c) {
- }
- }
-
- public class TestConstructorTwoReverse implements java.io.Serializable {
- public TestConstructorTwoReverse(char c) {
- }
-
- public TestConstructorTwoReverse(byte b) {
- }
- }
-
-
- // Test Constructor Modifiers
- public class TestConstructorPublic implements java.io.Serializable {
- public TestConstructorPublic() {
- }
- }
-
- public class TestConstructorPrivate implements java.io.Serializable {
- private TestConstructorPrivate() {
- }
-
- public TestConstructorPrivate(int i) {
- this();
- }
- }
-
- public class TestConstructorProtected implements java.io.Serializable {
- protected TestConstructorProtected() {
- }
- }
- // TODO constructor modifier strict?
- // TODO constructor modifier static?
- // TODO constructor modifier final?
- // TODO constructor modifier synchronized?
- // TODO constructor modifier native?
- // TODO constructor modifier abstract?
-
-
- // Test constructor signature
- public class TestConstructorSignature implements java.io.Serializable {
- public TestConstructorSignature(boolean z, byte b, char c, short s,
- int i, float f, double j, Object l) {
- }
- }
-
-
- // Test Method Modifiers
- public class TestMethodPublic implements java.io.Serializable {
- public void method() {
- }
- }
-
- @SuppressWarnings("unused")
- public class TestMehodPrivate implements java.io.Serializable {
- private void method() {
- }
- }
-
- public class TestMethodProtected implements java.io.Serializable {
- protected void method() {
- }
- }
-
- public class TestMethodStrict implements java.io.Serializable {
- strictfp void method() {
- }
- }
-
- public static class TestMethodStatic implements java.io.Serializable {
- static void method() {
- }
- }
-
- public class TestMethodFinal implements java.io.Serializable {
- final void method() {
- }
- }
-
- public class TestMethodSynchronized implements java.io.Serializable {
- synchronized void method() {
- }
- }
-
- public class TestMethodNative implements java.io.Serializable {
- native void method();
- }
-
- public abstract class TestMethodAbstractHelper implements
- java.io.Serializable {
- abstract void method();
- }
-
- public class TestMethodAbstract extends TestMethodAbstractHelper implements
- java.io.Serializable {
- @Override
- void method() {
- }
- }
-
-
- // Test method signature
- public class TestMethodSignature implements java.io.Serializable {
- public void method(boolean z, byte b, char c, short s, int i, float f,
- double j, Object l) {
- }
- }
-
-
- // Test method return signature
- public class TestMethodReturnSignature implements java.io.Serializable {
- public void methodV() {
- }
-
- public boolean methodZ() {
- return false;
- }
-
- public byte methodB() {
- return 0;
- }
-
- public char methodC() {
- return '0';
- }
-
- public short methodS() {
- return 0;
- }
-
- public int methodI() {
- return 0;
- }
-
- public float methodF() {
- return 0F;
- }
-
- public double methodD() {
- return 0D;
- }
-
- public Object methodL() {
- return null;
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/StreamCorruptedExceptionTest.java b/luni/src/test/java/tests/api/java/io/StreamCorruptedExceptionTest.java
deleted file mode 100644
index f53129d..0000000
--- a/luni/src/test/java/tests/api/java/io/StreamCorruptedExceptionTest.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.StreamCorruptedException;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(StreamCorruptedException.class)
-public class StreamCorruptedExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.io.StreamCorruptedException#StreamCorruptedException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "StreamCorruptedException",
- args = {}
- )
- public void test_Constructor() {
- try {
- if (true) // To avoid unreachable code compilation error.
- throw new StreamCorruptedException();
- fail("Test 1: StreamCorruptedException expected.");
- } catch (StreamCorruptedException e) {
- assertNull("Test 2: Null expected for exceptions constructed without a message.",
- e.getMessage());
- }
- }
-
- /**
- * @tests java.io.StreamCorruptedException#StreamCorruptedException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "StreamCorruptedException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- try {
- if (true) // To avoid unreachable code compilation error.
- throw new StreamCorruptedException("Something went wrong.");
- fail("Test 1: StreamCorruptedException expected.");
- } catch (StreamCorruptedException e) {
- assertEquals("Test 2: Incorrect message;",
- "Something went wrong.", e.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/StreamTokenizerTest.java b/luni/src/test/java/tests/api/java/io/StreamTokenizerTest.java
deleted file mode 100644
index c480ca6..0000000
--- a/luni/src/test/java/tests/api/java/io/StreamTokenizerTest.java
+++ /dev/null
@@ -1,757 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.ByteArrayInputStream;
-import java.io.CharArrayReader;
-import java.io.IOException;
-import java.io.PipedInputStream;
-import java.io.PipedOutputStream;
-import java.io.Reader;
-import java.io.StreamTokenizer;
-import java.io.StringBufferInputStream;
-import java.io.StringReader;
-
-import junit.framework.Assert;
-import tests.support.Support_StringReader;
-import tests.support.Support_ASimpleInputStream;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-// TODO: most of the assertTrue calls in this test case should be
-// replaced with assertEquals (possibly two assertEquals) see
-// test_ConstructorLjava_io_InputStream for example.
-// This gives much more helpful error messages.
-
-@TestTargetClass(StreamTokenizer.class)
-public class StreamTokenizerTest extends junit.framework.TestCase {
- Support_StringReader r;
-
- StreamTokenizer st;
-
- String testString;
-
- /**
- * @tests java.io.StreamTokenizer#StreamTokenizer(java.io.InputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StreamTokenizer",
- args = {java.io.InputStream.class}
- )
- public void test_ConstructorLjava_io_InputStream() throws IOException {
- st = new StreamTokenizer(new StringBufferInputStream(
- "/comments\n d 8 'h'"));
-
- assertEquals("the next token returned should be the letter d",
- StreamTokenizer.TT_WORD, st.nextToken());
- assertEquals("the next token returned should be the letter d",
- "d", st.sval);
-
- assertEquals("the next token returned should be the digit 8",
- StreamTokenizer.TT_NUMBER, st.nextToken());
- assertEquals("the next token returned should be the digit 8",
- 8.0, st.nval);
-
- assertEquals("the next token returned should be the quote character",
- 39, st.nextToken());
- assertEquals("the next token returned should be the quote character",
- "h", st.sval);
- }
-
- /**
- * @tests java.io.StreamTokenizer#StreamTokenizer(java.io.Reader)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StreamTokenizer",
- args = {java.io.Reader.class}
- )
- public void test_ConstructorLjava_io_Reader() throws IOException {
- setTest("/testing\n d 8 'h' ");
- assertEquals("the next token returned should be the letter d skipping the comments",
- StreamTokenizer.TT_WORD, st.nextToken());
- assertEquals("the next token returned should be the letter d",
- "d", st.sval);
-
- assertEquals("the next token returned should be the digit 8",
- StreamTokenizer.TT_NUMBER, st.nextToken());
- assertEquals("the next token returned should be the digit 8",
- 8.0, st.nval);
-
- assertEquals("the next token returned should be the quote character",
- 39, st.nextToken());
- assertEquals("the next token returned should be the quote character",
- "h", st.sval);
- }
-
- /**
- * @tests java.io.StreamTokenizer#commentChar(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "commentChar",
- args = {int.class}
- )
- public void test_commentCharI() throws IOException {
- setTest("*comment \n / 8 'h' ");
- st.ordinaryChar('/');
- st.commentChar('*');
- assertEquals("nextToken() did not return the character / skiping the comments starting with *",
- 47, st.nextToken());
- assertTrue("the next token returned should be the digit 8", st
- .nextToken() == StreamTokenizer.TT_NUMBER
- && st.nval == 8.0);
- assertTrue("the next token returned should be the quote character",
- st.nextToken() == 39 && st.sval.equals("h"));
- }
-
- /**
- * @tests java.io.StreamTokenizer#eolIsSignificant(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "eolIsSignificant",
- args = {boolean.class}
- )
- public void test_eolIsSignificantZ() throws IOException {
- setTest("d 8\n");
- // by default end of line characters are not significant
- assertTrue("nextToken did not return d",
- st.nextToken() == StreamTokenizer.TT_WORD
- && st.sval.equals("d"));
- assertTrue("nextToken did not return 8",
- st.nextToken() == StreamTokenizer.TT_NUMBER
- && st.nval == 8.0);
- assertTrue("nextToken should be the end of file",
- st.nextToken() == StreamTokenizer.TT_EOF);
- setTest("d\n");
- st.eolIsSignificant(true);
- // end of line characters are significant
- assertTrue("nextToken did not return d",
- st.nextToken() == StreamTokenizer.TT_WORD
- && st.sval.equals("d"));
- assertTrue("nextToken is the end of line",
- st.nextToken() == StreamTokenizer.TT_EOL);
- }
-
- /**
- * @tests java.io.StreamTokenizer#lineno()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lineno",
- args = {}
- )
- public void test_lineno() throws IOException {
- setTest("d\n 8\n");
- assertEquals("the lineno should be 1", 1, st.lineno());
- st.nextToken();
- st.nextToken();
- assertEquals("the lineno should be 2", 2, st.lineno());
- st.nextToken();
- assertEquals("the next line no should be 3", 3, st.lineno());
- }
-
- /**
- * @tests java.io.StreamTokenizer#lowerCaseMode(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lowerCaseMode",
- args = {boolean.class}
- )
- public void test_lowerCaseModeZ() throws Exception {
- // SM.
- setTest("HELLOWORLD");
- st.lowerCaseMode(true);
-
- st.nextToken();
- assertEquals("sval not converted to lowercase.", "helloworld", st.sval
- );
- }
-
- /**
- * @tests java.io.StreamTokenizer#nextToken()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- method = "nextToken",
- args = {}
- )
- public void test_nextToken() throws IOException {
- setTest("\r\n/* fje fje 43.4 f \r\n f g */ 456.459 \r\n"
- + "Hello / \r\n \r\n \n \r \257 Hi \'Hello World\'");
- st.ordinaryChar('/');
- st.slashStarComments(true);
- st.nextToken();
- assertTrue("Wrong Token type1: " + (char) st.ttype,
- st.ttype == StreamTokenizer.TT_NUMBER);
- st.nextToken();
- assertTrue("Wrong Token type2: " + st.ttype,
- st.ttype == StreamTokenizer.TT_WORD);
- st.nextToken();
- assertTrue("Wrong Token type3: " + st.ttype, st.ttype == '/');
- st.nextToken();
- assertTrue("Wrong Token type4: " + st.ttype,
- st.ttype == StreamTokenizer.TT_WORD);
- st.nextToken();
- assertTrue("Wrong Token type5: " + st.ttype,
- st.ttype == StreamTokenizer.TT_WORD);
- st.nextToken();
- assertTrue("Wrong Token type6: " + st.ttype, st.ttype == '\'');
- assertTrue("Wrong Token type7: " + st.ttype, st.sval
- .equals("Hello World"));
- st.nextToken();
- assertTrue("Wrong Token type8: " + st.ttype, st.ttype == -1);
-
- final PipedInputStream pin = new PipedInputStream();
- PipedOutputStream pout = new PipedOutputStream(pin);
- pout.write("hello\n\r\r".getBytes());
- st = new StreamTokenizer(pin);
- st.eolIsSignificant(true);
- assertTrue("Wrong token 1,1",
- st.nextToken() == StreamTokenizer.TT_WORD
- && st.sval.equals("hello"));
- assertTrue("Wrong token 1,2", st.nextToken() == '\n');
- assertTrue("Wrong token 1,3", st.nextToken() == '\n');
- assertTrue("Wrong token 1,4", st.nextToken() == '\n');
- pout.close();
- assertTrue("Wrong token 1,5",
- st.nextToken() == StreamTokenizer.TT_EOF);
-
- st = new StreamTokenizer(new Support_StringReader("\n \r\n#"));
- st.ordinaryChar('\n'); // make \n ordinary
- st.eolIsSignificant(true);
- assertTrue("Wrong token 2,1", st.nextToken() == '\n');
- assertTrue("Wrong token 2,2", st.nextToken() == '\n');
- assertEquals("Wrong token 2,3", '#', st.nextToken());
-
- Support_ASimpleInputStream sis = new Support_ASimpleInputStream();
- sis.throwExceptionOnNextUse = true;
- st = new StreamTokenizer(sis);
- try {
- st.nextToken();
- fail("IOException expected.");
- } catch (IOException e) {
- // Expected.
- }
- }
-
- /**
- * @tests java.io.StreamTokenizer#ordinaryChar(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ordinaryChar",
- args = {int.class}
- )
- public void test_ordinaryCharI() throws IOException {
- // SM.
- setTest("Ffjein 893");
- st.ordinaryChar('F');
- st.nextToken();
- assertTrue("OrdinaryChar failed." + (char) st.ttype,
- st.ttype == 'F');
- }
-
- /**
- * @tests java.io.StreamTokenizer#ordinaryChars(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ordinaryChars",
- args = {int.class, int.class}
- )
- public void test_ordinaryCharsII() throws IOException {
- // SM.
- setTest("azbc iof z 893");
- st.ordinaryChars('a', 'z');
- assertEquals("OrdinaryChars failed.", 'a', st.nextToken());
- assertEquals("OrdinaryChars failed.", 'z', st.nextToken());
- }
-
- /**
- * @tests java.io.StreamTokenizer#parseNumbers()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "parseNumbers",
- args = {}
- )
- public void test_parseNumbers() throws IOException {
- // SM
- setTest("9.9 678");
- assertTrue("Base behavior failed.",
- st.nextToken() == StreamTokenizer.TT_NUMBER);
- st.ordinaryChars('0', '9');
- assertEquals("setOrdinary failed.", '6', st.nextToken());
- st.parseNumbers();
- assertTrue("parseNumbers failed.",
- st.nextToken() == StreamTokenizer.TT_NUMBER);
- }
-
- /**
- * @tests java.io.StreamTokenizer#pushBack()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "pushBack",
- args = {}
- )
- public void test_pushBack() throws IOException {
- // SM.
- setTest("Hello 897");
- st.nextToken();
- st.pushBack();
- assertTrue("PushBack failed.",
- st.nextToken() == StreamTokenizer.TT_WORD);
- }
-
- /**
- * @tests java.io.StreamTokenizer#quoteChar(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "quoteChar",
- args = {int.class}
- )
- public void test_quoteCharI() throws IOException {
- // SM
- setTest("<Hello World< HelloWorldH");
- st.quoteChar('<');
- assertEquals("QuoteChar failed.", '<', st.nextToken());
- assertEquals("QuoteChar failed.", "Hello World", st.sval);
- st.quoteChar('H');
- st.nextToken();
- assertEquals("QuoteChar failed for word.", "elloWorld", st.sval
- );
- }
-
- /**
- * @tests java.io.StreamTokenizer#resetSyntax()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "resetSyntax",
- args = {}
- )
- public void test_resetSyntax() throws IOException {
- // SM
- setTest("H 9\' ello World");
- st.resetSyntax();
- assertTrue("resetSyntax failed1." + (char) st.ttype,
- st.nextToken() == 'H');
- assertTrue("resetSyntax failed1." + (char) st.ttype,
- st.nextToken() == ' ');
- assertTrue("resetSyntax failed2." + (char) st.ttype,
- st.nextToken() == '9');
- assertTrue("resetSyntax failed3." + (char) st.ttype,
- st.nextToken() == '\'');
- }
-
- /**
- * @tests java.io.StreamTokenizer#slashSlashComments(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "slashSlashComments",
- args = {boolean.class}
- )
- public void test_slashSlashCommentsZ() throws IOException {
- // SM.
- setTest("// foo \r\n /fiji \r\n -456");
- st.ordinaryChar('/');
- st.slashSlashComments(true);
- assertEquals("Test failed.", '/', st.nextToken());
- assertTrue("Test failed.",
- st.nextToken() == StreamTokenizer.TT_WORD);
- }
-
- /**
- * @tests java.io.StreamTokenizer#slashSlashComments(boolean)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "slashSlashComments",
- args = {boolean.class}
- )
- public void test_slashSlashComments_withSSOpen() throws IOException {
- Reader reader = new CharArrayReader( "t // t t t".toCharArray());
-
- StreamTokenizer st = new StreamTokenizer(reader);
- st.slashSlashComments(true);
-
- assertEquals(StreamTokenizer.TT_WORD,st.nextToken());
- assertEquals(StreamTokenizer.TT_EOF,st.nextToken());
- }
-
- /**
- * @tests java.io.StreamTokenizer#slashSlashComments(boolean)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "slashSlashComments",
- args = {boolean.class}
- )
- public void test_slashSlashComments_withSSOpen_NoComment() throws IOException {
- Reader reader = new CharArrayReader( "// t".toCharArray());
-
- StreamTokenizer st = new StreamTokenizer(reader);
- st.slashSlashComments(true);
- st.ordinaryChar('/');
-
- assertEquals(StreamTokenizer.TT_EOF,st.nextToken());
- }
-
- /**
- * @tests java.io.StreamTokenizer#slashSlashComments(boolean)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "slashSlashComments",
- args = {boolean.class}
- )
- public void test_slashSlashComments_withSSClosed() throws IOException {
- Reader reader = new CharArrayReader( "// t".toCharArray());
-
- StreamTokenizer st = new StreamTokenizer(reader);
- st.slashSlashComments(false);
- st.ordinaryChar('/');
-
- assertEquals('/',st.nextToken());
- assertEquals('/',st.nextToken());
- assertEquals(StreamTokenizer.TT_WORD,st.nextToken());
- }
-
- /**
- * @tests java.io.StreamTokenizer#slashStarComments(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "slashStarComments",
- args = {boolean.class}
- )
- public void test_slashStarCommentsZ() throws IOException {
- setTest("/* foo \r\n /fiji \r\n*/ -456");
- st.ordinaryChar('/');
- st.slashStarComments(true);
- assertTrue("Test failed.",
- st.nextToken() == StreamTokenizer.TT_NUMBER);
- }
-
- /**
- * @tests java.io.StreamTokenizer#slashStarComments(boolean)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "slashStarComments",
- args = {boolean.class}
- )
- public void test_slashStarComments_withSTOpen() throws IOException {
- Reader reader = new CharArrayReader( "t /* t */ t".toCharArray());
-
- StreamTokenizer st = new StreamTokenizer(reader);
- st.slashStarComments(true);
-
- assertEquals(StreamTokenizer.TT_WORD,st.nextToken());
- assertEquals(StreamTokenizer.TT_WORD,st.nextToken());
- assertEquals(StreamTokenizer.TT_EOF,st.nextToken());
- }
-
- /**
- * @tests java.io.StreamTokenizer#slashStarComments(boolean)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "slashStarComments",
- args = {boolean.class}
- )
- public void test_slashStarComments_withSTClosed() throws IOException {
- Reader reader = new CharArrayReader( "t /* t */ t".toCharArray());
-
- StreamTokenizer st = new StreamTokenizer(reader);
- st.slashStarComments(false);
-
- assertEquals(StreamTokenizer.TT_WORD,st.nextToken());
- assertEquals(StreamTokenizer.TT_EOF,st.nextToken());
- }
-
- /**
- * @tests java.io.StreamTokenizer#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() throws IOException {
- setTest("ABC Hello World");
- st.nextToken();
- assertTrue("toString failed." + st.toString(),
- st.toString().equals(
- "Token[ABC], line 1"));
- }
-
- /**
- * @tests java.io.StreamTokenizer#whitespaceChars(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "whitespaceChars",
- args = {int.class, int.class}
- )
- public void test_whitespaceCharsII() throws IOException {
- setTest("azbc iof z 893");
- st.whitespaceChars('a', 'z');
- assertTrue("OrdinaryChar failed.",
- st.nextToken() == StreamTokenizer.TT_NUMBER);
- }
-
- /**
- * @tests java.io.StreamTokenizer#wordChars(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "wordChars",
- args = {int.class, int.class}
- )
- public void test_wordCharsII() throws IOException {
- setTest("A893 -9B87");
- st.wordChars('0', '9');
- assertTrue("WordChar failed1.",
- st.nextToken() == StreamTokenizer.TT_WORD);
- assertEquals("WordChar failed2.", "A893", st.sval);
- assertTrue("WordChar failed3.",
- st.nextToken() == StreamTokenizer.TT_NUMBER);
- st.nextToken();
- assertEquals("WordChar failed4.", "B87", st.sval);
-
- setTest(" Hello World");
- st.wordChars(' ', ' ');
- st.nextToken();
- assertEquals("WordChars failed for whitespace.", "Hello World", st.sval
- );
-
- setTest(" Hello World\r\n \'Hello World\' Hello\' World");
- st.wordChars(' ', ' ');
- st.wordChars('\'', '\'');
- st.nextToken();
- assertTrue("WordChars failed for whitespace: " + st.sval, st.sval
- .equals("Hello World"));
- st.nextToken();
- assertTrue("WordChars failed for quote1: " + st.sval, st.sval
- .equals("\'Hello World\' Hello\' World"));
- }
-
- private void setTest(String s) {
- testString = s;
- r = new Support_StringReader(testString);
- st = new StreamTokenizer(r);
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "General functionality of these methods tested in separate tests.",
- method = "lineno",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "General functionality of these methods tested in separate tests.",
- method = "nextToken",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "General functionality of these methods tested in separate tests.",
- method = "toString",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "General functionality of these methods tested in separate tests.",
- method = "commentChar",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "General functionality of these methods tested in separate tests.",
- method = "eolIsSignificant",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "General functionality of these methods tested in separate tests.",
- method = "lowerCaseMode",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "General functionality of these methods tested in separate tests.",
- method = "ordinaryChar",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "General functionality of these methods tested in separate tests.",
- method = "slashStarComments",
- args = {boolean.class}
- )
- })
- public void test_basicStringTokenizerMethods()
- {
- String str = "Testing 12345 \n alpha \r\n omega";
- String strb = "-3.8 'BLIND mice' \r sEe /* how */ they run";
- StringReader aa = new StringReader(str);
- StringReader ba = new StringReader(strb);
- StreamTokenizer a = new StreamTokenizer(aa);
- StreamTokenizer b = new StreamTokenizer(ba);
-
- try {
- Assert.assertTrue(a.lineno() == 1);
- Assert.assertTrue(a.nextToken() == StreamTokenizer.TT_WORD);
- Assert.assertTrue(a.toString().equals("Token[Testing], line 1"));
- Assert.assertTrue(a.nextToken() == StreamTokenizer.TT_NUMBER);
- Assert.assertTrue(a.toString().equals("Token[n=12345.0], line 1"));
- Assert.assertTrue(a.nextToken() == StreamTokenizer.TT_WORD);
- Assert.assertTrue(a.toString().equals("Token[alpha], line 2"));
- Assert.assertTrue(a.nextToken() == StreamTokenizer.TT_WORD);
- Assert.assertTrue(a.toString().equals("Token[omega], line 3"));
- Assert.assertTrue(a.nextToken() == StreamTokenizer.TT_EOF);
- Assert.assertTrue(a.toString().equals("Token[EOF], line 3"));
-
- b.commentChar('u');
- b.eolIsSignificant(true);
- b.lowerCaseMode(true);
- b.ordinaryChar('y');
- b.slashStarComments(true);
-
- Assert.assertTrue(b.nextToken() == StreamTokenizer.TT_NUMBER);
- Assert.assertTrue(b.nval == -3.8);
- Assert.assertTrue(b.toString().equals("Token[n=-3.8], line 1"));
- Assert.assertTrue(b.nextToken() == 39); // '
- Assert.assertTrue(b.toString().equals("Token[BLIND mice], line 1"));
- Assert.assertTrue(b.nextToken() == 10); // \n
- Assert.assertTrue(b.toString().equals("Token[EOL], line 2"));
- Assert.assertTrue(b.nextToken() == StreamTokenizer.TT_WORD);
- Assert.assertTrue(b.toString().equals("Token[see], line 2"));
- Assert.assertTrue(b.nextToken() == StreamTokenizer.TT_WORD);
- Assert.assertTrue(b.toString().equals("Token[the], line 2"));
- Assert.assertTrue(b.nextToken() == 121); // y
- Assert.assertTrue(b.toString().equals("Token['y'], line 2"));
- Assert.assertTrue(b.nextToken() == StreamTokenizer.TT_WORD);
- Assert.assertTrue(b.toString().equals("Token[r], line 2"));
- Assert.assertTrue(b.nextToken() == StreamTokenizer.TT_EOF);
- Assert.assertTrue(b.toString().equals("Token[EOF], line 2"));
- }
- catch (Exception ex){
- System.out.println("Exception found in StreamTokenizer");
- ex.printStackTrace();
- throw new RuntimeException("error in test, see stdout");
- }
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "nextToken",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "toString",
- args = {}
- )
- })
- public void test_harmonyRegressionTest() {
- byte[] data = new byte[] {(byte) '-'};
- StreamTokenizer tokenizer = new StreamTokenizer(new ByteArrayInputStream(data));
- try {
- tokenizer.nextToken();
- } catch(Exception e) {
- Assert.fail(e.getMessage());
- }
- String result = tokenizer.toString();
- Assert.assertEquals("Token['-'], line 1", result);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "nextToken",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "toString",
- args = {}
- )
- })
- public void test_harmonyRegressionTest2() {
- byte[] data = new byte[] {(byte) '"',
- (byte) 'H',
- (byte) 'e',
- (byte) 'l',
- (byte) 'l',
- (byte) 'o',
- (byte) '"'};
- StreamTokenizer tokenizer = new StreamTokenizer(new ByteArrayInputStream(data));
- try {
- tokenizer.nextToken();
- } catch (Exception e) {
- e.printStackTrace();
- }
- String result = tokenizer.toString();
- Assert.assertEquals("Token[Hello], line 1", result);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/StringBufferInputStreamTest.java b/luni/src/test/java/tests/api/java/io/StringBufferInputStreamTest.java
deleted file mode 100644
index bf6b11a..0000000
--- a/luni/src/test/java/tests/api/java/io/StringBufferInputStreamTest.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-
-import java.io.StringBufferInputStream;
-
-@TestTargetClass(StringBufferInputStream.class)
-public class StringBufferInputStreamTest extends junit.framework.TestCase {
-
- StringBufferInputStream sbis;
-
- /**
- * @tests java.io.StringBufferInputStream#StringBufferInputStream(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StringBufferInputStream",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- try {
- new StringBufferInputStream("");
- } catch (Exception ee) {
- fail("Exception " + ee.getMessage() + " does not expected in this case");
- }
- // Test for method java.io.StringBufferInputStream(java.lang.String)
- }
-
- /**
- * @tests java.io.StringBufferInputStream#available()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "available",
- args = {}
- )
- public void test_available() {
- // Test for method int java.io.StringBufferInputStream.available()
- assertEquals("Returned incorrect number of available bytes", 11, sbis
- .available());
- }
-
- /**
- * @tests java.io.StringBufferInputStream#read()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII() {
- // Test for method int java.io.StringBufferInputStream.read()
- byte[] buf = new byte[5];
- sbis.skip(6);
- sbis.read(buf, 0, 5);
- assertEquals("Returned incorrect chars", "World", new String(buf));
- }
-
- /**
- * @tests java.io.StringBufferInputStream#read()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
- public void test_read$BII_Exception() {
- // Test for method int java.io.StringBufferInputStream.read()
- byte[] buf = new byte[10];
- try {
- sbis.read(buf, 0, -1);
- fail("IndexOutOfBoundsException was not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- sbis.read(buf, -1, 1);
- fail("IndexOutOfBoundsException was not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- sbis.read(buf, 10, 1);
- fail("IndexOutOfBoundsException was not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.io.StringBufferInputStream#read(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "read",
- args = {}
- )
- public void test_read() {
- // Test for method int java.io.StringBufferInputStream.read(byte [],
- // int, int)
- assertEquals("Read returned incorrect char", 'H', sbis.read());
- }
-
- /**
- * @tests java.io.StringBufferInputStream#reset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reset",
- args = {}
- )
- public void test_reset() {
- // Test for method void java.io.StringBufferInputStream.reset()
- long s = sbis.skip(6);
- assertEquals("Unable to skip correct umber of chars", 6, s);
- sbis.reset();
- assertEquals("Failed to reset", 'H', sbis.read());
- }
-
- /**
- * @tests java.io.StringBufferInputStream#skip(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "skip",
- args = {long.class}
- )
- public void test_skipJ() {
- // Test for method long java.io.StringBufferInputStream.skip(long)
- long s = sbis.skip(6);
- assertEquals("Unable to skip correct umber of chars", 6, s);
- assertEquals("Skip positioned at incorrect char", 'W', sbis.read());
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- sbis = new StringBufferInputStream("Hello World");
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/StringReaderTest.java b/luni/src/test/java/tests/api/java/io/StringReaderTest.java
deleted file mode 100644
index b0fa469..0000000
--- a/luni/src/test/java/tests/api/java/io/StringReaderTest.java
+++ /dev/null
@@ -1,279 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-
-import java.io.IOException;
-import java.io.StringReader;
-
-@TestTargetClass(StringReader.class)
-public class StringReaderTest extends junit.framework.TestCase {
-
- String testString = "This is a test string";
-
- StringReader sr;
-
- /**
- * @tests java.io.StringReader#StringReader(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StringReader",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.io.StringReader(java.lang.String)
- try {
- new StringReader("Test string");
- } catch (Exception ee) {
- fail ("Exception " + ee.getMessage() + " does not expected in this case");
- }
- }
-
- /**
- * @tests java.io.StringReader#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "close",
- args = {}
- )
- public void test_close() {
- // Test for method void java.io.StringReader.close()
- try {
- sr = new StringReader(testString);
- sr.close();
- char[] buf = new char[10];
- sr.read(buf, 0, 2);
- fail("Close failed");
- } catch (java.io.IOException e) {
- return;
- }
- }
-
- /**
- * @throws IOException
- * @tests java.io.StringReader#mark(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "IOException will never be thrown for this implementation.",
- method = "mark",
- args = {int.class}
- )
- public void test_markI() throws IOException {
- sr = new StringReader(testString);
- sr.skip(5);
- sr.mark(0);
- sr.skip(5);
- sr.reset();
- char[] buf = new char[10];
- sr.read(buf, 0, 2);
- assertTrue("Failed to return to mark", new String(buf, 0, 2)
- .equals(testString.substring(5, 7)));
- try {
- sr.mark(-1);
- fail("IllegalArgumentException not thrown!");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.StringReader#markSupported()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "markSupported",
- args = {}
- )
- public void test_markSupported() {
- // Test for method boolean java.io.StringReader.markSupported()
-
- sr = new StringReader(testString);
- assertTrue("markSupported returned false", sr.markSupported());
- }
-
- /**
- * @tests java.io.StringReader#read()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "IOException will never be thrown for this implementation.",
- method = "read",
- args = {}
- )
- public void test_read() {
- // Test for method int java.io.StringReader.read()
- try {
- sr = new StringReader(testString);
- int r = sr.read();
- assertEquals("Failed to read char", 'T', r);
- sr = new StringReader(new String(new char[] { '\u8765' }));
- assertTrue("Wrong double byte char", sr.read() == '\u8765');
- } catch (Exception e) {
- fail("Exception during read test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.StringReader#read(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "IOException will never be thrown for this implementation.",
- method = "read",
- args = {char[].class, int.class, int.class}
- )
- public void test_read$CII() throws Exception {
- // Test for method int java.io.StringReader.read(char [], int, int)
- try {
- sr = new StringReader(testString);
- char[] buf = new char[testString.length()];
- int r = sr.read(buf, 0, testString.length());
- assertTrue("Failed to read chars", r == testString.length());
- assertTrue("Read chars incorrectly", new String(buf, 0, r)
- .equals(testString));
- } catch (Exception e) {
- fail("Exception during read test : " + e.getMessage());
- }
-
- char[] buf = new char[testString.length()];
- sr = new StringReader(testString);
- try {
- sr.read(buf, 0, -1);
- fail("IndexOutOfBoundsException was not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- sr.read(buf, -1, 1);
- fail("IndexOutOfBoundsException was not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- sr.read(buf, 1, testString.length());
- fail("IndexOutOfBoundsException was not thrown");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.io.StringReader#ready()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "IOException will never be thrown for this implementation.",
- method = "ready",
- args = {}
- )
- public void test_ready() {
- // Test for method boolean java.io.StringReader.ready()
- try {
- sr = new StringReader(testString);
- assertTrue("Steam not ready", sr.ready());
- sr.close();
- int r = 0;
- try {
- sr.ready();
- } catch (IOException e) {
- r = 1;
- }
- assertEquals("Expected IOException not thrown in read()", 1, r);
- } catch (IOException e) {
- fail("IOException during ready test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.StringReader#reset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "IOException will never be thrown for this implementation.",
- method = "reset",
- args = {}
- )
- public void test_reset() {
- // Test for method void java.io.StringReader.reset()
- try {
- sr = new StringReader(testString);
- sr.skip(5);
- sr.mark(0);
- sr.skip(5);
- sr.reset();
- char[] buf = new char[10];
- sr.read(buf, 0, 2);
- assertTrue("Failed to reset properly", new String(buf, 0, 2)
- .equals(testString.substring(5, 7)));
- } catch (Exception e) {
- fail("Exception during reset test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.StringReader#skip(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "IOException will never be thrown for this implementation.",
- method = "skip",
- args = {long.class}
- )
- public void test_skipJ() {
- // Test for method long java.io.StringReader.skip(long)
- try {
- sr = new StringReader(testString);
- sr.skip(5);
- char[] buf = new char[10];
- sr.read(buf, 0, 2);
- assertTrue("Failed to skip properly", new String(buf, 0, 2)
- .equals(testString.substring(5, 7)));
- } catch (Exception e) {
- fail("Exception during skip test : " + e.getMessage());
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
-
- try {
- sr.close();
- } catch (Exception e) {
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/StringWriterTest.java b/luni/src/test/java/tests/api/java/io/StringWriterTest.java
deleted file mode 100644
index 1436b1e..0000000
--- a/luni/src/test/java/tests/api/java/io/StringWriterTest.java
+++ /dev/null
@@ -1,306 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-
-import java.io.IOException;
-import java.io.StringWriter;
-
-@TestTargetClass(StringWriter.class)
-public class StringWriterTest extends junit.framework.TestCase {
-
- StringWriter sw;
-
- /**
- * @tests java.io.StringWriter#StringWriter()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StringWriter",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StringWriter",
- args = {int.class}
- )
- })
- public void test_Constructor() {
- new StringWriter();
- new StringWriter(10);
- new StringWriter(10000);
- }
-
- /**
- * @tests java.io.StringWriter#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "There won't be IOException, ever!",
- method = "close",
- args = {}
- )
- public void test_close() {
- // Test for method void java.io.StringWriter.close()
- try {
- sw.close();
- } catch (IOException e) {
- fail("IOException closing StringWriter : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.io.StringWriter#flush()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "flush",
- args = {}
- )
- public void test_flush() {
- // Test for method void java.io.StringWriter.flush()
- sw.flush();
- sw.write('c');
- assertEquals("Failed to flush char", "c", sw.toString());
- }
-
- /**
- * @tests java.io.StringWriter#getBuffer()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBuffer",
- args = {}
- )
- public void test_getBuffer() {
- // Test for method java.lang.StringBuffer
- // java.io.StringWriter.getBuffer()
-
- sw.write("This is a test string");
- StringBuffer sb = sw.getBuffer();
- assertEquals("Incorrect buffer returned",
- "This is a test string", sb.toString());
- }
-
- /**
- * @tests java.io.StringWriter#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.io.StringWriter.toString()
- sw.write("This is a test string");
- assertEquals("Incorrect string returned",
- "This is a test string", sw.toString());
- }
-
- /**
- * @tests java.io.StringWriter#write(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {char[].class, int.class, int.class}
- )
- public void test_write$CII() {
- // Test for method void java.io.StringWriter.write(char [], int, int)
- char[] c = new char[1000];
- "This is a test string".getChars(0, 21, c, 0);
- sw.write(c, 4, 14);
- assertEquals("Chars not written properly",
- " is a test str", sw.toString());
- }
-
- /**
- * @tests java.io.StringWriter#write(char[], int, int)
- * Regression for HARMONY-387
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {char[].class, int.class, int.class}
- )
- public void test_write$CII_Exception() {
- StringWriter obj = new StringWriter();
- try {
- obj.write(new char[10], 0, -1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- obj.write(new char[10], -1, 1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
-
- try {
- obj.write(new char[10], 2, 9);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.io.StringWriter#write(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {int.class}
- )
- public void test_writeI() {
- // Test for method void java.io.StringWriter.write(int)
- sw.write('c');
- assertEquals("Char not written properly", "c", sw.toString());
- }
-
- /**
- * @tests java.io.StringWriter#write(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {java.lang.String.class}
- )
- public void test_writeLjava_lang_String() {
- // Test for method void java.io.StringWriter.write(java.lang.String)
- sw.write("This is a test string");
- assertEquals("String not written properly",
- "This is a test string", sw.toString());
- }
-
- /**
- * @tests java.io.StringWriter#write(java.lang.String, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {java.lang.String.class, int.class, int.class}
- )
- public void test_writeLjava_lang_StringII() {
- // Test for method void java.io.StringWriter.write(java.lang.String,
- // int, int)
- sw.write("This is a test string", 2, 2);
- assertEquals("String not written properly", "is", sw.toString());
- }
-
- /**
- * @tests java.io.StringWriter#append(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {char.class}
- )
- public void test_appendChar() throws IOException {
- char testChar = ' ';
- StringWriter stringWriter = new StringWriter(20);
- stringWriter.append(testChar);
- assertEquals(String.valueOf(testChar), stringWriter.toString());
- stringWriter.close();
- }
-
- /**
- * @tests java.io.PrintWriter#append(CharSequence)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {java.lang.CharSequence.class}
- )
- public void test_appendCharSequence() throws IOException {
-
- String testString = "My Test String";
- StringWriter stringWriter = new StringWriter(20);
- stringWriter.append(testString);
- assertEquals(String.valueOf(testString), stringWriter.toString());
- stringWriter.close();
- }
-
- /**
- * @tests java.io.PrintWriter#append(CharSequence, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {java.lang.CharSequence.class, int.class, int.class}
- )
- public void test_appendCharSequenceIntInt() throws IOException {
- String testString = "My Test String";
- StringWriter stringWriter = new StringWriter(20);
- stringWriter.append(testString, 1, 3);
- assertEquals(testString.substring(1, 3), stringWriter.toString());
- stringWriter.close();
-
- try {
- StringWriter tobj = new StringWriter(9);
- tobj.append("01234567890123456789", 19, 2);
- fail("IndexOutOfBoundsException not thrown!");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- StringWriter tobj = new StringWriter(9);
- tobj.append("01234567890123456789", 29, 2);
- fail("IndexOutOfBoundsException not thrown!");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
-
- sw = new StringWriter();
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/SyncFailedExceptionTest.java b/luni/src/test/java/tests/api/java/io/SyncFailedExceptionTest.java
deleted file mode 100644
index 0f7e0da..0000000
--- a/luni/src/test/java/tests/api/java/io/SyncFailedExceptionTest.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.SyncFailedException;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(SyncFailedException.class)
-public class SyncFailedExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.io.SyncFailedException#SyncFailedException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "SyncFailedException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- try {
- if (true) // To avoid unreachable code compilation error.
- throw new SyncFailedException("Something went wrong.");
- fail("Test 1: SyncFailedException expected.");
- } catch (SyncFailedException e) {
- assertEquals("Test 2: Incorrect message;",
- "Something went wrong.", e.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/UTFDataFormatExceptionTest.java b/luni/src/test/java/tests/api/java/io/UTFDataFormatExceptionTest.java
deleted file mode 100644
index d7a97d3..0000000
--- a/luni/src/test/java/tests/api/java/io/UTFDataFormatExceptionTest.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.UTFDataFormatException;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(UTFDataFormatException.class)
-public class UTFDataFormatExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.io.UTFDataFormatException#UTFDataFormatException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "UTFDataFormatException",
- args = {}
- )
- public void test_Constructor() {
- try {
- if (true) // To avoid unreachable code compilation error.
- throw new UTFDataFormatException();
- fail("Test 1: UTFDataFormatException expected.");
- } catch (UTFDataFormatException e) {
- assertNull("Test 2: Null expected for exceptions constructed without a message.",
- e.getMessage());
- }
- }
-
- /**
- * @tests java.io.UTFDataFormatException#UTFDataFormatException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "UTFDataFormatException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- try {
- if (true) // To avoid unreachable code compilation error.
- throw new UTFDataFormatException("Something went wrong.");
- fail("Test 1: UTFDataFormatException expected.");
- } catch (UTFDataFormatException e) {
- assertEquals("Test 2: Incorrect message;",
- "Something went wrong.", e.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/UnsupportedEncodingExceptionTest.java b/luni/src/test/java/tests/api/java/io/UnsupportedEncodingExceptionTest.java
deleted file mode 100644
index 45b20da..0000000
--- a/luni/src/test/java/tests/api/java/io/UnsupportedEncodingExceptionTest.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import java.io.UnsupportedEncodingException;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(UnsupportedEncodingException.class)
-public class UnsupportedEncodingExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.io.UnsupportedEncodingException#UnsupportedEncodingException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "UnsupportedEncodingException",
- args = {}
- )
- public void test_Constructor() {
- try {
- if (true) // To avoid unreachable code compilation error.
- throw new UnsupportedEncodingException();
- fail("Test 1: UnsupportedEncodingException expected.");
- } catch (UnsupportedEncodingException e) {
- assertNull("Test 2: Null expected for exceptions constructed without a message.",
- e.getMessage());
- }
- }
-
- /**
- * @tests java.io.UnsupportedEncodingException#UnsupportedEncodingException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- method = "UnsupportedEncodingException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- try {
- if (true) // To avoid unreachable code compilation error.
- throw new UnsupportedEncodingException("Something went wrong.");
- fail("Test 1: UnsupportedEncodingException expected.");
- } catch (UnsupportedEncodingException e) {
- assertEquals("Test 2: Incorrect message;",
- "Something went wrong.", e.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/WriteAbortedExceptionTest.java b/luni/src/test/java/tests/api/java/io/WriteAbortedExceptionTest.java
deleted file mode 100644
index 1278d98..0000000
--- a/luni/src/test/java/tests/api/java/io/WriteAbortedExceptionTest.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * 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 tests.api.java.io;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-
-import java.io.IOException;
-import java.io.WriteAbortedException;
-
-@TestTargetClass(WriteAbortedException.class)
-public class WriteAbortedExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.io.WriteAbortedException#WriteAbortedException(java.lang.String,
- * java.lang.Exception)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "WriteAbortedException",
- args = {java.lang.String.class, java.lang.Exception.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_Exception() {
- // Test for method java.io.WriteAbortedException(java.lang.String,
- // java.lang.Exception)
- try {
- if (true)
- throw new WriteAbortedException("HelloWorld",
- new WriteAbortedException("ByeWorld", null));
- } catch (WriteAbortedException e) {
- return;
- }
- fail("Failed to generate expected Exception");
- }
-
- /**
- * @tests java.io.WriteAbortedException#getMessage()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCause",
- args = {}
- )
- public void test_getCause() {
- try {
- if (true) {
- throw new WriteAbortedException("HelloWorld",
- new IOException("Something went wrong."));
- }
- fail("Test 1: WriteAbortedException expected.");
- } catch (WriteAbortedException e) {
- Throwable cause = e.getCause();
- assertTrue("Test 2: Incorrect exception cause: " + cause,
- cause.getClass().equals(IOException.class) &&
- cause.getMessage().equals("Something went wrong."));
- }
- }
-
- /**
- * @tests java.io.WriteAbortedException#getMessage()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
- public void test_getMessage() {
- // Test for method java.lang.String
- // java.io.WriteAbortedException.getMessage()
- try {
- if (true)
- throw new WriteAbortedException("HelloWorld",
- new WriteAbortedException("ByeWorld", null));
- } catch (WriteAbortedException e) {
- assertTrue("WriteAbortedException::getMessage() failed"
- + e.getMessage(), e.getMessage().equals(
- "HelloWorld; java.io.WriteAbortedException: ByeWorld"));
- return;
- }
- fail("Failed to generate expected Exception");
- }
-}
diff --git a/luni/src/test/java/tests/api/java/io/WriterTest.java b/luni/src/test/java/tests/api/java/io/WriterTest.java
deleted file mode 100644
index 2a15c67..0000000
--- a/luni/src/test/java/tests/api/java/io/WriterTest.java
+++ /dev/null
@@ -1,338 +0,0 @@
-/* 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 tests.api.java.io;
-
-import java.io.IOException;
-import java.io.Writer;
-
-import junit.framework.TestCase;
-import tests.support.Support_ASimpleWriter;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(Writer.class)
-public class WriterTest extends TestCase {
-
- /**
- * @tests java.io.Writer#append(char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {char.class}
- )
- public void test_appendChar() throws IOException {
- char testChar = ' ';
- MockWriter writer = new MockWriter(20);
- writer.append(testChar);
- assertEquals(String.valueOf(testChar), String.valueOf(writer
- .getContents()));
- writer.close();
-
- Writer tobj = new Support_ASimpleWriter(2);
- tobj.append('a');
- tobj.append('b');
- assertEquals("Wrong stuff written!", "ab", tobj.toString());
- try {
- tobj.append('c');
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.Writer#append(CharSequence)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "append",
- args = {java.lang.CharSequence.class}
- )
- public void test_appendCharSequence() throws IOException {
- String testString = "My Test String";
- MockWriter writer = new MockWriter(20);
- writer.append(testString);
- assertEquals(testString, String.valueOf(writer.getContents()));
- writer.close();
-
- Writer tobj = new Support_ASimpleWriter(20);
- tobj.append(testString);
- assertEquals("Wrong stuff written!", testString, tobj.toString());
- try {
- tobj.append(testString);
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.Writer#append(CharSequence, int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "append",
- args = {CharSequence.class, int.class, int.class}
- )
- public void test_appendCharSequenceIntInt() throws IOException {
- String testString = "My Test String";
- MockWriter writer = new MockWriter(20);
- writer.append(testString, 1, 3);
- assertEquals(testString.substring(1, 3), String.valueOf(writer
- .getContents()));
- writer.close();
-
- Writer tobj = new Support_ASimpleWriter(21);
- testString = "0123456789abcdefghijABCDEFGHIJ";
- tobj.append(testString, 0, 5);
- assertEquals("Wrong stuff written!", "01234", tobj.toString());
- tobj.append(testString, 10, 15);
- assertEquals("Wrong stuff written!", "01234abcde", tobj.toString());
- tobj.append(testString, 20, 30);
- assertEquals("Wrong stuff written!", "01234abcdeABCDEFGHIJ", tobj.toString());
- try {
- tobj.append(testString, 30, 31);
- fail("IndexOutOfBoundsException not thrown!");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- tobj.append(testString, 20, 21); // Just fill the writer to its limit!
- try {
- tobj.append(testString, 29, 30);
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.Writer#append(CharSequence, int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "append",
- args = {CharSequence.class, int.class, int.class}
- )
- public void test_appendCharSequenceIntInt_Exception() throws IOException {
- String testString = "My Test String";
- Writer tobj = new Support_ASimpleWriter(21);
- try {
- tobj.append(testString, 30, 31);
- fail("IndexOutOfBoundsException not thrown!");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- tobj.append(testString, -1, 1);
- fail("IndexOutOfBoundsException not thrown!");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- tobj.append(testString, 0, -1);
- fail("IndexOutOfBoundsException not thrown!");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {char[].class}
- )
- public void test_write$C() throws IOException {
- Writer tobj = new Support_ASimpleWriter(21);
- tobj.write("01234".toCharArray());
- assertEquals("Wrong stuff written!", "01234", tobj.toString());
- tobj.write("abcde".toCharArray());
- assertEquals("Wrong stuff written!", "01234abcde", tobj.toString());
- tobj.write("ABCDEFGHIJ".toCharArray());
- assertEquals("Wrong stuff written!", "01234abcdeABCDEFGHIJ", tobj.toString());
- tobj.write("z".toCharArray()); // Just fill the writer to its limit!
- try {
- tobj.write("LES JEUX SONT FAITS".toCharArray());
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {int.class}
- )
- public void test_writeI() throws IOException {
- Writer tobj = new Support_ASimpleWriter(2);
- tobj.write('a');
- tobj.write('b');
- assertEquals("Wrong stuff written!", "ab", tobj.toString());
- try {
- tobj.write('c');
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {java.lang.String.class}
- )
- public void test_writeLjava_lang_String() throws IOException {
- Writer tobj = new Support_ASimpleWriter(21);
- tobj.write("01234");
- assertEquals("Wrong stuff written!", "01234", tobj.toString());
- tobj.write("abcde");
- assertEquals("Wrong stuff written!", "01234abcde", tobj.toString());
- tobj.write("ABCDEFGHIJ");
- assertEquals("Wrong stuff written!", "01234abcdeABCDEFGHIJ", tobj.toString());
- tobj.write("z"); // Just fill the writer to its limit!
- try {
- tobj.write("LES JEUX SONT FAITS");
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.PrintWriter#write(java.lang.String, int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {String.class, int.class, int.class}
- )
- public void test_writeLjava_lang_StringII() throws IOException {
- String testString;
- Writer tobj = new Support_ASimpleWriter(21);
- testString = "0123456789abcdefghijABCDEFGHIJ";
- tobj.write(testString, 0, 5);
- assertEquals("Wrong stuff written!", "01234", tobj.toString());
- tobj.write(testString, 10, 5);
- assertEquals("Wrong stuff written!", "01234abcde", tobj.toString());
- tobj.write(testString, 20, 10);
- assertEquals("Wrong stuff written!", "01234abcdeABCDEFGHIJ", tobj.toString());
- try {
- tobj.write(testString, 30, 1);
- fail("IndexOutOfBoundsException not thrown!");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- tobj.write(testString, 20, 1); // Just fill the writer to its limit!
- try {
- tobj.write(testString, 29, 1);
- fail("IOException not thrown!");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests java.io.Writer#append(CharSequence, int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "write",
- args = {String.class, int.class, int.class}
- )
- public void test_writeLjava_lang_StringII_Exception() throws IOException {
- String testString = "My Test String";
- Writer tobj = new Support_ASimpleWriter(21);
- try {
- tobj.write(testString, 30, 31);
- fail("IndexOutOfBoundsException not thrown!");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- tobj.write(testString, -1, 1);
- fail("IndexOutOfBoundsException not thrown!");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- try {
- tobj.write(testString, 0, -1);
- fail("IndexOutOfBoundsException not thrown!");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- class MockWriter extends Writer {
- private char[] contents;
-
- private int length;
-
- private int offset;
-
- MockWriter(int capacity) {
- contents = new char[capacity];
- length = capacity;
- offset = 0;
- }
-
- public synchronized void close() throws IOException {
- flush();
- contents = null;
- }
-
- public synchronized void flush() throws IOException {
- // do nothing
- }
-
- public void write(char[] buffer, int offset, int count)
- throws IOException {
- if (null == contents) {
- throw new IOException();
- }
- if (offset < 0 || count < 0 || offset >= buffer.length) {
- throw new IndexOutOfBoundsException();
- }
- count = Math.min(count, buffer.length - offset);
- count = Math.min(count, this.length - this.offset);
- for (int i = 0; i < count; i++) {
- contents[this.offset + i] = buffer[offset + i];
- }
- this.offset += count;
-
- }
-
- public char[] getContents() {
- char[] result = new char[offset];
- for (int i = 0; i < offset; i++) {
- result[i] = contents[i];
- }
- return result;
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/lang/AllTests.java b/luni/src/test/java/tests/api/java/lang/AllTests.java
deleted file mode 100644
index 5a70224..0000000
--- a/luni/src/test/java/tests/api/java/lang/AllTests.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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 tests.api.java.lang;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-/**
- * TODO Type description
- */
-public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(AllTests.suite());
- }
-
- public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Test for java.lang");
-
- // $JUnit-BEGIN$
-
- suite.addTestSuite(Process2Test.class);
- suite.addTestSuite(ProcessTest.class);
- suite.addTestSuite(ProcessManagerTest.class);
- suite.addTestSuite(BooleanTest.class);
- suite.addTestSuite(StringTest.class);
-
- // $JUnit-END$
-
- return suite;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/BooleanTest.java b/luni/src/test/java/tests/api/java/lang/BooleanTest.java
deleted file mode 100644
index 9c467e5..0000000
--- a/luni/src/test/java/tests/api/java/lang/BooleanTest.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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 tests.api.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for the class {@link Boolean}.
- */
-@TestTargetClass(Boolean.class)
-public class BooleanTest
- extends TestCase
-{
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Checks that booleanValue() returns true.",
- method = "booleanValue",
- args = {}
- )
- public void test_TRUE() {
- assertTrue(Boolean.TRUE.booleanValue() == true);
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Checks that booleanValue() returns false.",
- method = "booleanValue",
- args = {}
- )
- public void test_FALSE() {
- assertTrue(Boolean.FALSE.booleanValue() == false);
- }
-
- // TODO(danfuzz): Add tests for the rest of Boolean here.
-}
diff --git a/luni/src/test/java/tests/api/java/lang/Process2Test.java b/luni/src/test/java/tests/api/java/lang/Process2Test.java
deleted file mode 100644
index 51b29d8..0000000
--- a/luni/src/test/java/tests/api/java/lang/Process2Test.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * 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 tests.api.java.lang;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-import tests.support.Support_Exec;
-
-@TestTargetClass(Process.class)
-public class Process2Test extends junit.framework.TestCase {
- /**
- * @tests java.lang.Process#getInputStream(),
- * java.lang.Process#getErrorStream()
- * java.lang.Process#getOutputStream()
- * Tests if these methods return buffered streams.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getErrorStream",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getInputStream",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getOutputStream",
- args = {}
- )
- })
- @AndroidOnly("dalvikvm specific")
- public void test_isBufferedStreams() {
- // Regression test for HARMONY-2735.
- try {
- Object[] execArgs = Support_Exec.execJava2(new String[0], null, true);
- Process p = (Process) execArgs[0];
- InputStream in = p.getInputStream();
- assertNotNull(in);
- in = p.getErrorStream();
- assertNotNull(in);
- OutputStream out = p.getOutputStream();
- assertNotNull(out);
- in.close();
- out.close();
- p.destroy();
- } catch (Exception ex) {
- fail("Unexpected exception got: " + ex);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getErrorStream",
- args = {}
- )
- public void test_getErrorStream() {
- String[] commands = {"ls"};
- Process process = null;
- try {
- process = Runtime.getRuntime().exec(commands, null, null);
- InputStream is = process.getErrorStream();
- StringBuffer msg = new StringBuffer("");
- while (true) {
- int c = is.read();
- if (c == -1)
- break;
- msg.append((char) c);
- }
- assertEquals("", msg.toString());
- } catch (IOException e) {
- fail("IOException was thrown.");
- } finally {
- process.destroy();
- }
-
- String[] unknownCommands = {"mkdir", "-u", "test"};
- Process erProcess = null;
- try {
- erProcess = Runtime.getRuntime().exec(unknownCommands, null, null);
- InputStream is = erProcess.getErrorStream();
- StringBuffer msg = new StringBuffer("");
- while (true) {
- int c = is.read();
- if (c == -1)
- break;
- msg.append((char) c);
- }
- assertTrue("Error stream should not be empty",
- !"".equals(msg.toString()));
- } catch (IOException e) {
- fail("IOException was thrown.");
- } finally {
- erProcess.destroy();
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/ProcessManagerTest.java b/luni/src/test/java/tests/api/java/lang/ProcessManagerTest.java
deleted file mode 100644
index 8a6da3b..0000000
--- a/luni/src/test/java/tests/api/java/lang/ProcessManagerTest.java
+++ /dev/null
@@ -1,255 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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 tests.api.java.lang;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-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.io.OutputStream;
-
-@TestTargetClass(Process.class)
-public class ProcessManagerTest extends TestCase {
-
- Thread thread = null;
- Process process = null;
- boolean isThrown = false;
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getOutputStream",
- args = {}
- )
- public void testCat() throws IOException, InterruptedException {
- String[] commands = { "cat" };
- Process process = Runtime.getRuntime().exec(commands, null, null);
-
- OutputStream out = process.getOutputStream();
- String greeting = "Hello, World!";
- out.write(greeting.getBytes());
- out.write('\n');
- out.close();
-
- assertEquals(greeting, readLine(process));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "waitFor",
- args = {}
- )
- public void testSleep() throws IOException {
- String[] commands = { "sleep", "1" };
- process = Runtime.getRuntime().exec(commands, null, null);
- try {
- assertEquals(0, process.waitFor());
-
- } catch(InterruptedException ie) {
- fail("InterruptedException was thrown.");
- }
-
- isThrown = false;
- thread = new Thread() {
- public void run() {
- String[] commands = { "sleep", "1000"};
- try {
- process = Runtime.getRuntime().exec(commands, null, null);
- } catch (IOException e1) {
- fail("IOException was thrown.");
- }
- try {
- process.waitFor();
- fail("InterruptedException was not thrown.");
- } catch(InterruptedException ie) {
- isThrown = true;
- }
- }
- };
-
- Thread interruptThread = new Thread() {
- public void run() {
- try {
- sleep(10);
- } catch(InterruptedException ie) {
- fail("InterruptedException was thrown in " +
- "the interruptThread.");
- }
- thread.interrupt();
- }
- };
- thread.start();
- interruptThread.start();
- try {
- interruptThread.join();
- } catch (InterruptedException e) {
- fail("InterruptedException was thrown.");
- }
- try {
- Thread.sleep(100);
- } catch(InterruptedException ie) {
-
- }
-
- thread.interrupt();
- //process.destroy();
- try {
- Thread.sleep(100);
- } catch(InterruptedException ie) {
-
- }
-
- assertTrue(isThrown);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInputStream",
- args = {}
- )
- public void testPwd() throws IOException, InterruptedException {
- String[] commands = { "sh", "-c", "pwd" };
- Process process = Runtime.getRuntime().exec(
- commands, null, new File("/"));
- logErrors(process);
- assertEquals("/", readLine(process));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInputStream",
- args = {}
- )
- public void testEnvironment() throws IOException, InterruptedException {
- String[] commands = { "sh", "-c", "echo $FOO" };
-
- // Remember to set the path so we can find sh.
- String[] environment = { "FOO=foo", "PATH=" + System.getenv("PATH") };
- Process process = Runtime.getRuntime().exec(
- commands, environment, null);
- logErrors(process);
- assertEquals("foo", readLine(process));
- }
-
- String readLine(Process process) throws IOException {
- InputStream in = process.getInputStream();
- BufferedReader reader = new BufferedReader(new InputStreamReader(in));
- return reader.readLine();
- }
-
- void logErrors(final Process process) throws IOException {
- Thread thread = new Thread() {
- public void run() {
- InputStream in = process.getErrorStream();
- BufferedReader reader
- = new BufferedReader(new InputStreamReader(in));
- String line;
- try {
- while ((line = reader.readLine()) != null) {
- System.err.println(line);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- };
- thread.setDaemon(true);
- thread.start();
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Stress test.",
- method = "waitFor",
- args = {}
- )
- public void testHeavyLoad() {
- int i;
- for (i = 0; i < 2000; i++)
- stuff();
- }
-
- private static void stuff() {
- Runtime rt = Runtime.getRuntime();
- try {
- Process proc = rt.exec("ls");
- proc.waitFor();
- proc = null;
- } catch (Exception ex) {
- System.err.println("Failure: " + ex);
- throw new RuntimeException(ex);
- }
- rt.gc();
- rt = null;
- }
-
- InputStream in;
-
- public void testCloseNonStandardFds()
- throws IOException, InterruptedException {
- String[] commands = { "ls", "/proc/self/fd" };
-
- Process process = Runtime.getRuntime().exec(commands, null, null);
- int before = countLines(process);
-
- // Open a new fd.
- this.in = new FileInputStream("/proc/version");
-
- try {
- process = Runtime.getRuntime().exec(commands, null, null);
- int after = countLines(process);
-
- // Assert that the new fd wasn't open in the second run.
- assertEquals(before, after);
- } finally {
- this.in = null;
- }
- }
-
- /**
- * Counts lines of input from the given process. Equivalent to "wc -l".
- */
- private int countLines(Process process) throws IOException {
- logErrors(process);
- InputStream in = process.getInputStream();
- BufferedReader reader = new BufferedReader(new InputStreamReader(in));
- int count = 0;
- while (reader.readLine() != null) {
- count++;
- }
- return count;
- }
-
- public void testInvalidCommand()
- throws IOException, InterruptedException {
- try {
- String[] commands = { "doesnotexist" };
- Runtime.getRuntime().exec(commands, null, null);
- } catch (IOException e) { /* expected */ }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/ProcessTest.java b/luni/src/test/java/tests/api/java/lang/ProcessTest.java
deleted file mode 100644
index 84bcbde..0000000
--- a/luni/src/test/java/tests/api/java/lang/ProcessTest.java
+++ /dev/null
@@ -1,240 +0,0 @@
-/*
- * 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 tests.api.java.lang;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-@TestTargetClass(Process.class)
-public class ProcessTest extends junit.framework.TestCase {
-
- /**
- * @tests java.lang.Process#getInputStream()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInputStream",
- args = {}
- )
- public void test_getInputStream() {
- try {
- // Test for:
- //Object[] execArgs = Support_Exec.execJava2(
- // new String[] { "tests.support.Support_AvailTest" }, null,
- // true);
- //Process proc = (Process) execArgs[0];
-
- String[] commands = { "sleep", "1"};
- Process proc = Runtime.getRuntime().exec(commands, null, null);
-
- OutputStream os = proc.getOutputStream();
-
- // first number indicates total stream length
- // second number indicates length of data after second space
- // this will allow us to verify length at start, middle, and end
- os.write("10 5 abcde".getBytes());
- os.close();
-
- InputStream is = proc.getInputStream();
- StringBuffer msg = new StringBuffer("");
- while (true) {
- int c = is.read();
- if (c == -1)
- break;
- msg.append((char) c);
- }
- is.close();
- proc.waitFor();
- //Support_Exec.checkStderr(execArgs);
- proc.destroy();
- assertEquals("true", msg.toString(), msg.toString());
- } catch (IOException e) {
- fail("IOException executing avail test: " + e);
- } catch (InterruptedException e) {
- fail("InterruptedException executing avail test: " + e);
- }
- }
-
- /**
- * @tests java.lang.Process#getOutputStream()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getOutputStream",
- args = {}
- )
- public void test_getOutputStream() {
- try {
- String[] commands = { "sleep", "1"};
- Process proc = Runtime.getRuntime().exec(commands, null, null);
- OutputStream os = proc.getOutputStream();
- // send data, and check if it is echoed back correctly
- String str1 = "Some data for testing communication between processes\n";
- String str2 = "More data that serves the same purpose.\n";
- String str3 = "Here is some more data.\n";
- os.write(str1.getBytes());
- try {
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- os.close();
- InputStream is = proc.getInputStream();
- StringBuffer msg = new StringBuffer("");
- while (true) {
- int c = is.read();
- if (c == -1)
- break;
- msg.append((char) c);
- }
- is.close();
- proc.waitFor();
- //Support_Exec.checkStderr(execArgs);
- proc.destroy();
- String org = str1;
- String recvd = msg.toString();
- // Doesn't pass on RI
- // assertTrue("Data returned did not match data sent. Received: '"
- // + recvd + "' sent: '" + org + "'", recvd.equals(org));
- } catch (IOException e) {
- fail("IOException executing avail test: " + e);
- } catch (InterruptedException e) {
- fail("InterruptedException executing avail test: " + e);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "exitValue",
- args = {}
- )
- public void test_exitValue() {
- try {
- String[] commands = { "ls" };
- Process process = Runtime.getRuntime().exec(commands, null, null);
- try {
- Thread.sleep(5000);
- } catch(Exception e) {
-
- }
- assertTrue(process.exitValue() == 0);
-
- String[] commandsSleep = { "sleep", "3" };
- process = Runtime.getRuntime().exec(commandsSleep, null, null);
- process.destroy();
- try {
- Thread.sleep(5000);
- } catch (Exception e) {}
- assertTrue(process.exitValue() != 0);
-
- process = Runtime.getRuntime().exec(commandsSleep, null, null);
- try {
- process.exitValue();
- fail("IllegalThreadStateException was not thrown.");
- } catch(IllegalThreadStateException itse) {
- //expected
- }
- } catch (IOException e) {
- fail("IOException was thrown.");
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Process",
- args = {}
- )
- public void test_Constructor() {
- ProcessClass pc = new ProcessClass();
- assertTrue(pc.exitValue() == 0);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "destroy",
- args = {}
- )
- public void test_destroy() {
- String[] commands = { "ls"};
- try {
- Process process = Runtime.getRuntime().exec(commands, null, null);
- process.destroy();
- } catch (IOException e) {
- fail("IOException was thrown.");
- }
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-
- protected void doneSuite() {
- }
-
- class ProcessClass extends Process {
-
- ProcessClass() {
- super();
- }
-
- @Override
- public void destroy() {
-
- }
-
- @Override
- public int exitValue() {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- public InputStream getErrorStream() {
- return null;
- }
-
- @Override
- public InputStream getInputStream() {
- return null;
- }
-
- @Override
- public OutputStream getOutputStream() {
- return null;
- }
-
- @Override
- public int waitFor() throws InterruptedException {
- // TODO Auto-generated method stub
- return 0;
- }
-
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/StringTest.java b/luni/src/test/java/tests/api/java/lang/StringTest.java
deleted file mode 100644
index 4260e79..0000000
--- a/luni/src/test/java/tests/api/java/lang/StringTest.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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 tests.api.java.lang;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for the class {@link String}.
- */
-@TestTargetClass(String.class)
-public class StringTest extends TestCase {
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "NullPointerException is not verified.",
- method = "contains",
- args = {java.lang.CharSequence.class}
- )
- public void test_contains() {
- assertTrue("aabc".contains("abc"));
- assertTrue("abcd".contains("abc"));
- assertFalse("abcd".contains("cba"));
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IndexOutOfBoundsException is not verified.",
- method = "charAt",
- args = {int.class}
- )
- public void test_charAt() {
- assertTrue("abcd".charAt(0) == 'a');
- assertTrue("abcd".charAt(3) == 'd');
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't check empty string, null as a parameter.",
- method = "startsWith",
- args = {java.lang.String.class}
- )
- public void test_StartsWith() {
- assertTrue("abcd".startsWith("abc"));
- assertFalse("abcd".startsWith("aabc"));
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't check empty string, null as a parameter.",
- method = "endsWith",
- args = {java.lang.String.class}
- )
- public void test_EndsWith() {
- assertTrue("abcd".endsWith("bcd"));
- assertFalse("abcd".endsWith("bcde"));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!Constants",
- args = {}
- )
- public void test_CASE_INSENSITIVE_ORDER() {
- String s1 = "ABCDEFG";
- String s2 = "abcdefg";
-
- assertTrue(String.CASE_INSENSITIVE_ORDER.compare(s1, s2) == 0);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/ref/AllTests.java b/luni/src/test/java/tests/api/java/lang/ref/AllTests.java
deleted file mode 100644
index 75b7b9f..0000000
--- a/luni/src/test/java/tests/api/java/lang/ref/AllTests.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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 tests.api.java.lang.ref;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-/**
- * TODO Type description
- */
-public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(AllTests.suite());
- }
-
- public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Test for java.lang.ref");
-
- // $JUnit-BEGIN$
-
- suite.addTestSuite(PhantomReferenceTest.class);
- suite.addTestSuite(ReferenceQueueTest.class);
- suite.addTestSuite(ReferenceTest.class);
- suite.addTestSuite(SoftReferenceTest.class);
- suite.addTestSuite(WeakReferenceTest.class);
-
- // $JUnit-END$
-
- return suite;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/ref/PhantomReferenceTest.java b/luni/src/test/java/tests/api/java/lang/ref/PhantomReferenceTest.java
deleted file mode 100644
index 330aa94..0000000
--- a/luni/src/test/java/tests/api/java/lang/ref/PhantomReferenceTest.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * 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 tests.api.java.lang.ref;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.lang.ref.PhantomReference;
-import java.lang.ref.Reference;
-import java.lang.ref.ReferenceQueue;
-
-//TODO: write a test to verify that the referent's finalize() happens
-// before the PhantomReference is enqueued.
-
-@TestTargetClass(PhantomReference.class)
-public class PhantomReferenceTest extends junit.framework.TestCase {
- static Boolean bool;
- public boolean isCalled = false;
- protected void doneSuite() {
- bool = null;
- }
-
- /**
- * @tests java.lang.ref.PhantomReference#get()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {}
- )
- public void test_get() {
- ReferenceQueue rq = new ReferenceQueue();
- bool = new Boolean(false);
- PhantomReference pr = new PhantomReference(bool, rq);
- assertNull("get() should return null.", pr.get());
- pr.enqueue();
- assertNull("get() should return null.", pr.get());
- pr.clear();
- assertNull("get() should return null.", pr.get());
- }
-
- /**
- * @tests java.lang.Runtime#gc()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Interaction test with Runtime.getRuntime().gc().",
- method = "get",
- args = {}
- )
- public void test_gcInteraction() {
- class TestPhantomReference<T> extends PhantomReference<T> {
- public TestPhantomReference(T referent,
- ReferenceQueue<? super T> q) {
- super(referent, q);
- }
- public boolean enqueue() {
- // Initiate another GC from inside enqueue() to
- // see if it causes any problems inside the VM.
- Runtime.getRuntime().gc();
- return super.enqueue();
- }
- }
-
- final ReferenceQueue rq = new ReferenceQueue();
- final PhantomReference[] tprs = new PhantomReference[4];
-
- class TestThread extends Thread {
- public void run() {
- // Create the object in a separate thread to ensure
- // it will be gc'ed.
- Object obj = new Object();
- tprs[0] = new TestPhantomReference(obj, rq);
- tprs[1] = new TestPhantomReference(obj, rq);
- tprs[2] = new TestPhantomReference(obj, rq);
- tprs[3] = new TestPhantomReference(obj, rq);
- }
- }
-
- try {
- Thread t = new TestThread();
- t.start();
- t.join();
- System.gc();
- System.runFinalization();
-
- assertNull("get() should return null.", tprs[0].get());
- assertNull("get() should return null.", tprs[1].get());
- assertNull("get() should return null.", tprs[2].get());
- assertNull("get() should return null.", tprs[3].get());
-
- for (int i = 0; i < 4; i++) {
- Reference r = rq.remove(100L);
- assertNotNull("Reference should have been enqueued.", r);
- }
-
- // These are to make sure that tprs and its elements don't get
- // optimized out.
- assertNull("get() should return null.", tprs[0].get());
- assertNull("get() should return null.", tprs[1].get());
- assertNull("get() should return null.", tprs[2].get());
- assertNull("get() should return null.", tprs[3].get());
- } catch (InterruptedException e) {
- fail("InterruptedException : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.lang.ref.PhantomReference#PhantomReference(java.lang.Object,
- * java.lang.ref.ReferenceQueue)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PhantomReference",
- args = {java.lang.Object.class, java.lang.ref.ReferenceQueue.class}
- )
- public void test_ConstructorLjava_lang_ObjectLjava_lang_ref_ReferenceQueue() {
- ReferenceQueue rq = new ReferenceQueue();
- bool = new Boolean(true);
- try {
- PhantomReference pr = new PhantomReference(bool, rq);
- // Allow the finalizer to run to potentially enqueue
- Thread.sleep(1000);
- assertTrue("Initialization failed.", !pr.isEnqueued());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- // need a reference to bool so the jit does not optimize it away
- assertTrue("should always pass", bool.booleanValue());
-
- boolean exception = false;
- try {
- new PhantomReference(bool, null);
- } catch (NullPointerException e) {
- exception = true;
- }
- assertTrue("Should not throw NullPointerException", !exception);
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/ref/ReferenceQueueTest.java b/luni/src/test/java/tests/api/java/lang/ref/ReferenceQueueTest.java
deleted file mode 100644
index 0a32139..0000000
--- a/luni/src/test/java/tests/api/java/lang/ref/ReferenceQueueTest.java
+++ /dev/null
@@ -1,283 +0,0 @@
-/*
- * 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 tests.api.java.lang.ref;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.lang.ref.PhantomReference;
-import java.lang.ref.Reference;
-import java.lang.ref.ReferenceQueue;
-import java.lang.ref.SoftReference;
-import java.lang.ref.WeakReference;
-
-@TestTargetClass(ReferenceQueue.class)
-public class ReferenceQueueTest extends junit.framework.TestCase {
- static Boolean b;
-
- static Integer integer;
- boolean isThrown = false;
-
- protected void doneSuite() {
- b = null;
- integer = null;
- }
-
- public class ChildThread implements Runnable {
- public ChildThread() {
- }
-
- public void run() {
- try {
- rq.wait(1000);
- } catch (Exception e) {
- }
- synchronized (rq) {
- // store in a static so it won't be gc'ed because the jit
- // optimized it out
- integer = new Integer(667);
- SoftReference sr = new SoftReference(integer, rq);
- sr.enqueue();
- rq.notify();
- }
- }
- }
-
- ReferenceQueue rq;
-
- /**
- * @tests java.lang.ref.ReferenceQueue#poll()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "poll",
- args = {}
- )
- public void test_poll() {
- // store in a static so it won't be gc'ed because the jit
- // optimized it out
- b = new Boolean(true);
- Object obj = new Object();
- String str = "Test";
-
- SoftReference sr = new SoftReference(b, rq);
- WeakReference wr = new WeakReference(obj, rq);
- PhantomReference pr = new PhantomReference(str, rq);
- assertNull(rq.poll());
- sr.enqueue();
- wr.enqueue();
- pr.enqueue();
-
- try {
- assertNull("Remove failed.", rq.poll().get());
- } catch (Exception e) {
- fail("Exception during the test : " + e.getMessage());
- }
-
- try {
- assertEquals("Remove failed.", obj, (rq.poll().get()));
- } catch (Exception e) {
- fail("Exception during the test : " + e.getMessage());
- }
-
- try {
- assertTrue("Remove failed.", ((Boolean) rq.poll().get())
- .booleanValue());
- } catch (Exception e) {
- fail("Exception during the test : " + e.getMessage());
- }
- assertNull(rq.poll());
-
- sr.enqueue();
- wr.enqueue();
-
- System.gc();
- System.runFinalization();
-
- assertNull(rq.poll());
- }
-
- /**
- * @tests java.lang.ref.ReferenceQueue#remove()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {}
- )
- public void test_remove() {
- // store in a static so it won't be gc'ed because the jit
- // optimized it out
- b = new Boolean(true);
-
- SoftReference sr = new SoftReference(b, rq);
- sr.enqueue();
- try {
- assertTrue("Remove failed.", ((Boolean) rq.remove().get())
- .booleanValue());
- } catch (Exception e) {
- fail("Exception during the test : " + e.getMessage());
- }
-
- assertNull(rq.poll());
-
- sr.enqueue();
-
- class RemoveThread extends Thread {
- public void run() {
- try {
- rq.remove();
- } catch(InterruptedException ie) {
- isThrown = true;
- }
- }
- }
- RemoveThread rt = new RemoveThread();
- rt.start();
- try {
- Thread.sleep(100);
- } catch(InterruptedException ie) {
-
- }
- rt.interrupt();
- try {
- Thread.sleep(100);
- } catch(InterruptedException ie) {
-
- }
- assertTrue(isThrown);
- assertNull(rq.poll());
- }
-
- /**
- * @tests java.lang.ref.ReferenceQueue#remove(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {long.class}
- )
- public void test_removeJ() {
- try {
- assertNull("Queue should be empty. (poll)", rq.poll());
- assertNull("Queue should be empty. (remove(1))",
- rq.remove((long) 1));
- Thread ct = new Thread(new ChildThread());
- ct.start();
- Reference ret = rq.remove(0L);
- assertNotNull("Delayed remove failed.", ret);
- } catch (InterruptedException e) {
- fail("InterruptedExeException during test : " + e.getMessage());
- }
- catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
-
- Object obj = new Object();
- WeakReference wr = new WeakReference(obj, rq);
- Boolean b = new Boolean(true);
- SoftReference sr = new SoftReference(b, rq);
- String str = "Test";
- PhantomReference pr = new PhantomReference(str, rq);
-
- pr.enqueue();
- wr.enqueue();
- sr.enqueue();
-
- try {
- Reference result = rq.remove(1L);
- assertTrue((Boolean)result.get());
- result = rq.remove(1L);
- assertEquals(obj, result.get());
- result = rq.remove(1L);
- assertNull(result.get());
- } catch (IllegalArgumentException e1) {
- fail("IllegalArgumentException was thrown.");
- } catch (InterruptedException e1) {
- fail("InterruptedException was thrown.");
- }
- rq = new ReferenceQueue();
- isThrown = false;
- assertNull(rq.poll());
-
- class RemoveThread extends Thread {
- public void run() {
- try {
- rq.remove(1000L);
- } catch(InterruptedException ie) {
- isThrown = true;
- }
- }
- }
- RemoveThread rt = new RemoveThread();
- rt.start();
- try {
- Thread.sleep(10);
- } catch(InterruptedException ie) {
-
- }
- rt.interrupt();
- try {
- Thread.sleep(10);
- } catch(InterruptedException ie) {
-
- }
- assertTrue(isThrown);
- assertNull(rq.poll());
-
- try {
- rq.remove(-1);
- fail("IllegalArgumentException expected.");
- } catch(IllegalArgumentException iae) {
- //expected
- } catch (InterruptedException e) {
- fail("Unexpected InterruptedException.");
- }
- }
-
- /**
- * @tests java.lang.ref.ReferenceQueue#ReferenceQueue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ReferenceQueue",
- args = {}
- )
- public void test_Constructor() {
- ReferenceQueue rq = new ReferenceQueue();
- assertNull(rq.poll());
- try {
- rq.remove(100L);
- } catch (InterruptedException e) {
- fail("InterruptedException was thrown.");
- }
- }
-
- protected void setUp() {
- rq = new ReferenceQueue();
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/ref/ReferenceTest.java b/luni/src/test/java/tests/api/java/lang/ref/ReferenceTest.java
deleted file mode 100644
index 68284ef..0000000
--- a/luni/src/test/java/tests/api/java/lang/ref/ReferenceTest.java
+++ /dev/null
@@ -1,461 +0,0 @@
-/*
- * 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 tests.api.java.lang.ref;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.AssertionFailedError;
-
-import java.lang.ref.PhantomReference;
-import java.lang.ref.Reference;
-import java.lang.ref.ReferenceQueue;
-import java.lang.ref.SoftReference;
-import java.lang.ref.WeakReference;
-import java.util.Vector;
-
-@TestTargetClass(Reference.class)
-public class ReferenceTest extends junit.framework.TestCase {
- Object tmpA, tmpB, tmpC, obj;
-
- volatile Reference r;
-
- /*
- * For test_subclass().
- */
- static TestWeakReference twr;
- static AssertionFailedError error;
- static boolean testObjectFinalized;
- static class TestWeakReference<T> extends WeakReference<T> {
- public volatile boolean clearSeen = false;
- public volatile boolean enqueueSeen = false;
-
- public TestWeakReference(T referent) {
- super(referent);
- }
-
- public TestWeakReference(T referent, ReferenceQueue<? super T> q) {
- super(referent, q);
- }
-
- public void clear() {
- clearSeen = true;
- if (testObjectFinalized) {
- error = new AssertionFailedError("Clear should happen " +
- "before finalization.");
- throw error;
- }
- if (enqueueSeen) {
- error = new AssertionFailedError("Clear should happen " +
- "before enqueue.");
- throw error;
- }
- super.clear();
- }
-
- public boolean enqueue() {
- enqueueSeen = true;
- if (!clearSeen) {
- error = new AssertionFailedError("Clear should happen " +
- "before enqueue.");
- throw error;
- }
-
- /* Do this last; it may notify the main test thread,
- * and anything we'd do after it (e.g., setting clearSeen)
- * wouldn't be seen.
- */
- return super.enqueue();
- }
- }
-
- protected void doneSuite() {
- tmpA = tmpB = obj = null;
- }
-
- /**
- * @tests java.lang.ref.Reference#clear()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- tmpA = new Object();
- tmpB = new Object();
- tmpC = new Object();
- SoftReference sr = new SoftReference(tmpA, new ReferenceQueue());
- WeakReference wr = new WeakReference(tmpB, new ReferenceQueue());
- PhantomReference pr = new PhantomReference(tmpC, new ReferenceQueue());
- assertTrue("Start: Object not cleared.", (sr.get() != null)
- && (wr.get() != null));
- assertNull("Referent is not null.", pr.get());
- sr.clear();
- wr.clear();
- pr.clear();
- assertTrue("End: Object cleared.", (sr.get() == null)
- && (wr.get() == null));
- assertNull("Referent is not null.", pr.get());
- // Must reference tmpA and tmpB so the jit does not optimize them away
- assertTrue("should always pass", tmpA != sr.get() && tmpB != wr.get());
- }
-
- /**
- * @tests java.lang.ref.Reference#enqueue()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "enqueue",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isEnqueued",
- args = {}
- )
- })
- public void test_enqueue() {
- ReferenceQueue rq = new ReferenceQueue();
- obj = new Object();
- Reference ref = new SoftReference(obj, rq);
- assertTrue("Enqueue failed.", (!ref.isEnqueued())
- && ((ref.enqueue()) && (ref.isEnqueued())));
- assertTrue("Not properly enqueued.", rq.poll().get() == obj);
- // This fails...
- assertTrue("Should remain enqueued.", !ref.isEnqueued());
- assertTrue("Can not enqueue twice.", (!ref.enqueue())
- && (rq.poll() == null));
-
- rq = new ReferenceQueue();
- obj = new Object();
-
- ref = new WeakReference(obj, rq);
- assertTrue("Enqueue failed2.", (!ref.isEnqueued())
- && ((ref.enqueue()) && (ref.isEnqueued())));
- assertTrue("Not properly enqueued2.", rq.poll().get() == obj);
- assertTrue("Should remain enqueued2.", !ref.isEnqueued()); // This
- // fails.
- assertTrue("Can not enqueue twice2.", (!ref.enqueue())
- && (rq.poll() == null));
-
- ref = new PhantomReference(obj, rq);
- assertTrue("Enqueue failed3.", (!ref.isEnqueued())
- && ((ref.enqueue()) && (ref.isEnqueued())));
- assertNull("Not properly enqueued3.", rq.poll().get());
- assertTrue("Should remain enqueued3.", !ref.isEnqueued()); // This
- // fails.
- assertTrue("Can not enqueue twice3.", (!ref.enqueue())
- && (rq.poll() == null));
- }
-
- /**
- * @tests java.lang.ref.Reference#enqueue()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies positive functionality for WeakReference.",
- method = "get",
- args = {}
- )
- public void test_get_WeakReference() {
- // Test the general/overall functionality of Reference.
-
- class TestObject {
- public boolean finalized;
-
- public TestObject() {
- finalized = false;
- }
-
- protected void finalize() {
- finalized = true;
- }
- }
-
- final ReferenceQueue rq = new ReferenceQueue();
-
- class TestThread extends Thread {
-
- public void run() {
- // Create the object in a separate thread to ensure it will be
- // gc'ed
- Object testObj = new TestObject();
- r = new WeakReference(testObj, rq);
- testObj = null;
- }
- }
-
- Reference ref;
-
- try {
- TestThread t = new TestThread();
- t.start();
- t.join();
- System.gc();
- System.runFinalization();
- ref = rq.remove();
- assertNotNull("Object not garbage collected1.", ref);
- assertTrue("Unexpected ref1", ref == r);
- assertNull("Object could not be reclaimed1.", r.get());
- } catch (InterruptedException e) {
- fail("InterruptedException : " + e.getMessage());
- }
-
- try {
- TestThread t = new TestThread();
- t.start();
- t.join();
- System.gc();
- System.runFinalization();
- ref = rq.poll();
- assertNotNull("Object not garbage collected.", ref);
- assertTrue("Unexpected ref2", ref == r);
- assertNull("Object could not be reclaimed.", ref.get());
- // Reference wr so it does not get collected
- assertNull("Object could not be reclaimed.", r.get());
- } catch (Exception e) {
- fail("Exception : " + e.getMessage());
- }
- }
-
-
- /**
- * Makes sure that overridden versions of clear() and enqueue()
- * get called, and that clear/enqueue/finalize happen in the
- * right order for WeakReferences.
- *
- * @tests java.lang.ref.Reference#clear()
- * @tests java.lang.ref.Reference#enqueue()
- * @tests java.lang.Object#finalize()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Makes sure that overridden versions of clear() and enqueue() " +
- "get called, and that clear/enqueue/finalize happen in the " +
- "right order for WeakReferences.",
- method = "clear",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Makes sure that overridden versions of clear() and enqueue() " +
- "get called, and that clear/enqueue/finalize happen in the " +
- "right order for WeakReferences.",
- method = "enqueue",
- args = {}
- )
- })
- public void test_subclass() {
- error = null;
- testObjectFinalized = false;
- twr = null;
-
- class TestObject {
- public TestWeakReference testWeakReference = null;
-
- public void setTestWeakReference(TestWeakReference twr) {
- testWeakReference = twr;
- }
-
- protected void finalize() {
- testObjectFinalized = true;
- if (!testWeakReference.clearSeen) {
- error = new AssertionFailedError("Clear should happen " +
- "before finalize.");
- throw error;
- }
- }
- }
-
- final ReferenceQueue rq = new ReferenceQueue();
-
- class TestThread extends Thread {
- public void run() {
- // Create the object in a separate thread to ensure it will be
- // gc'ed
- TestObject testObj = new TestObject();
- twr = new TestWeakReference(testObj, rq);
- testObj.setTestWeakReference(twr);
- testObj = null;
- }
- }
-
- Reference ref;
-
- try {
- Thread t = new TestThread();
- t.start();
- t.join();
- System.gc();
- System.runFinalization();
- ref = rq.remove(5000L); // Give up after five seconds.
-
- assertNotNull("Object not garbage collected.", ref);
- assertTrue("Unexpected reference.", ref == twr);
- assertNull("Object could not be reclaimed.", twr.get());
- //assertTrue("Overridden clear() should have been called.",
- // twr.clearSeen);
- //assertTrue("Overridden enqueue() should have been called.",
- // twr.enqueueSeen);
- assertTrue("finalize() should have been called.",
- testObjectFinalized);
- } catch (InterruptedException e) {
- fail("InterruptedException : " + e.getMessage());
- }
-
- }
-
- /**
- * @tests java.lang.ref.Reference#get()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't check that get() can return null.",
- method = "get",
- args = {}
- )
- public void test_get() {
-
- Vector<StringBuffer> vec = new Vector<StringBuffer>();
- WeakReference ref = new WeakReference(vec, new ReferenceQueue());
- assertTrue("Get succeeded.", ref.get() == vec);
-
- Runtime rt = Runtime.getRuntime();
-
- long beforeTest = rt.freeMemory();
- while(rt.freeMemory() < beforeTest * 2/3) {
- vec.add(new StringBuffer(1000));
- }
- vec = null;
-
- System.gc();
- System.runFinalization();
- assertNull("get() doesn't return null after gc for WeakReference",
- ref.get());
-
- obj = new Object();
- ref = new WeakReference(obj, new ReferenceQueue());
- ref.clear();
- assertNull("get() doesn't return null after clear for WeakReference",
- ref.get());
- }
-
- /**
- * @tests java.lang.ref.Reference#isEnqueued()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isEnqueued",
- args = {}
- )
- public void test_isEnqueued() {
- ReferenceQueue rq = new ReferenceQueue();
- obj = new Object();
- Reference ref = new SoftReference(obj, rq);
- assertTrue("Should start off not enqueued.", !ref.isEnqueued());
- ref.enqueue();
- assertTrue("Should now be enqueued.", ref.isEnqueued());
- ref.enqueue();
- assertTrue("Should still be enqueued.", ref.isEnqueued());
- rq.poll();
- // This fails ...
- assertTrue("Should now be not enqueued.", !ref.isEnqueued());
- }
-
- /* Contrives a situation where the only reference to a string
- * is a WeakReference from an object that is being finalized.
- * Checks to make sure that the referent of the WeakReference
- * is still pointing to a valid object.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Contrives a situation where the only reference to a string " +
- "is a WeakReference from an object that is being finalized. " +
- "Checks to make sure that the referent of the WeakReference " +
- "is still pointing to a valid object.",
- method = "get",
- args = {}
- )
- public void test_finalizeReferenceInteraction() {
- error = null;
- testObjectFinalized = false;
-
- class TestObject {
- WeakReference<String> stringRef;
-
- public TestObject(String referent) {
- stringRef = new WeakReference<String>(referent);
- }
-
- protected void finalize() {
- try {
- /* If a VM bug has caused the referent to get
- * freed without the reference getting cleared,
- * looking it up, assigning it to a local and
- * doing a GC should cause some sort of exception.
- */
- String s = stringRef.get();
- System.gc();
- testObjectFinalized = true;
- } catch (Throwable t) {
- error = new AssertionFailedError("something threw '" + t +
- "' in finalize()");
- }
- }
- }
-
- class TestThread extends Thread {
- public void run() {
- // Create the object in a separate thread to ensure it will be
- // gc'ed
- TestObject testObj = new TestObject(new String("sup /b/"));
- }
- }
-
- try {
- Thread t = new TestThread();
- t.start();
- t.join();
- System.gc();
- System.runFinalization();
- Thread.sleep(1000);
- if (error != null) {
- throw error;
- }
- assertTrue("finalize() should have been called.",
- testObjectFinalized);
- } catch (InterruptedException e) {
- fail("InterruptedException : " + e.getMessage());
- }
- }
-
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/ref/SoftReferenceTest.java b/luni/src/test/java/tests/api/java/lang/ref/SoftReferenceTest.java
deleted file mode 100644
index f2d3fbb..0000000
--- a/luni/src/test/java/tests/api/java/lang/ref/SoftReferenceTest.java
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * 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 tests.api.java.lang.ref;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.lang.ref.Reference;
-import java.lang.ref.ReferenceQueue;
-import java.lang.ref.SoftReference;
-import java.util.Vector;
-
-@TestTargetClass(SoftReference.class)
-public class SoftReferenceTest extends junit.framework.TestCase {
- static Boolean bool;
- SoftReference r;
-
- protected void doneSuite() {
- bool = null;
- }
-
- /**
- * @tests java.lang.ref.SoftReference#SoftReference(java.lang.Object,
- * java.lang.ref.ReferenceQueue)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SoftReference",
- args = {java.lang.Object.class, java.lang.ref.ReferenceQueue.class}
- )
- public void test_ConstructorLjava_lang_ObjectLjava_lang_ref_ReferenceQueue() {
- ReferenceQueue rq = new ReferenceQueue();
- bool = new Boolean(true);
- try {
- SoftReference sr = new SoftReference(bool, rq);
- assertTrue("Initialization failed.", ((Boolean) sr.get())
- .booleanValue());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
-
- boolean exception = false;
- try {
- new SoftReference(bool, null);
- } catch (NullPointerException e) {
- exception = true;
- }
- assertTrue("Should not throw NullPointerException", !exception);
- }
-
- /**
- * @tests java.lang.ref.SoftReference#SoftReference(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SoftReference",
- args = {java.lang.Object.class}
- )
- public void test_ConstructorLjava_lang_Object() {
- bool = new Boolean(true);
- try {
- SoftReference sr = new SoftReference(bool);
- assertTrue("Initialization failed.", ((Boolean) sr.get())
- .booleanValue());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.lang.ref.SoftReference#get()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Doesn't verified that get() can return null.",
- method = "get",
- args = {}
- )
- public void test_get() {
- bool = new Boolean(false);
- SoftReference sr = new SoftReference(bool);
- assertTrue("Same object not returned.", bool == sr.get());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {}
- )
- public void test_get_SoftReference() {
-
- class TestObject {
- public boolean finalized;
- public TestObject() {
- finalized = false;
- }
-
- protected void finalize() {
- finalized = true;
- }
- }
-
- final ReferenceQueue rq = new ReferenceQueue();
-
- class TestThread extends Thread {
- public void run() {
- Object testObj = new TestObject();
- r = new SoftReference(testObj, rq);
- }
- }
- Reference ref;
- try {
- TestThread t = new TestThread();
- t.start();
- t.join();
- Vector<StringBuffer> v = new Vector<StringBuffer>();
- try {
- while(true) {
- v.add(new StringBuffer(10000));
- }
- } catch(OutOfMemoryError ofme) {
- v = null;
- }
- } catch (InterruptedException e) {
- fail("InterruptedException : " + e.getMessage());
- }
-
- assertNull("get() should return null " +
- "if OutOfMemoryError is thrown.", r.get());
-
- try {
- TestThread t = new TestThread();
- t.start();
- t.join();
- System.gc();
- System.runFinalization();
- ref = rq.poll();
- assertNotNull("Object not garbage collected.", ref);
- assertNull("Object is not null.", ref.get());
- assertNotNull("Object could not be reclaimed.", r.get());
- } catch (Exception e) {
- fail("Exception : " + e.getMessage());
- }
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/ref/WeakReferenceTest.java b/luni/src/test/java/tests/api/java/lang/ref/WeakReferenceTest.java
deleted file mode 100644
index 8bf5f49..0000000
--- a/luni/src/test/java/tests/api/java/lang/ref/WeakReferenceTest.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * 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 tests.api.java.lang.ref;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.lang.ref.ReferenceQueue;
-import java.lang.ref.WeakReference;
-
-@TestTargetClass(WeakReference.class)
-public class WeakReferenceTest extends junit.framework.TestCase {
- static Boolean bool;
-
- protected void doneSuite() {
- bool = null;
- }
-
- /**
- * @tests java.lang.ref.WeakReference#WeakReference(java.lang.Object,
- * java.lang.ref.ReferenceQueue)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "WeakReference",
- args = {java.lang.Object.class, java.lang.ref.ReferenceQueue.class}
- )
- public void test_ConstructorLjava_lang_ObjectLjava_lang_ref_ReferenceQueue() {
- ReferenceQueue rq = new ReferenceQueue();
- bool = new Boolean(true);
- try {
- // Allow the finalizer to run to potentially enqueue
- WeakReference wr = new WeakReference(bool, rq);
- assertTrue("Initialization failed.", ((Boolean) wr.get())
- .booleanValue());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- // need a reference to bool so the jit does not optimize it away
- assertTrue("should always pass", bool.booleanValue());
-
- boolean exception = false;
- try {
- new WeakReference(bool, null);
- } catch (NullPointerException e) {
- exception = true;
- }
- assertTrue("Should not throw NullPointerException", !exception);
- }
-
- /**
- * @tests java.lang.ref.WeakReference#WeakReference(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "WeakReference",
- args = {java.lang.Object.class}
- )
- public void test_ConstructorLjava_lang_Object() {
- bool = new Boolean(true);
- try {
- WeakReference wr = new WeakReference(bool);
- // Allow the finalizer to run to potentially enqueue
- Thread.sleep(1000);
- assertTrue("Initialization failed.", ((Boolean) wr.get())
- .booleanValue());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- // need a reference to bool so the jit does not optimize it away
- assertTrue("should always pass", bool.booleanValue());
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/AccessibleObjectTest.java b/luni/src/test/java/tests/api/java/lang/reflect/AccessibleObjectTest.java
deleted file mode 100644
index f1c7026..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/AccessibleObjectTest.java
+++ /dev/null
@@ -1,269 +0,0 @@
-/*
- * 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 tests.api.java.lang.reflect;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.lang.annotation.Annotation;
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Inherited;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-import java.lang.reflect.AccessibleObject;
-import java.lang.reflect.Modifier;
-import java.util.HashSet;
-import java.util.Set;
-
-@TestTargetClass(AccessibleObject.class)
-public class AccessibleObjectTest extends junit.framework.TestCase {
-
- public class TestClass {
- public Object aField;
-
- @InheritedRuntime
- public void annotatedMethod(){}
- }
-
- public class SubTestClass extends TestClass{
- @AnnotationRuntime0
- @AnnotationRuntime1
- @AnnotationClass0
- @AnnotationSource0
- public void annotatedMethod(){}
- }
-
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target( {ElementType.METHOD})
- static @interface AnnotationRuntime0 {
- }
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target( { ElementType.METHOD})
- static @interface AnnotationRuntime1 {
- }
-
- @Retention(RetentionPolicy.CLASS)
- @Target( { ElementType.METHOD})
- static @interface AnnotationClass0 {
- }
-
- @Retention(RetentionPolicy.SOURCE)
- @Target( {ElementType.METHOD})
- static @interface AnnotationSource0 {
- }
-
- @Inherited
- @Retention(RetentionPolicy.RUNTIME)
- @Target( {ElementType.METHOD})
- static @interface InheritedRuntime {
- }
-
- //used for constructor test
- private static class MyAccessibleObject extends AccessibleObject{
- public MyAccessibleObject() {
- super();
- }
- }
-
- /**
- * @tests java.lang.reflect.AccessibleObject#AccessibleObject()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "The only thing I can do",
- method = "AccessibleObject",
- args = {}
- )
- public void test_Constructor() {
- assertNotNull(new MyAccessibleObject());
- }
-
- /**
- * @tests java.lang.reflect.AccessibleObject#isAccessible()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isAccessible",
- args = {}
- )
- public void test_isAccessible() {
- // Test for method boolean
- // java.lang.reflect.AccessibleObject.isAccessible()
- try {
- AccessibleObject ao = TestClass.class.getField("aField");
- ao.setAccessible(true);
- assertTrue("Returned false to isAccessible", ao.isAccessible());
- ao.setAccessible(false);
- assertTrue("Returned true to isAccessible", !ao.isAccessible());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.lang.reflect.AccessibleObject#setAccessible(java.lang.reflect.AccessibleObject[],
- * boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "SecurityExeption is tested in tests.security.permissions.JavaLangReflectAccessibleObjectTest",
- method = "setAccessible",
- args = {java.lang.reflect.AccessibleObject[].class, boolean.class}
- )
- public void test_setAccessible$Ljava_lang_reflect_AccessibleObjectZ() {
- try {
- AccessibleObject ao = TestClass.class.getField("aField");
- AccessibleObject[] aoa = new AccessibleObject[] { ao };
- AccessibleObject.setAccessible(aoa, true);
- assertTrue("Returned false to isAccessible", ao.isAccessible());
- AccessibleObject.setAccessible(aoa, false);
- assertTrue("Returned true to isAccessible", !ao.isAccessible());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.lang.reflect.AccessibleObject#setAccessible(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "SecurityExeption is tested in tests.security.permissions.JavaLangReflectAccessibleObjectTest",
- method = "setAccessible",
- args = {boolean.class}
- )
- public void test_setAccessible() throws Exception {
- AccessibleObject ao = TestClass.class.getField("aField");
- ao.setAccessible(true);
- assertTrue("Returned false to isAccessible", ao.isAccessible());
- ao.setAccessible(false);
- assertFalse("Returned true to isAccessible", ao.isAccessible());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAnnotation",
- args = {java.lang.Class.class}
- )
- public void test_getAnnotation() throws Exception{
- AccessibleObject ao = SubTestClass.class.getMethod("annotatedMethod");
- //test error case
- boolean npeThrown = false;
- try {
- ao.getAnnotation(null);
- fail("NPE expected");
- } catch (NullPointerException e) {
- npeThrown = true;
- }
- assertTrue("NPE expected", npeThrown);
-
- //test inherited on method has no effect
- InheritedRuntime ir = ao.getAnnotation(InheritedRuntime.class);
- assertNull("Inherited Annotations should have no effect", ir);
-
- //test ordinary runtime annotation
- AnnotationRuntime0 rt0 = ao.getAnnotation(AnnotationRuntime0.class);
- assertNotNull("AnnotationRuntime0 instance expected", rt0);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAnnotations",
- args = {}
- )
- public void test_getAnnotations() throws Exception {
- AccessibleObject ao = SubTestClass.class.getMethod("annotatedMethod");
- Annotation[] annotations = ao.getAnnotations();
- assertEquals(2, annotations.length);
-
- Set<Class<?>> ignoreOrder = new HashSet<Class<?>>();
- ignoreOrder.add(annotations[0].annotationType());
- ignoreOrder.add(annotations[1].annotationType());
-
- assertTrue("Missing @AnnotationRuntime0",
- ignoreOrder.contains(AnnotationRuntime0.class));
- assertTrue("Missing @AnnotationRuntime1",
- ignoreOrder.contains(AnnotationRuntime1.class));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaredAnnotations",
- args = {}
- )
- public void test_getDeclaredAnnotations() throws Exception {
- AccessibleObject ao = SubTestClass.class.getMethod("annotatedMethod");
- Annotation[] annotations = ao.getDeclaredAnnotations();
- assertEquals(2, annotations.length);
-
- Set<Class<?>> ignoreOrder = new HashSet<Class<?>>();
- ignoreOrder.add(annotations[0].annotationType());
- ignoreOrder.add(annotations[1].annotationType());
-
- assertTrue("Missing @AnnotationRuntime0",
- ignoreOrder.contains(AnnotationRuntime0.class));
- assertTrue("Missing @AnnotationRuntime1",
- ignoreOrder.contains(AnnotationRuntime1.class));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isAnnotationPresent",
- args = {java.lang.Class.class}
- )
- public void test_isAnnotationPresent() throws Exception {
- AccessibleObject ao = SubTestClass.class.getMethod("annotatedMethod");
- assertTrue("Missing @AnnotationRuntime0",
- ao.isAnnotationPresent(AnnotationRuntime0.class));
- assertFalse("AnnotationSource0 should not be visible at runtime",
- ao.isAnnotationPresent(AnnotationSource0.class));
- boolean npeThrown = false;
- try {
- ao.isAnnotationPresent(null);
- fail("NPE expected");
- } catch (NullPointerException e) {
- npeThrown = true;
- }
- assertTrue("NPE expected", npeThrown);
- }
-
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/AllTests.java b/luni/src/test/java/tests/api/java/lang/reflect/AllTests.java
deleted file mode 100644
index bba0915..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/AllTests.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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 tests.api.java.lang.reflect;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-/**
- * TODO Type description
- */
-public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(AllTests.suite());
- }
-
- public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Test for java.lang.reflect");
-
- // $JUnit-BEGIN$
- suite.addTestSuite(AccessibleObjectTest.class);
- suite.addTestSuite(ArrayTest.class);
- suite.addTestSuite(ConstructorTest.class);
- suite.addTestSuite(FieldTest.class);
- suite.addTestSuite(InvocationTargetExceptionTest.class);
- suite.addTestSuite(MalformedParameterizedTypeExceptionTests.class);
- suite.addTestSuite(UndeclaredThrowableExceptionTests.class);
- suite.addTestSuite(MethodTest.class);
- suite.addTestSuite(ModifierTest.class);
- suite.addTestSuite(ProxyTest.class);
- suite.addTestSuite(ReflectPermissionTest.class);
- suite.addTestSuite(GenericArrayTypeTest.class);
- suite.addTestSuite(TypeVariableTest.class);
- suite.addTestSuite(ParameterizedTypeTest.class);
- suite.addTestSuite(BoundedGenericMethodsTests.class);
- suite.addTestSuite(GenericMethodsTests.class);
- suite.addTestSuite(WildcardTypeTest.class);
- suite.addTestSuite(GenericTypesTest.class);
- suite.addTestSuite(GenericReflectionCornerCases.class);
- suite.addTestSuite(GenericSignatureFormatErrorTest.class);
- // $JUnit-END$
-
- return suite;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/ArrayTest.java b/luni/src/test/java/tests/api/java/lang/reflect/ArrayTest.java
deleted file mode 100644
index 04dbb2b..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/ArrayTest.java
+++ /dev/null
@@ -1,1133 +0,0 @@
-/*
- * 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 tests.api.java.lang.reflect;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.lang.reflect.Array;
-
-@TestTargetClass(Array.class)
-public class ArrayTest extends junit.framework.TestCase {
-
- /**
- * @tests java.lang.reflect.Array#get(java.lang.Object, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {java.lang.Object.class, int.class}
- )
- public void test_getLjava_lang_ObjectI() {
- // Test for method java.lang.Object
- // java.lang.reflect.Array.get(java.lang.Object, int)
-
- int[] x = { 1 };
- Object ret = null;
- boolean thrown = false;
- try {
- ret = Array.get(x, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value",
- 1, ((Integer) ret).intValue());
- try {
- ret = Array.get(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.get(x, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- //same test with non primitive component type
- Integer[] y = new Integer[]{ 1 };
- ret = null;
- thrown = false;
- try {
- ret = Array.get(y, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value",
- 1, ((Integer) ret).intValue());
- try {
- ret = Array.get(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.get(y, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
- }
-
- /**
- * @tests java.lang.reflect.Array#getBoolean(java.lang.Object, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBoolean",
- args = {java.lang.Object.class, int.class}
- )
- public void test_getBooleanLjava_lang_ObjectI() {
- // Test for method boolean
- // java.lang.reflect.Array.getBoolean(java.lang.Object, int)
- boolean[] x = { true };
- boolean ret = false;
- boolean thrown = false;
- try {
- ret = Array.getBoolean(x, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertTrue("Get returned incorrect value", ret);
- try {
- ret = Array.getBoolean(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getBoolean(x, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getBoolean(null, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * @tests java.lang.reflect.Array#getByte(java.lang.Object, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getByte",
- args = {java.lang.Object.class, int.class}
- )
- public void test_getByteLjava_lang_ObjectI() {
- // Test for method byte
- // java.lang.reflect.Array.getByte(java.lang.Object, int)
- byte[] x = { 1 };
- byte ret = 0;
- boolean thrown = false;
- try {
- ret = Array.getByte(x, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, ret);
- try {
- ret = Array.getByte(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getByte(x, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getByte(null, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * @tests java.lang.reflect.Array#getChar(java.lang.Object, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getChar",
- args = {java.lang.Object.class, int.class}
- )
- public void test_getCharLjava_lang_ObjectI() {
- // Test for method char
- // java.lang.reflect.Array.getChar(java.lang.Object, int)
- char[] x = { 1 };
- char ret = 0;
- boolean thrown = false;
- try {
- ret = Array.getChar(x, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, ret);
- try {
- ret = Array.getChar(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getChar(x, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getChar(null, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * @tests java.lang.reflect.Array#getDouble(java.lang.Object, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDouble",
- args = {java.lang.Object.class, int.class}
- )
- public void test_getDoubleLjava_lang_ObjectI() {
- // Test for method double
- // java.lang.reflect.Array.getDouble(java.lang.Object, int)
- double[] x = { 1 };
- double ret = 0;
- boolean thrown = false;
- try {
- ret = Array.getDouble(x, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, ret, 0.0);
- try {
- ret = Array.getDouble(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
-
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getDouble(x, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getDouble(null, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * @tests java.lang.reflect.Array#getFloat(java.lang.Object, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFloat",
- args = {java.lang.Object.class, int.class}
- )
- public void test_getFloatLjava_lang_ObjectI() {
- // Test for method float
- // java.lang.reflect.Array.getFloat(java.lang.Object, int)
- float[] x = { 1 };
- float ret = 0;
- boolean thrown = false;
- try {
- ret = Array.getFloat(x, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, ret, 0.0);
- try {
- ret = Array.getFloat(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getFloat(x, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getFloat(null, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * @tests java.lang.reflect.Array#getInt(java.lang.Object, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInt",
- args = {java.lang.Object.class, int.class}
- )
- public void test_getIntLjava_lang_ObjectI() {
- // Test for method int java.lang.reflect.Array.getInt(java.lang.Object,
- // int)
- int[] x = { 1 };
- int ret = 0;
- boolean thrown = false;
- try {
- ret = Array.getInt(x, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, ret);
- try {
- ret = Array.getInt(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getInt(x, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getInt(null, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * @tests java.lang.reflect.Array#getLength(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLength",
- args = {java.lang.Object.class}
- )
- public void test_getLengthLjava_lang_Object() {
- // Test for method int
- // java.lang.reflect.Array.getLength(java.lang.Object)
- long[] x = { 1 };
-
- assertEquals("Returned incorrect length", 1, Array.getLength(x));
- assertEquals("Returned incorrect length", 10000, Array
- .getLength(new Object[10000]));
- try {
- Array.getLength(new Object());
- } catch (IllegalArgumentException e) {
- // Correct
- return;
- }
- fail("Failed to throw exception when passed non-array");
- }
-
- /**
- * @tests java.lang.reflect.Array#getLong(java.lang.Object, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLong",
- args = {java.lang.Object.class, int.class}
- )
- public void test_getLongLjava_lang_ObjectI() {
- // Test for method long
- // java.lang.reflect.Array.getLong(java.lang.Object, int)
- long[] x = { 1 };
- long ret = 0;
- boolean thrown = false;
- try {
- ret = Array.getLong(x, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, ret);
- try {
- ret = Array.getLong(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getLong(x, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getLong(null, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * @tests java.lang.reflect.Array#getShort(java.lang.Object, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getShort",
- args = {java.lang.Object.class, int.class}
- )
- public void test_getShortLjava_lang_ObjectI() {
- // Test for method short
- // java.lang.reflect.Array.getShort(java.lang.Object, int)
- short[] x = { 1 };
- short ret = 0;
- boolean thrown = false;
- try {
- ret = Array.getShort(x, 0);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, ret);
- try {
- ret = Array.getShort(new Object(), 0);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getShort(x, 4);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
- thrown = false;
- try {
- ret = Array.getShort(null, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * @tests java.lang.reflect.Array#newInstance(java.lang.Class, int[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "newInstance",
- args = {java.lang.Class.class, int[].class}
- )
- public void test_newInstanceLjava_lang_Class$I() {
- // Test for method java.lang.Object
- // java.lang.reflect.Array.newInstance(java.lang.Class, int [])
- int[][] x;
- int[] y = { 2 };
-
- x = (int[][]) Array.newInstance(int[].class, y);
- assertEquals("Failed to instantiate array properly", 2, x.length);
-
- boolean thrown = false;
- try {
- x = (int[][]) Array.newInstance(null, y);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
-
- thrown = false;
- try {
- Array.newInstance(int[].class, new int[]{1,-1});
- } catch (NegativeArraySizeException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Negative array size failed to throw NegativeArraySizeException");
- }
-
- thrown = false;
- try {
- Array.newInstance(int[].class, new int[]{});
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Zero array size failed to throw IllegalArgumentException");
- }
- }
-
- /**
- * @tests java.lang.reflect.Array#newInstance(java.lang.Class, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "newInstance",
- args = {java.lang.Class.class, int.class}
- )
- public void test_newInstanceLjava_lang_ClassI() {
- // Test for method java.lang.Object
- // java.lang.reflect.Array.newInstance(java.lang.Class, int)
- int[] x;
-
- x = (int[]) Array.newInstance(int.class, 100);
- assertEquals("Failed to instantiate array properly", 100, x.length);
-
- boolean thrown = false;
- try {
- Array.newInstance(null, 100);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
-
- thrown = false;
- try {
- Array.newInstance(int[].class, -1);
- } catch (NegativeArraySizeException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Negative array size failed to throw NegativeArraySizeException");
- }
- }
-
- /**
- * @tests java.lang.reflect.Array#set(java.lang.Object, int,
- * java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "set",
- args = {java.lang.Object.class, int.class, java.lang.Object.class}
- )
- public void test_setLjava_lang_ObjectILjava_lang_Object() {
- // Test for method void java.lang.reflect.Array.set(java.lang.Object,
- // int, java.lang.Object)
- int[] x = { 0 };
- boolean thrown = false;
- try {
- Array.set(x, 0, new Integer(1));
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, ((Integer) Array.get(x, 0))
- .intValue());
- try {
- Array.set(new Object(), 0, new Object());
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- Array.set(x, 4, new Integer(1));
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- // trying to put null in a primitive array causes
- // a IllegalArgumentException in 5.0
- boolean exception = false;
- try {
- Array.set(new int[1], 0, null);
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue("expected exception not thrown", exception);
-
- thrown = false;
- try {
- Array.set(null, 0, 2);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * @tests java.lang.reflect.Array#setBoolean(java.lang.Object, int, boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setBoolean",
- args = {java.lang.Object.class, int.class, boolean.class}
- )
- public void test_setBooleanLjava_lang_ObjectIZ() {
- // Test for method void
- // java.lang.reflect.Array.setBoolean(java.lang.Object, int, boolean)
- boolean[] x = { false };
- boolean thrown = false;
- try {
- Array.setBoolean(x, 0, true);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertTrue("Failed to set correct value", Array.getBoolean(x, 0));
- try {
- Array.setBoolean(new Object(), 0, false);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown){
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- Array.setBoolean(x, 4, false);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- thrown = false;
- try {
- Array.setBoolean(null, 0, true);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * @tests java.lang.reflect.Array#setByte(java.lang.Object, int, byte)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setByte",
- args = {java.lang.Object.class, int.class, byte.class}
- )
- public void test_setByteLjava_lang_ObjectIB() {
- // Test for method void
- // java.lang.reflect.Array.setByte(java.lang.Object, int, byte)
- byte[] x = { 0 };
- boolean thrown = false;
- try {
- Array.setByte(x, 0, (byte) 1);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, Array.getByte(x, 0));
- try {
- Array.setByte(new Object(), 0, (byte) 9);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- Array.setByte(x, 4, (byte) 9);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- thrown = false;
- try {
- Array.setByte(null, 0, (byte)0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * @tests java.lang.reflect.Array#setChar(java.lang.Object, int, char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setChar",
- args = {java.lang.Object.class, int.class, char.class}
- )
- public void test_setCharLjava_lang_ObjectIC() {
- // Test for method void
- // java.lang.reflect.Array.setChar(java.lang.Object, int, char)
- char[] x = { 0 };
- boolean thrown = false;
- try {
- Array.setChar(x, 0, (char) 1);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, Array.getChar(x, 0));
- try {
- Array.setChar(new Object(), 0, (char) 9);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- Array.setChar(x, 4, (char) 9);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- thrown = false;
- try {
- Array.setChar(null, 0, (char)0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * @tests java.lang.reflect.Array#setDouble(java.lang.Object, int, double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setDouble",
- args = {java.lang.Object.class, int.class, double.class}
- )
- public void test_setDoubleLjava_lang_ObjectID() {
- // Test for method void
- // java.lang.reflect.Array.setDouble(java.lang.Object, int, double)
- double[] x = { 0 };
- boolean thrown = false;
- try {
- Array.setDouble(x, 0, 1);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, Array.getDouble(x, 0), 0.0);
- try {
- Array.setDouble(new Object(), 0, 9);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- Array.setDouble(x, 4, 9);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- thrown = false;
- try {
- Array.setDouble(null, 0, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * @tests java.lang.reflect.Array#setFloat(java.lang.Object, int, float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setFloat",
- args = {java.lang.Object.class, int.class, float.class}
- )
- public void test_setFloatLjava_lang_ObjectIF() {
- // Test for method void
- // java.lang.reflect.Array.setFloat(java.lang.Object, int, float)
- float[] x = { 0.0f };
- boolean thrown = false;
- try {
- Array.setFloat(x, 0, (float) 1);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, Array.getFloat(x, 0), 0.0);
- try {
- Array.setFloat(new Object(), 0, (float) 9);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- Array.setFloat(x, 4, (float) 9);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- thrown = false;
- try {
- Array.setFloat(null, 0, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * @tests java.lang.reflect.Array#setInt(java.lang.Object, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setInt",
- args = {java.lang.Object.class, int.class, int.class}
- )
- public void test_setIntLjava_lang_ObjectII() {
- // Test for method void java.lang.reflect.Array.setInt(java.lang.Object,
- // int, int)
- int[] x = { 0 };
- boolean thrown = false;
- try {
- Array.setInt(x, 0, (int) 1);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, Array.getInt(x, 0));
- try {
- Array.setInt(new Object(), 0, (int) 9);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- Array.setInt(x, 4, (int) 9);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- thrown = false;
- try {
- Array.setInt(null, 0, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * @tests java.lang.reflect.Array#setLong(java.lang.Object, int, long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setLong",
- args = {java.lang.Object.class, int.class, long.class}
- )
- public void test_setLongLjava_lang_ObjectIJ() {
- // Test for method void
- // java.lang.reflect.Array.setLong(java.lang.Object, int, long)
- long[] x = { 0 };
- boolean thrown = false;
- try {
- Array.setLong(x, 0, 1);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, Array.getLong(x, 0));
- try {
- Array.setLong(new Object(), 0, 9);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- Array.setLong(x, 4, 9);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- thrown = false;
- try {
- Array.setLong(null, 0, 0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * @tests java.lang.reflect.Array#setShort(java.lang.Object, int, short)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setShort",
- args = {java.lang.Object.class, int.class, short.class}
- )
- public void test_setShortLjava_lang_ObjectIS() {
- // Test for method void
- // java.lang.reflect.Array.setShort(java.lang.Object, int, short)
- short[] x = { 0 };
- boolean thrown = false;
- try {
- Array.setShort(x, 0, (short) 1);
- } catch (Exception e) {
- fail("Exception during get test : " + e.getMessage());
- }
- assertEquals("Get returned incorrect value", 1, Array.getShort(x, 0));
- try {
- Array.setShort(new Object(), 0, (short) 9);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Passing non-array failed to throw exception");
- }
- thrown = false;
- try {
- Array.setShort(x, 4, (short) 9);
- } catch (ArrayIndexOutOfBoundsException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Invalid index failed to throw exception");
- }
-
- thrown = false;
- try {
- Array.setShort(null, 0, (short)0);
- } catch (NullPointerException e) {
- // Correct behaviour
- thrown = true;
- }
- if (!thrown) {
- fail("Null argument failed to throw NPE");
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/BoundedGenericMethodsTests.java b/luni/src/test/java/tests/api/java/lang/reflect/BoundedGenericMethodsTests.java
deleted file mode 100644
index 0a8ab0f..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/BoundedGenericMethodsTests.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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 tests.api.java.lang.reflect;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.lang.reflect.Method;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-
-/**
- * Tests bounded type parameters declared on methods.
- */
-@TestTargetClass(Method.class)
-public class BoundedGenericMethodsTests extends GenericReflectionTestsBase {
- @SuppressWarnings("unchecked")
- static class BoundedGenericMethods<S> {
-
- public <T extends BoundedGenericMethods> void noParamNoReturn() {}
- public <T extends BoundedGenericMethods> void paramNoReturn(T param) {}
-
- public <T extends BoundedGenericMethods> T noParamReturn() {
- return (T) new Object();
- }
- public <T extends BoundedGenericMethods> T paramReturn(T t) {
- return t;
- }
- }
- @SuppressWarnings("unchecked")
- private static Class<? extends BoundedGenericMethods> clazz = BoundedGenericMethodsTests.BoundedGenericMethods.class;
-
- /**
- * Tests whether the type parameter is upper bounded by BoundedGenericMethods.
- * <T extends BoundedGenericMethods>.
- *
- * @param method
- * the declaring method
- */
- private void checkBoundedTypeParameter(Method method) {
- TypeVariable<Method> typeParameter = getTypeParameter(method);
- assertEquals("T", typeParameter.getName());
- assertEquals(method, typeParameter.getGenericDeclaration());
-
- Type[] bounds = typeParameter.getBounds();
- assertLenghtOne(bounds);
- Type bound = bounds[0];
- assertEquals(BoundedGenericMethods.class, bound);
- }
-
- /**
- * Tests whether the specified method declares a parameter with the type of
- * the type parameter.
- *
- * @param method
- * the declaring method
- */
- private void parameterType(Method method) {
- TypeVariable<Method> typeParameter = getTypeParameter(method);
- assertLenghtOne(method.getGenericParameterTypes());
- Type genericParameterType = method.getGenericParameterTypes()[0];
- assertEquals(typeParameter, genericParameterType);
- assertTrue(genericParameterType instanceof TypeVariable);
- TypeVariable<?> typeVariable = (TypeVariable<?>) genericParameterType;
- assertEquals(method, typeVariable.getGenericDeclaration());
-
- Type[] paramBounds = typeVariable.getBounds();
- assertLenghtOne(paramBounds);
- Type paramBound = paramBounds[0];
- assertEquals(BoundedGenericMethods.class, paramBound);
- }
-
- @SuppressWarnings("unchecked")
- private void checkReturnType(Method method) {
- Type genericReturnType = method.getGenericReturnType();
- assertEquals(getTypeParameter(method), genericReturnType);
- assertTrue(genericReturnType instanceof TypeVariable);
-
- TypeVariable<Method> returnTypeVariable = (TypeVariable<Method>) genericReturnType;
- assertEquals(method, returnTypeVariable.getGenericDeclaration());
-
- Type[] bounds = returnTypeVariable.getBounds();
- assertLenghtOne(bounds);
- Type bound = bounds[0];
-
- assertEquals(BoundedGenericMethods.class, bound);
- }
-
-
-
- /**
- * Tests that there are is one Type Parameter on the Class itself.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Doesn't check GenericSignatureFormatError.",
- method = "getTypeParameters",
- args = {}
- )
- public void testBoundedGenericMethods() {
- assertLenghtOne(clazz.getTypeParameters());
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Doesn't check GenericSignatureFormatError.",
- method = "getTypeParameters",
- args = {}
- )
- public void testNoParamNoReturn() throws SecurityException, NoSuchMethodException {
- Method method = clazz.getMethod("noParamNoReturn");
- checkBoundedTypeParameter(method);
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Doesn't check GenericSignatureFormatError.",
- method = "getTypeParameters",
- args = {}
- )
- public void testUnboundedParamNoReturn() throws SecurityException, NoSuchMethodException {
- Method method = clazz.getMethod("paramNoReturn", BoundedGenericMethods.class);
- checkBoundedTypeParameter(method);
- parameterType(method);
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Doesn't check GenericSignatureFormatError.",
- method = "getTypeParameters",
- args = {}
- )
- public void testNoParamReturn() throws SecurityException, NoSuchMethodException {
- Method method = clazz.getMethod("noParamReturn");
- checkBoundedTypeParameter(method);
- assertLenghtZero(method.getGenericParameterTypes());
- checkReturnType(method);
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Doesn't check GenericSignatureFormatError.",
- method = "getTypeParameters",
- args = {}
- )
- public void testUnboundedParamReturn() throws SecurityException, NoSuchMethodException {
- Method method = clazz.getMethod("paramReturn", BoundedGenericMethods.class);
- checkBoundedTypeParameter(method);
- parameterType(method);
- checkReturnType(method);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/ConstructorTest.java b/luni/src/test/java/tests/api/java/lang/reflect/ConstructorTest.java
deleted file mode 100644
index 6bdb55a..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/ConstructorTest.java
+++ /dev/null
@@ -1,573 +0,0 @@
-/*
- * 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 tests.api.java.lang.reflect;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.lang.annotation.Annotation;
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Modifier;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-
-@TestTargetClass(
- value = Constructor.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- method = "isSynthetic",
- args = {},
- notes = "Since code which relies on synthetic members is not " +
- "portable, this should not be tested"
- )
- })
-public class ConstructorTest extends junit.framework.TestCase {
-
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER})
- static @interface ConstructorTestAnnotationRuntime0 {
- }
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER})
- static @interface ConstructorTestAnnotationRuntime1 {
- }
-
- @Retention(RetentionPolicy.CLASS)
- @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER})
- static @interface ConstructorTestAnnotationClass0 {
- }
-
- @Retention(RetentionPolicy.SOURCE)
- @Target( {ElementType.CONSTRUCTOR, ElementType.PARAMETER})
- static @interface ConstructorTestAnnotationSource0 {
- }
-
- static class ConstructorTestHelper extends Object {
- int cval;
-
- @ConstructorTestAnnotationRuntime0
- @ConstructorTestAnnotationRuntime1
- @ConstructorTestAnnotationClass0
- @ConstructorTestAnnotationSource0
- public ConstructorTestHelper() throws IndexOutOfBoundsException {
- cval = 99;
- }
-
- public ConstructorTestHelper(
- @ConstructorTestAnnotationRuntime0
- @ConstructorTestAnnotationRuntime1
- @ConstructorTestAnnotationClass0
- @ConstructorTestAnnotationSource0 Object x) {
- }
-
- public ConstructorTestHelper(String... x) {
- }
-
- private ConstructorTestHelper(int a) {
- }
-
- protected ConstructorTestHelper(long a) {
- }
-
- public int check() {
- return cval;
- }
- }
-
- static class GenericConstructorTestHelper<T, S extends T, E extends Exception> {
- public GenericConstructorTestHelper(T t, S s) {}
- public GenericConstructorTestHelper() throws E{}
- }
-
-// Used to test synthetic constructor.
-//
-// static class Outer {
-// private Outer(){}
-// class Inner {
-// {new Outer();}
-// }
-// }
-
- /**
- * @tests java.lang.reflect.Constructor#getDeclaredAnnotations()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getParameterAnnotations",
- args = {}
- )
- public void test_getParameterAnnotations() throws Exception {
- Constructor<ConstructorTestHelper> ctor1 = ConstructorTestHelper.class
- .getConstructor(Object.class);
- Annotation[][] paramAnnotations = ctor1.getParameterAnnotations();
- assertEquals("Annotations for wrong number of parameters returned", 1,
- paramAnnotations.length);
- assertEquals("Wrong number of annotations returned", 2,
- paramAnnotations[0].length);
-
- Set<Class<?>> ignoreOrder = new HashSet<Class<?>>();
- ignoreOrder.add(paramAnnotations[0][0].annotationType());
- ignoreOrder.add(paramAnnotations[0][1].annotationType());
-
- assertTrue("Missing ConstructorTestAnnotationRuntime0", ignoreOrder
- .contains(ConstructorTestAnnotationRuntime0.class));
- assertTrue("Missing ConstructorTestAnnotationRuntime1", ignoreOrder
- .contains(ConstructorTestAnnotationRuntime1.class));
- }
-
-
- /**
- * @tests java.lang.reflect.Constructor#getDeclaredAnnotations()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaredAnnotations",
- args = {}
- )
- public void test_getDeclaredAnnotations() throws Exception {
- Constructor<ConstructorTestHelper> ctor1 = null;
- ctor1 = ConstructorTestHelper.class.getConstructor(new Class[0]);
- Annotation[] annotations = ctor1.getDeclaredAnnotations();
- assertEquals("Wrong number of annotations returned", 2,
- annotations.length);
- Set<Class<?>> ignoreOrder = new HashSet<Class<?>>();
- ignoreOrder.add(annotations[0].annotationType());
- ignoreOrder.add(annotations[1].annotationType());
-
- assertTrue("Missing ConstructorTestAnnotationRuntime0", ignoreOrder
- .contains(ConstructorTestAnnotationRuntime0.class));
- assertTrue("Missing ConstructorTestAnnotationRuntime1", ignoreOrder
- .contains(ConstructorTestAnnotationRuntime1.class));
- }
-
- /**
- * @tests java.lang.reflect.Constructor#isVarargs()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isVarArgs",
- args = {}
- )
- public void test_isVarArgs() throws Exception {
- Constructor<ConstructorTestHelper> varArgCtor = ConstructorTestHelper.class
- .getConstructor(String[].class);
- assertTrue("Vararg constructor not recognized", varArgCtor.isVarArgs());
-
- Constructor<ConstructorTestHelper> nonVarArgCtor = ConstructorTestHelper.class
- .getConstructor(Object.class);
- assertFalse("Non vararg constructor recognized as vararg constructor",
- nonVarArgCtor.isVarArgs());
- }
-
- /**
- * @tests java.lang.reflect.Constructor#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() throws Exception {
- Constructor<ConstructorTestHelper> constructor = ConstructorTestHelper.class
- .getConstructor();
- assertEquals(
- "The constructor's hashCode is not equal to the hashCode of the name of the declaring class",
- ConstructorTestHelper.class.getName().hashCode(), constructor
- .hashCode());
- }
-
- /**
- * @tests java.lang.reflect.Constructor#toGenericString()
- */
- @SuppressWarnings("unchecked")
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toGenericString",
- args = {}
- )
- public void test_toGenericString() throws Exception {
- Constructor<GenericConstructorTestHelper> genericCtor = GenericConstructorTestHelper.class
- .getConstructor(Object.class, Object.class);
- assertEquals(
- "Wrong generic string returned",
- "public tests.api.java.lang.reflect.ConstructorTest$GenericConstructorTestHelper(T,S)",
- genericCtor.toGenericString());
- Constructor<GenericConstructorTestHelper> ctor = GenericConstructorTestHelper.class
- .getConstructor();
- assertEquals(
- "Wrong generic string returned",
- "public tests.api.java.lang.reflect.ConstructorTest$GenericConstructorTestHelper() throws E",
- ctor.toGenericString());
- }
-
- /**
- * @tests java.lang.reflect.Constructor#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- Constructor<ConstructorTestHelper> ctor1 = null, ctor2 = null;
- try {
- ctor1 = ConstructorTestHelper.class.getConstructor(
- new Class[0]);
- ctor2 = ConstructorTestHelper.class.getConstructor(Object.class);
- } catch (Exception e) {
- fail("Exception during equals test : " + e.getMessage());
- }
- assertTrue("Different Contructors returned equal", !ctor1.equals(ctor2));
- }
-
- /**
- * @tests java.lang.reflect.Constructor#getDeclaringClass()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaringClass",
- args = {}
- )
- public void test_getDeclaringClass() {
- boolean val = false;
- try {
- Class<? extends ConstructorTestHelper> pclass = new ConstructorTestHelper().getClass();
- Constructor<? extends ConstructorTestHelper> ctor = pclass.getConstructor(new Class[0]);
- val = ctor.getDeclaringClass().equals(pclass);
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- assertTrue("Returned incorrect declaring class", val);
- }
-
- /**
- * @tests java.lang.reflect.Constructor#getExceptionTypes()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getExceptionTypes",
- args = {}
- )
- public void test_getExceptionTypes() {
- // Test for method java.lang.Class []
- // java.lang.reflect.Constructor.getExceptionTypes()
- Class[] exceptions = null;
- Class<? extends IndexOutOfBoundsException> ex = null;
- try {
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
- .getConstructor(new Class[0]);
- exceptions = ctor.getExceptionTypes();
- ex = new IndexOutOfBoundsException().getClass();
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- assertEquals("Returned exception list of incorrect length",
- 1, exceptions.length);
- assertTrue("Returned incorrect exception", exceptions[0].equals(ex));
- }
-
- /**
- * @tests java.lang.reflect.Constructor#getModifiers()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getModifiers",
- args = {}
- )
- public void test_getModifiers() {
- // Test for method int java.lang.reflect.Constructor.getModifiers()
- int mod = 0;
- try {
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
- .getConstructor(new Class[0]);
- mod = ctor.getModifiers();
- assertTrue("Returned incorrect modifers for public ctor",
- ((mod & Modifier.PUBLIC) == Modifier.PUBLIC)
- && ((mod & Modifier.PRIVATE) == 0));
- } catch (NoSuchMethodException e) {
- fail("Exception during test : " + e.getMessage());
- }
- try {
- Class[] cl = { int.class };
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
- .getDeclaredConstructor(cl);
- mod = ctor.getModifiers();
- assertTrue("Returned incorrect modifers for private ctor",
- ((mod & Modifier.PRIVATE) == Modifier.PRIVATE)
- && ((mod & Modifier.PUBLIC) == 0));
- } catch (NoSuchMethodException e) {
- fail("Exception during test : " + e.getMessage());
- }
- try {
- Class[] cl = { long.class };
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
- .getDeclaredConstructor(cl);
- mod = ctor.getModifiers();
- assertTrue("Returned incorrect modifers for private ctor",
- ((mod & Modifier.PROTECTED) == Modifier.PROTECTED)
- && ((mod & Modifier.PUBLIC) == 0));
- } catch (NoSuchMethodException e) {
- fail("NoSuchMethodException during test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.lang.reflect.Constructor#getName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getName",
- args = {}
- )
- public void test_getName() {
- // Test for method java.lang.String
- // java.lang.reflect.Constructor.getName()
- try {
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
- .getConstructor(new Class[0]);
- assertTrue(
- "Returned incorrect name: " + ctor.getName(),
- ctor
- .getName()
- .equals(
- "tests.api.java.lang.reflect.ConstructorTest$ConstructorTestHelper"));
- } catch (Exception e) {
- fail("Exception obtaining contructor : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.lang.reflect.Constructor#getParameterTypes()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getParameterTypes",
- args = {}
- )
- public void test_getParameterTypes() {
- // Test for method java.lang.Class []
- // java.lang.reflect.Constructor.getParameterTypes()
- Class[] types = null;
- try {
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
- .getConstructor(new Class[0]);
- types = ctor.getParameterTypes();
- } catch (Exception e) {
- fail("Exception during getParameterTypes test:"
- + e.toString());
- }
- assertEquals("Incorrect parameter returned", 0, types.length);
-
- Class[] parms = null;
- try {
- parms = new Class[1];
- parms[0] = new Object().getClass();
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
- .getConstructor(parms);
- types = ctor.getParameterTypes();
- } catch (Exception e) {
- fail("Exception during getParameterTypes test:"
- + e.toString());
- }
- assertTrue("Incorrect parameter returned", types[0].equals(parms[0]));
- }
-
- /**
- * @tests java.lang.reflect.Constructor#getGenericParameterTypes()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getGenericParameterTypes",
- args = {}
- )
- @SuppressWarnings("unchecked")
- public void test_getGenericParameterTypes() {
- Type[] types = null;
- try {
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper()
- .getClass().getConstructor(new Class[0]);
- types = ctor.getGenericParameterTypes();
- } catch (Exception e) {
- fail("Exception during getParameterTypes test:" + e.toString());
- }
- assertEquals("Incorrect parameter returned", 0, types.length);
-
- Class<?>[] parms = null;
- try {
- parms = new Class[] {Object.class};
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper()
- .getClass().getConstructor(parms);
- types = ctor.getGenericParameterTypes();
- } catch (Exception e) {
- fail("Exception during getParameterTypes test:" + e.toString());
- }
- assertTrue("Incorrect parameter returned", types[0].equals(parms[0]));
-
-
- try {
- Constructor<GenericConstructorTestHelper> constructor = GenericConstructorTestHelper.class
- .getConstructor(Object.class, Object.class);
- types = constructor.getGenericParameterTypes();
- } catch (Exception e) {
- fail("Exception during getParameterTypes test:" + e.toString());
- }
-
- assertEquals("Wrong number of parameter types returned", 2,
- types.length);
-
- assertEquals("Wrong number of parameter types returned", "T",
- ((TypeVariable)types[0]).getName());
- assertEquals("Wrong number of parameter types returned", "S",
- ((TypeVariable)types[1]).getName());
- }
-
- /**
- * @tests java.lang.reflect.Constructor#getGenericParameterTypes()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getGenericExceptionTypes",
- args = {}
- )
- @SuppressWarnings("unchecked")
- public void test_getGenericExceptionTypes() {
- Type[] types = null;
-
- try {
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper()
- .getClass().getConstructor(new Class[0]);
- types = ctor.getGenericExceptionTypes();
- } catch (Exception e) {
- fail("Exception during getGenericExceptionTypes test:" + e.toString());
- }
- System.out.println(Arrays.toString(types));
- assertEquals("Wrong number of exception types returned", 1, types.length);
-
-
- try {
- Constructor<GenericConstructorTestHelper> constructor = GenericConstructorTestHelper.class
- .getConstructor();
- types = constructor.getGenericExceptionTypes();
- } catch (Exception e) {
- fail("Exception during getGenericExceptionTypes test:"
- + e.toString());
- }
-
- assertEquals("Wrong number of exception types returned", 1,
- types.length);
-
- assertEquals("Wrong exception name returned.", "E",
- ((TypeVariable)types[0]).getName());
-
- }
-
-
-
- /**
- * @tests java.lang.reflect.Constructor#newInstance(java.lang.Object[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "newInstance",
- args = {java.lang.Object[].class}
- )
- public void test_newInstance$Ljava_lang_Object() {
- // Test for method java.lang.Object
- // java.lang.reflect.Constructor.newInstance(java.lang.Object [])
-
- ConstructorTestHelper test = null;
- try {
- Constructor<? extends ConstructorTestHelper> ctor = new ConstructorTestHelper().getClass()
- .getConstructor(new Class[0]);
- test = ctor.newInstance((Object[])null);
- } catch (Exception e) {
- fail("Failed to create instance : " + e.getMessage());
- }
- assertEquals("improper instance created", 99, test.check());
- }
-
- /**
- * @tests java.lang.reflect.Constructor#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String
- // java.lang.reflect.Constructor.toString()
- Class[] parms = null;
- Constructor<? extends ConstructorTestHelper> ctor = null;
- try {
- parms = new Class[1];
- parms[0] = new Object().getClass();
- ctor = new ConstructorTestHelper().getClass().getConstructor(parms);
- } catch (Exception e) {
- fail("Exception during getParameterTypes test:"
- + e.toString());
- }
- assertTrue(
- "Returned incorrect string representation: " + ctor.toString(),
- ctor
- .toString()
- .equals(
- "public tests.api.java.lang.reflect.ConstructorTest$ConstructorTestHelper(java.lang.Object)"));
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
-
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/FieldTest.java b/luni/src/test/java/tests/api/java/lang/reflect/FieldTest.java
deleted file mode 100644
index 460cf66..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/FieldTest.java
+++ /dev/null
@@ -1,2157 +0,0 @@
-/*
- * 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 tests.api.java.lang.reflect;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-import tests.support.Support_Field;
-
-import java.lang.annotation.Annotation;
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Inherited;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-import java.util.HashSet;
-import java.util.Set;
-
-@TestTargetClass(Field.class)
-public class FieldTest extends junit.framework.TestCase {
-
- // BEGIN android-note
- // This test had a couple of bugs in it. Some parts of the code were
- // unreachable before. Also some tests expected the wrong excpetions
- // to be thrown. This version has been validated to pass on a standard
- // JDK 1.5.
- // END android-note
-
- public class TestClass {
- @AnnotationRuntime0
- @AnnotationRuntime1
- @AnnotationClass0
- @AnnotationSource0
- public int annotatedField;
- class Inner{}
- }
-
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target( {ElementType.FIELD})
- static @interface AnnotationRuntime0 {
- }
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target( { ElementType.FIELD})
- static @interface AnnotationRuntime1 {
- }
-
- @Retention(RetentionPolicy.CLASS)
- @Target( { ElementType.FIELD})
- static @interface AnnotationClass0 {
- }
-
- @Retention(RetentionPolicy.SOURCE)
- @Target( {ElementType.FIELD})
- static @interface AnnotationSource0 {
- }
-
- @Inherited
- @Retention(RetentionPolicy.RUNTIME)
- @Target( {ElementType.FIELD})
- static @interface InheritedRuntime {
- }
-
- public class GenericField<S, T extends Number> {
- S field;
- T boundedField;
- int intField;
- }
-
-
- static class TestField {
- public static int pubfield1;
-
- private static int privfield1 = 123;
-
- protected int intField = Integer.MAX_VALUE;
- protected final int intFField = Integer.MAX_VALUE;
- protected static int intSField = Integer.MAX_VALUE;
- private final int intPFField = Integer.MAX_VALUE;
-
- protected short shortField = Short.MAX_VALUE;
- protected final short shortFField = Short.MAX_VALUE;
- protected static short shortSField = Short.MAX_VALUE;
- private final short shortPFField = Short.MAX_VALUE;
-
- protected boolean booleanField = true;
- protected static boolean booleanSField = true;
- protected final boolean booleanFField = true;
- private final boolean booleanPFField = true;
-
- protected byte byteField = Byte.MAX_VALUE;
- protected static byte byteSField = Byte.MAX_VALUE;
- protected final byte byteFField = Byte.MAX_VALUE;
- private final byte bytePFField = Byte.MAX_VALUE;
-
- protected long longField = Long.MAX_VALUE;
- protected final long longFField = Long.MAX_VALUE;
- protected static long longSField = Long.MAX_VALUE;
- private final long longPFField = Long.MAX_VALUE;
-
- protected double doubleField = Double.MAX_VALUE;
- protected static double doubleSField = Double.MAX_VALUE;
- protected static final double doubleSFField = Double.MAX_VALUE;
- protected final double doubleFField = Double.MAX_VALUE;
- private final double doublePFField = Double.MAX_VALUE;
-
- protected float floatField = Float.MAX_VALUE;
- protected final float floatFField = Float.MAX_VALUE;
- protected static float floatSField = Float.MAX_VALUE;
- private final float floatPFField = Float.MAX_VALUE;
-
- protected char charField = 'T';
- protected static char charSField = 'T';
- private final char charPFField = 'T';
-
- protected final char charFField = 'T';
-
- private static final int x = 1;
-
- public volatile transient int y = 0;
-
- protected static transient volatile int prsttrvol = 99;
- }
-
- public class TestFieldSub1 extends TestField {
- }
-
- public class TestFieldSub2 extends TestField {
- }
-
- static class A {
- protected short shortField = Short.MAX_VALUE;
- }
-
- static enum TestEnum {
- A, B, C;
- int field;
- }
-
- /**
- * @tests java.lang.reflect.Field#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean
- // java.lang.reflect.Field.equals(java.lang.Object)
- TestField x = new TestField();
- Field f = null;
- try {
- f = x.getClass().getDeclaredField("shortField");
- } catch (Exception e) {
- fail("Exception during getType test : " + e.getMessage());
- }
- try {
- assertTrue("Same Field returned false", f.equals(f));
- assertTrue("Inherited Field returned false", f.equals(x.getClass()
- .getDeclaredField("shortField")));
- assertTrue("Identical Field from different class returned true", !f
- .equals(A.class.getDeclaredField("shortField")));
- } catch (Exception e) {
- fail("Exception during getType test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.lang.reflect.Field#get(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {java.lang.Object.class}
- )
- public void test_getLjava_lang_Object() throws Throwable {
- // Test for method java.lang.Object
- // java.lang.reflect.Field.get(java.lang.Object)
- TestField x = new TestField();
- Field f = x.getClass().getDeclaredField("doubleField");
- Double val = (Double) f.get(x);
-
- assertTrue("Returned incorrect double field value",
- val.doubleValue() == Double.MAX_VALUE);
- // Test getting a static field;
- f = x.getClass().getDeclaredField("doubleSField");
- f.set(x, new Double(1.0));
- val = (Double) f.get(x);
- assertEquals("Returned incorrect double field value", 1.0, val
- .doubleValue());
-
- // Try a get on a private field
- boolean thrown = false;
- try {
- f = TestAccess.class.getDeclaredField("xxx");
- assertNotNull(f);
- f.get(null);
- fail("No expected IllegalAccessException");
- } catch (IllegalAccessException ok) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- // Try a get on a private field in nested member
- // temporarily commented because it breaks J9 VM
- // Regression for HARMONY-1309
- //f = x.getClass().getDeclaredField("privfield1");
- //assertEquals(x.privfield1, f.get(x));
-
- // Try a get using an invalid class.
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- f.get(new String());
- fail("No expected IllegalArgumentException");
- } catch (IllegalArgumentException exc) {
- // Correct - Passed an Object that does not declare or inherit f
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = TestField.class.getDeclaredField("intField");
- f.get(null);
- fail("Expected NullPointerException not thrown");
- } catch (NullPointerException exc) {
- // Correct - Passed an Object that does not declare or inherit f
- thrown = true;
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- //Test no NPE on static fields
- thrown = false;
- try {
- f = TestField.class.getDeclaredField("doubleSField");
- f.get(null);
- assertTrue("Exception thrown", true);
- } catch (Exception exc) {
- fail("No exception expected");
- }
- }
-
- class SupportSubClass extends Support_Field {
-
- Object getField(char primitiveType, Object o, Field f,
- Class expectedException) {
- Object res = null;
- try {
- primitiveType = Character.toUpperCase(primitiveType);
- switch (primitiveType) {
- case 'I': // int
- res = new Integer(f.getInt(o));
- break;
- case 'J': // long
- res = new Long(f.getLong(o));
- break;
- case 'Z': // boolean
- res = new Boolean(f.getBoolean(o));
- break;
- case 'S': // short
- res = new Short(f.getShort(o));
- break;
- case 'B': // byte
- res = new Byte(f.getByte(o));
- break;
- case 'C': // char
- res = new Character(f.getChar(o));
- break;
- case 'D': // double
- res = new Double(f.getDouble(o));
- break;
- case 'F': // float
- res = new Float(f.getFloat(o));
- break;
- default:
- res = f.get(o);
- }
- if (expectedException != null) {
- fail("expected exception " + expectedException.getName());
- }
- } catch (Exception e) {
- if (expectedException == null) {
- fail("unexpected exception " + e);
- } else {
- assertTrue("expected exception "
- + expectedException.getName() + " and got " + e, e
- .getClass().equals(expectedException));
- }
- }
- return res;
- }
-
- void setField(char primitiveType, Object o, Field f,
- Class expectedException, Object value) {
- try {
- primitiveType = Character.toUpperCase(primitiveType);
- switch (primitiveType) {
- case 'I': // int
- f.setInt(o, ((Integer) value).intValue());
- break;
- case 'J': // long
- f.setLong(o, ((Long) value).longValue());
- break;
- case 'Z': // boolean
- f.setBoolean(o, ((Boolean) value).booleanValue());
- break;
- case 'S': // short
- f.setShort(o, ((Short) value).shortValue());
- break;
- case 'B': // byte
- f.setByte(o, ((Byte) value).byteValue());
- break;
- case 'C': // char
- f.setChar(o, ((Character) value).charValue());
- break;
- case 'D': // double
- f.setDouble(o, ((Double) value).doubleValue());
- break;
- case 'F': // float
- f.setFloat(o, ((Float) value).floatValue());
- break;
- default:
- f.set(o, value);
- }
- if (expectedException != null) {
- fail("expected exception " + expectedException.getName()
- + " for field " + f.getName() + ", value " + value);
- }
- } catch (Exception e) {
- if (expectedException == null) {
- fail("unexpected exception " + e + " for field "
- + f.getName() + ", value " + value);
- } else {
- assertTrue("expected exception "
- + expectedException.getName() + " and got " + e
- + " for field " + f.getName() + ", value " + value,
- e.getClass().equals(expectedException));
- }
- }
- }
- }
-
- /**
- * @tests java.lang.reflect.Field#get(java.lang.Object)
- * @tests java.lang.reflect.Field#getByte(java.lang.Object)
- * @tests java.lang.reflect.Field#getBoolean(java.lang.Object)
- * @tests java.lang.reflect.Field#getShort(java.lang.Object)
- * @tests java.lang.reflect.Field#getInt(java.lang.Object)
- * @tests java.lang.reflect.Field#getLong(java.lang.Object)
- * @tests java.lang.reflect.Field#getFloat(java.lang.Object)
- * @tests java.lang.reflect.Field#getDouble(java.lang.Object)
- * @tests java.lang.reflect.Field#getChar(java.lang.Object)
- * @tests java.lang.reflect.Field#set(java.lang.Object, java.lang.Object)
- * @tests java.lang.reflect.Field#setByte(java.lang.Object, byte)
- * @tests java.lang.reflect.Field#setBoolean(java.lang.Object, boolean)
- * @tests java.lang.reflect.Field#setShort(java.lang.Object, short)
- * @tests java.lang.reflect.Field#setInt(java.lang.Object, int)
- * @tests java.lang.reflect.Field#setLong(java.lang.Object, long)
- * @tests java.lang.reflect.Field#setFloat(java.lang.Object, float)
- * @tests java.lang.reflect.Field#setDouble(java.lang.Object, double)
- * @tests java.lang.reflect.Field#setChar(java.lang.Object, char)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "get",
- args = {java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getByte",
- args = {java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getBoolean",
- args = {java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getShort",
- args = {java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getInt",
- args = {java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getFloat",
- args = {java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getDouble",
- args = {java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getChar",
- args = {java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "set",
- args = {java.lang.Object.class, java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "setBoolean",
- args = {java.lang.Object.class, boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "setByte",
- args = {java.lang.Object.class, byte.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "setShort",
- args = {java.lang.Object.class, short.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "setInt",
- args = {java.lang.Object.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "setLong",
- args = {java.lang.Object.class, long.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "setFloat",
- args = {java.lang.Object.class, float.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "setDouble",
- args = {java.lang.Object.class, double.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "setChar",
- args = {java.lang.Object.class, char.class}
- )
- })
- public void testProtectedFieldAccess() {
- Class fieldClass = new Support_Field().getClass();
- String fieldName = null;
- Field objectField = null;
- Field booleanField = null;
- Field byteField = null;
- Field charField = null;
- Field shortField = null;
- Field intField = null;
- Field longField = null;
- Field floatField = null;
- Field doubleField = null;
- try {
- fieldName = "objectField";
- objectField = fieldClass.getDeclaredField(fieldName);
-
- fieldName = "booleanField";
- booleanField = fieldClass.getDeclaredField(fieldName);
-
- fieldName = "byteField";
- byteField = fieldClass.getDeclaredField(fieldName);
-
- fieldName = "charField";
- charField = fieldClass.getDeclaredField(fieldName);
-
- fieldName = "shortField";
- shortField = fieldClass.getDeclaredField(fieldName);
-
- fieldName = "intField";
- intField = fieldClass.getDeclaredField(fieldName);
-
- fieldName = "longField";
- longField = fieldClass.getDeclaredField(fieldName);
-
- fieldName = "floatField";
- floatField = fieldClass.getDeclaredField(fieldName);
-
- fieldName = "doubleField";
- doubleField = fieldClass.getDeclaredField(fieldName);
- } catch (NoSuchFieldException e) {
- fail("missing field " + fieldName + " in test support class "
- + fieldClass.getName());
- }
-
- // create the various objects that might or might not have an instance
- // of the field
- Support_Field parentClass = new Support_Field();
- SupportSubClass subclass = new SupportSubClass();
- SupportSubClass otherSubclass = new SupportSubClass();
- Object plainObject = new Object();
-
- Class illegalAccessExceptionClass = new IllegalAccessException()
- .getClass();
- Class illegalArgumentExceptionClass = new IllegalArgumentException()
- .getClass();
-
- // The test will attempt to use pass an object to set for object, byte,
- // short, ..., float and double fields
- // and pass a byte to to setByte for byte, short, ..., float and double
- // fields and so on.
- // It will also test if IllegalArgumentException is thrown when the
- // field does not exist in the given object and that
- // IllegalAccessException is thrown when trying to access an
- // inaccessible protected field.
- // The test will also check that IllegalArgumentException is thrown for
- // all other attempts.
-
- // Ordered by widening conversion, except for 'L' at the beg (which
- // stands for Object).
- // If the object provided to set can be unwrapped to a primitive, then
- // the set method can set
- // primitive fields.
- char types[] = { 'L', 'B', 'S', 'C', 'I', 'J', 'F', 'D' };
- Field fields[] = { objectField, byteField, shortField, charField,
- intField, longField, floatField, doubleField };
- Object values[] = { new Byte((byte) 1), new Byte((byte) 1),
- new Short((short) 1), new Character((char) 1), new Integer(1),
- new Long(1), new Float(1), new Double(1) };
-
- // test set methods
- for (int i = 0; i < types.length; i++) {
- char type = types[i];
- Object value = values[i];
- for (int j = i; j < fields.length; j++) {
- Field field = fields[j];
- fieldName = field.getName();
-
- if (field == charField && type != 'C') {
- // the exception is that bytes and shorts CANNOT be
- // converted into chars even though chars CAN be
- // converted into ints, longs, floats and doubles
- subclass.setField(type, subclass, field,
- illegalArgumentExceptionClass, value);
- } else {
- // setting type into field);
- subclass.setField(type, subclass, field, null, value);
- subclass.setField(type, otherSubclass, field, null, value);
- subclass.setField(type, parentClass, field,
- illegalAccessExceptionClass, value);
- subclass.setField(type, plainObject, field,
- // Failed on JDK.
- illegalAccessExceptionClass, value);
- }
- }
- for (int j = 0; j < i; j++) {
- Field field = fields[j];
- fieldName = field.getName();
- // not setting type into field);
- subclass.setField(type, subclass, field,
- illegalArgumentExceptionClass, value);
- }
- }
-
- // test setBoolean
- Boolean booleanValue = Boolean.TRUE;
- subclass.setField('Z', subclass, booleanField, null, booleanValue);
- subclass.setField('Z', otherSubclass, booleanField, null, booleanValue);
- subclass.setField('Z', parentClass, booleanField,
- illegalAccessExceptionClass, booleanValue);
- subclass.setField('Z', plainObject, booleanField,
- // Failed on JDK
- illegalAccessExceptionClass, booleanValue);
- for (int j = 0; j < fields.length; j++) {
- Field listedField = fields[j];
- fieldName = listedField.getName();
- // not setting boolean into listedField
- subclass.setField('Z', subclass, listedField,
- illegalArgumentExceptionClass, booleanValue);
- }
- for (int i = 0; i < types.length; i++) {
- char type = types[i];
- Object value = values[i];
- subclass.setField(type, subclass, booleanField,
- illegalArgumentExceptionClass, value);
- }
-
- // We perform the analagous test on the get methods.
-
- // ordered by widening conversion, except for 'L' at the end (which
- // stands for Object), to which all primitives can be converted by
- // wrapping
- char newTypes[] = new char[] { 'B', 'S', 'C', 'I', 'J', 'F', 'D', 'L' };
- Field newFields[] = { byteField, shortField, charField, intField,
- longField, floatField, doubleField, objectField };
- fields = newFields;
- types = newTypes;
- // test get methods
- for (int i = 0; i < types.length; i++) {
- char type = types[i];
- for (int j = 0; j <= i; j++) {
- Field field = fields[j];
- fieldName = field.getName();
- if (type == 'C' && field != charField) {
- // the exception is that bytes and shorts CANNOT be
- // converted into chars even though chars CAN be
- // converted into ints, longs, floats and doubles
- subclass.getField(type, subclass, field,
- illegalArgumentExceptionClass);
- } else {
- // getting type from field
- subclass.getField(type, subclass, field, null);
- subclass.getField(type, otherSubclass, field, null);
- subclass.getField(type, parentClass, field,
- illegalAccessExceptionClass);
- subclass.getField(type, plainObject, field,
- illegalAccessExceptionClass);
- }
- }
- for (int j = i + 1; j < fields.length; j++) {
- Field field = fields[j];
- fieldName = field.getName();
- subclass.getField(type, subclass, field,
- illegalArgumentExceptionClass);
- }
- }
-
- // test getBoolean
- subclass.getField('Z', subclass, booleanField, null);
- subclass.getField('Z', otherSubclass, booleanField, null);
- subclass.getField('Z', parentClass, booleanField,
- illegalAccessExceptionClass);
- subclass.getField('Z', plainObject, booleanField,
- illegalAccessExceptionClass);
- for (int j = 0; j < fields.length; j++) {
- Field listedField = fields[j];
- fieldName = listedField.getName();
- // not getting boolean from listedField
- subclass.getField('Z', subclass, listedField,
- illegalArgumentExceptionClass);
- }
- for (int i = 0; i < types.length - 1; i++) {
- char type = types[i];
- subclass.getField(type, subclass, booleanField,
- illegalArgumentExceptionClass);
- }
- Object res = subclass.getField('L', subclass, booleanField, null);
- assertTrue("unexpected object " + res, res instanceof Boolean);
- }
-
- /**
- * @tests java.lang.reflect.Field#getBoolean(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBoolean",
- args = {java.lang.Object.class}
- )
- public void test_getBooleanLjava_lang_Object() {
- TestField x = new TestField();
- Field f = null;
- boolean val = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- val = f.getBoolean(x);
- } catch (Exception e) {
- fail("Exception during getBoolean test: " + e.toString());
- }
- assertTrue("Returned incorrect boolean field value", val);
-
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- f.getBoolean(x);
- fail("IllegalArgumentException expected but not thrown");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalArgumentException expected but not thrown");
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanPFField");
- f.getBoolean(x);
- fail("IllegalAccessException expected but not thrown");
- } catch (IllegalAccessException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalAccessException expected but not thrown"
- + ex.getMessage());
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.getBoolean(null);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- //Test no NPE on static field
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanSField");
- boolean staticValue = f.getBoolean(null);
- assertTrue("Wrong value returned", staticValue);
- } catch (Exception ex) {
- fail("No exception expected");
- }
- }
-
-
- /**
- * @tests java.lang.reflect.Field#getByte(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getByte",
- args = {java.lang.Object.class}
- )
- public void test_getByteLjava_lang_Object() {
- // Test for method byte
- // java.lang.reflect.Field.getByte(java.lang.Object)
- TestField x = new TestField();
- Field f = null;
- byte val = 0;
- try {
- f = x.getClass().getDeclaredField("byteField");
- val = f.getByte(x);
- } catch (Exception e) {
- fail("Exception during getbyte test : " + e.getMessage());
- }
- assertTrue("Returned incorrect byte field value", val == Byte.MAX_VALUE);
-
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- f.getByte(x);
- fail("IllegalArgumentException expected but not thrown");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalArgumentException expected but not thrown");
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("bytePFField");
- f.getByte(x);
- fail("IllegalAccessException expected but not thrown");
- } catch (IllegalAccessException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalAccessException expected but not thrown"
- + ex.getMessage());
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("byteField");
- f.getByte(null);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- //Test no NPE on static field
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("byteSField");
- byte staticValue = f.getByte(null);
- assertEquals("Wrong value returned", Byte.MAX_VALUE, staticValue);
- } catch (Exception ex) {
- fail("No exception expected "+ ex.getMessage());
- }
- }
-
- /**
- * @tests java.lang.reflect.Field#getChar(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getChar",
- args = {java.lang.Object.class}
- )
- public void test_getCharLjava_lang_Object() {
- // Test for method char
- // java.lang.reflect.Field.getChar(java.lang.Object)
- TestField x = new TestField();
- Field f = null;
- char val = 0;
- try {
- f = x.getClass().getDeclaredField("charField");
- val = f.getChar(x);
- } catch (Exception e) {
- fail("Exception during getCharacter test: " + e.toString());
- }
- assertEquals("Returned incorrect char field value", 'T', val);
-
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- f.getChar(x);
- fail("IllegalArgumentException expected but not thrown");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalArgumentException expected but not thrown");
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("charPFField");
- f.getChar(x);
- fail("IllegalAccessException expected but not thrown");
- } catch (IllegalAccessException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalAccessException expected but not thrown"
- + ex.getMessage());
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("charField");
- f.getChar(null);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- //Test no NPE on static field
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("charSField");
- char staticValue = f.getChar(null);
- assertEquals("Wrong value returned", 'T', staticValue);
- } catch (Exception ex) {
- fail("No exception expected "+ ex.getMessage());
- }
- }
-
- /**
- * @tests java.lang.reflect.Field#getDeclaringClass()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaringClass",
- args = {}
- )
- public void test_getDeclaringClass() {
- // Test for method java.lang.Class
- // java.lang.reflect.Field.getDeclaringClass()
- Field[] fields;
-
- try {
- fields = new TestField().getClass().getFields();
- assertTrue("Returned incorrect declaring class", fields[0]
- .getDeclaringClass().equals(new TestField().getClass()));
-
- // Check the case where the field is inherited to be sure the parent
- // is returned as the declarator
- fields = new TestFieldSub1().getClass().getFields();
- assertTrue("Returned incorrect declaring class", fields[0]
- .getDeclaringClass().equals(new TestField().getClass()));
- } catch (Exception e) {
- fail("Exception : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.lang.reflect.Field#getDouble(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDouble",
- args = {java.lang.Object.class}
- )
- public void test_getDoubleLjava_lang_Object() {
- // Test for method double
- // java.lang.reflect.Field.getDouble(java.lang.Object)
- TestField x = new TestField();
- Field f = null;
- double val = 0.0;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- val = f.getDouble(x);
- } catch (Exception e) {
- fail("Exception during getDouble test: " + e.toString());
- }
- assertTrue("Returned incorrect double field value",
- val == Double.MAX_VALUE);
-
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.getDouble(x);
- fail("IllegalArgumentException expected but not thrown");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalArgumentException expected but not thrown "
- + ex.getMessage());
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("doublePFField");
- f.getDouble(x);
- fail("IllegalAccessException expected but not thrown");
- } catch (IllegalAccessException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalAccessException expected but not thrown"
- + ex.getMessage());
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- f.getDouble(null);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- //Test no NPE on static field
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("doubleSFField");
- double staticValue = f.getDouble(null);
- assertEquals("Wrong value returned", Double.MAX_VALUE, staticValue);
- } catch (Exception ex) {
- fail("No exception expected "+ ex.getMessage());
- }
- }
-
- /**
- * @tests java.lang.reflect.Field#getFloat(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFloat",
- args = {java.lang.Object.class}
- )
- public void test_getFloatLjava_lang_Object() {
- // Test for method float
- // java.lang.reflect.Field.getFloat(java.lang.Object)
- TestField x = new TestField();
- Field f = null;
- float val = 0;
- try {
- f = x.getClass().getDeclaredField("floatField");
- val = f.getFloat(x);
- } catch (Exception e) {
- fail("Exception during getFloat test : " + e.getMessage());
- }
- assertTrue("Returned incorrect float field value",
- val == Float.MAX_VALUE);
-
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.getFloat(x);
- fail("IllegalArgumentException expected but not thrown");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalArgumentException expected but not thrown "
- + ex.getMessage());
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("floatPFField");
- f.getFloat(x);
- fail("IllegalAccessException expected but not thrown");
- } catch (IllegalAccessException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalAccessException expected but not thrown"
- + ex.getMessage());
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("floatField");
- f.getFloat(null);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- //Test no NPE on static field
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("floatSField");
- float staticValue = f.getFloat(null);
- assertEquals("Wrong value returned", Float.MAX_VALUE, staticValue);
- } catch (Exception ex) {
- fail("No exception expected "+ ex.getMessage());
- }
- }
-
- /**
- * @tests java.lang.reflect.Field#getInt(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInt",
- args = {java.lang.Object.class}
- )
- public void test_getIntLjava_lang_Object() {
- // Test for method int java.lang.reflect.Field.getInt(java.lang.Object)
- TestField x = new TestField();
- Field f = null;
- int val = 0;
- try {
- f = x.getClass().getDeclaredField("intField");
- val = f.getInt(x);
- } catch (Exception e) {
- fail("Exception during getInt test : " + e.getMessage());
- }
- assertTrue("Returned incorrect Int field value",
- val == Integer.MAX_VALUE);
-
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.getInt(x);
- fail("IllegalArgumentException expected but not thrown");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalArgumentException expected but not thrown "
- + ex.getMessage());
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("intPFField");
- f.getInt(x);
- fail("IllegalAccessException expected but not thrown");
- } catch (IllegalAccessException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalAccessException expected but not thrown"
- + ex.getMessage());
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("intField");
- f.getInt(null);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- //Test no NPE on static field
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("intSField");
- int staticValue = f.getInt(null);
- assertEquals("Wrong value returned", Integer.MAX_VALUE, staticValue);
- } catch (Exception ex) {
- fail("No exception expected " + ex.getMessage());
- }
-
- }
-
- /**
- * @tests java.lang.reflect.Field#getLong(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLong",
- args = {java.lang.Object.class}
- )
- public void test_getLongLjava_lang_Object() {
- // Test for method long
- // java.lang.reflect.Field.getLong(java.lang.Object)
- TestField x = new TestField();
- Field f = null;
- long val = 0;
- try {
- f = x.getClass().getDeclaredField("longField");
- val = f.getLong(x);
- } catch (Exception e) {
- fail("Exception during getLong test : " + e.getMessage());
- }
-
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.getLong(x);
- fail("IllegalArgumentException expected but not thrown");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalArgumentException expected but not thrown "
- + ex.getMessage());
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("longPFField");
- f.getLong(x);
- fail("IllegalAccessException expected but not thrown");
- } catch (IllegalAccessException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalAccessException expected but not thrown"
- + ex.getMessage());
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("longField");
- f.getLong(null);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- //Test no NPE on static field
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("longSField");
- long staticValue = f.getLong(null);
- assertEquals("Wrong value returned", Long.MAX_VALUE, staticValue);
- } catch (Exception ex) {
- fail("No exception expected "+ ex.getMessage());
- }
- }
-
- /**
- * @tests java.lang.reflect.Field#getModifiers()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getModifiers",
- args = {}
- )
- public void test_getModifiers() {
- // Test for method int java.lang.reflect.Field.getModifiers()
- TestField x = new TestField();
- Field f = null;
- try {
- f = x.getClass().getDeclaredField("prsttrvol");
- } catch (Exception e) {
- fail("Exception during getModifiers test: " + e.toString());
- }
- int mod = f.getModifiers();
- int mask = (Modifier.PROTECTED | Modifier.STATIC)
- | (Modifier.TRANSIENT | Modifier.VOLATILE);
- int nmask = (Modifier.PUBLIC | Modifier.NATIVE);
- assertTrue("Returned incorrect field modifiers: ",
- ((mod & mask) == mask) && ((mod & nmask) == 0));
- }
-
- /**
- * @tests java.lang.reflect.Field#getName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getName",
- args = {}
- )
- public void test_getName() {
- // Test for method java.lang.String java.lang.reflect.Field.getName()
- TestField x = new TestField();
- Field f = null;
- try {
- f = x.getClass().getDeclaredField("shortField");
- } catch (Exception e) {
- fail("Exception during getType test : " + e.getMessage());
- }
- assertEquals("Returned incorrect field name",
- "shortField", f.getName());
- }
-
- /**
- * @tests java.lang.reflect.Field#getShort(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getShort",
- args = {java.lang.Object.class}
- )
- public void test_getShortLjava_lang_Object() {
- // Test for method short
- // java.lang.reflect.Field.getShort(java.lang.Object)
- TestField x = new TestField();
- Field f = null;
- short val = 0;
- ;
- try {
- f = x.getClass().getDeclaredField("shortField");
- val = f.getShort(x);
- } catch (Exception e) {
- fail("Exception during getShort test : " + e.getMessage());
- }
- assertTrue("Returned incorrect short field value",
- val == Short.MAX_VALUE);
-
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.getShort(x);
- fail("IllegalArgumentException expected but not thrown");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalArgumentException expected but not thrown "
- + ex.getMessage());
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("shortPFField");
- f.getShort(x);
- fail("IllegalAccessException expected but not thrown");
- } catch (IllegalAccessException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("IllegalAccessException expected but not thrown"
- + ex.getMessage());
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("shortField");
- f.getShort(null);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- //Test no NPE on static field
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("shortSField");
- short staticValue = f.getShort(null);
- assertEquals("Wrong value returned", Short.MAX_VALUE, staticValue);
- } catch (Exception ex) {
- fail("No exception expected "+ ex.getMessage());
- }
- }
-
- /**
- * @tests java.lang.reflect.Field#getType()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getType",
- args = {}
- )
- public void test_getType() {
- // Test for method java.lang.Class java.lang.reflect.Field.getType()
- TestField x = new TestField();
- Field f = null;
- try {
- f = x.getClass().getDeclaredField("shortField");
- } catch (Exception e) {
- fail("Exception during getType test : " + e.getMessage());
- }
- assertTrue("Returned incorrect field type: " + f.getType().toString(),
- f.getType().equals(short.class));
- }
-
- /**
- * @tests java.lang.reflect.Field#set(java.lang.Object, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "set",
- args = {java.lang.Object.class, java.lang.Object.class}
- )
- public void test_setLjava_lang_ObjectLjava_lang_Object() throws Exception{
- // Test for method void java.lang.reflect.Field.set(java.lang.Object,
- // java.lang.Object)
- TestField x = new TestField();
- Field f = null;
- double val = 0.0;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- f.set(x, new Double(1.0));
- val = f.getDouble(x);
- } catch (Exception e) {
- fail("Exception during set test : " + e.getMessage());
- }
- assertEquals("Returned incorrect double field value", 1.0, val);
-
- //test wrong type
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.set(x, new Double(1.0));
- fail("Accessed field of invalid type");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- //test not accessible
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("doubleFField");
- assertFalse(f.isAccessible());
- f.set(x, new Double(1.0));
- fail("Accessed inaccessible field");
- } catch (IllegalAccessException ex) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.set(null, true);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- // Test setting a static field;
- f = x.getClass().getDeclaredField("doubleSField");
- f.set(null, new Double(1.0));
- val = f.getDouble(x);
- assertEquals("Returned incorrect double field value", 1.0, val);
- }
-
- /**
- * @tests java.lang.reflect.Field#setBoolean(java.lang.Object, boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setBoolean",
- args = {java.lang.Object.class, boolean.class}
- )
- public void test_setBooleanLjava_lang_ObjectZ() throws Exception{
- // Test for method void
- // java.lang.reflect.Field.setBoolean(java.lang.Object, boolean)
- TestField x = new TestField();
- Field f = null;
- boolean val = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.setBoolean(x, false);
- val = f.getBoolean(x);
- } catch (Exception e) {
- fail("Exception during setboolean test: " + e.toString());
- }
- assertTrue("Returned incorrect float field value", !val);
-
- //test wrong type
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- f.setBoolean(x, false);
- fail("Accessed field of invalid type");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- //test not accessible
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanPFField");
- assertFalse(f.isAccessible());
- f.setBoolean(x, true);
- fail("Accessed inaccessible field");
- } catch (IllegalAccessException ex) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.setBoolean(null, true);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- // Test setting a static field;
- f = x.getClass().getDeclaredField("booleanSField");
- f.setBoolean(null, false);
- val = f.getBoolean(x);
- assertFalse("Returned incorrect boolean field value", val);
- }
-
- /**
- * @tests java.lang.reflect.Field#setByte(java.lang.Object, byte)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setByte",
- args = {java.lang.Object.class, byte.class}
- )
- public void test_setByteLjava_lang_ObjectB() throws Exception{
- // Test for method void
- // java.lang.reflect.Field.setByte(java.lang.Object, byte)
- TestField x = new TestField();
- Field f = null;
- byte val = 0;
- try {
- f = x.getClass().getDeclaredField("byteField");
- f.setByte(x, (byte) 1);
- val = f.getByte(x);
- } catch (Exception e) {
- fail("Exception during setByte test : " + e.getMessage());
- }
- assertEquals("Returned incorrect float field value", 1, val);
-
- //test wrong type
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.setByte(x, Byte.MIN_VALUE);
- fail("Accessed field of invalid type");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- //test not accessible
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("bytePFField");
- assertFalse(f.isAccessible());
- f.setByte(x, Byte.MIN_VALUE);
- fail("Accessed inaccessible field");
- } catch (IllegalAccessException ex) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("byteField");
- f.setByte(null, Byte.MIN_VALUE);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- // Test setting a static field;
- f = x.getClass().getDeclaredField("byteSField");
- f.setByte(null, Byte.MIN_VALUE);
- val = f.getByte(x);
- assertEquals("Returned incorrect byte field value", Byte.MIN_VALUE,
- val);
- }
-
- /**
- * @tests java.lang.reflect.Field#setChar(java.lang.Object, char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setChar",
- args = {java.lang.Object.class, char.class}
- )
- public void test_setCharLjava_lang_ObjectC() throws Exception{
- // Test for method void
- // java.lang.reflect.Field.setChar(java.lang.Object, char)
- TestField x = new TestField();
- Field f = null;
- char val = 0;
- try {
- f = x.getClass().getDeclaredField("charField");
- f.setChar(x, (char) 1);
- val = f.getChar(x);
- } catch (Exception e) {
- fail("Exception during setChar test : " + e.getMessage());
- }
- assertEquals("Returned incorrect float field value", 1, val);
-
- //test wrong type
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.setChar(x, Character.MIN_VALUE);
- fail("Accessed field of invalid type");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- //test not accessible
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("charPFField");
- assertFalse(f.isAccessible());
- f.setChar(x, Character.MIN_VALUE);
- fail("Accessed inaccessible field");
- } catch (IllegalAccessException ex) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("charField");
- f.setChar(null, Character.MIN_VALUE);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- // Test setting a static field;
- f = x.getClass().getDeclaredField("charSField");
- f.setChar(null, Character.MIN_VALUE);
- val = f.getChar(x);
- assertEquals("Returned incorrect char field value",
- Character.MIN_VALUE, val);
- }
-
- /**
- * @tests java.lang.reflect.Field#setDouble(java.lang.Object, double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setDouble",
- args = {java.lang.Object.class, double.class}
- )
- public void test_setDoubleLjava_lang_ObjectD() throws Exception{
- // Test for method void
- // java.lang.reflect.Field.setDouble(java.lang.Object, double)
- TestField x = new TestField();
- Field f = null;
- double val = 0.0;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- f.setDouble(x, Double.MIN_VALUE);
- val = f.getDouble(x);
- } catch (Exception e) {
- fail("Exception during setDouble test: " + e.toString());
- }
- assertEquals("Returned incorrect double field value", Double.MIN_VALUE,
- val);
-
- //test wrong type
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.setDouble(x, Double.MIN_VALUE);
- fail("Accessed field of invalid type");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- //test not accessible
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("doublePFField");
- assertFalse(f.isAccessible());
- f.setDouble(x, Double.MIN_VALUE);
- fail("Accessed inaccessible field");
- } catch (IllegalAccessException ex) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("doubleField");
- f.setDouble(null, Double.MIN_VALUE);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- // Test setting a static field;
- f = x.getClass().getDeclaredField("doubleSField");
- f.setDouble(null, Double.MIN_VALUE);
- val = f.getDouble(x);
- assertEquals("Returned incorrect double field value",
- Double.MIN_VALUE, val);
- }
-
- /**
- * @tests java.lang.reflect.Field#setFloat(java.lang.Object, float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setFloat",
- args = {java.lang.Object.class, float.class}
- )
- public void test_setFloatLjava_lang_ObjectF() throws Exception{
- // Test for method void
- // java.lang.reflect.Field.setFloat(java.lang.Object, float)
- TestField x = new TestField();
- Field f = null;
- float val = 0.0F;
- try {
- f = x.getClass().getDeclaredField("floatField");
- f.setFloat(x, Float.MIN_VALUE);
- val = f.getFloat(x);
- } catch (Exception e) {
- fail("Exception during setFloat test : " + e.getMessage());
- }
- assertEquals("Returned incorrect float field value", Float.MIN_VALUE,
- val, 0.0);
-
- //test wrong type
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.setFloat(x, Float.MIN_VALUE);
- fail("Accessed field of invalid type");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- //test not accessible
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("floatPFField");
- assertFalse(f.isAccessible());
- f.setFloat(x, Float.MIN_VALUE);
- fail("Accessed inaccessible field");
- } catch (IllegalAccessException ex) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- //Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("floatField");
- f.setFloat(null, Float.MIN_VALUE);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- // Test setting a static field;
- f = x.getClass().getDeclaredField("floatSField");
- f.setFloat(null, Float.MIN_VALUE);
- val = f.getFloat(x);
- assertEquals("Returned incorrect float field value",
- Float.MIN_VALUE, val);
- }
-
- /**
- * @tests java.lang.reflect.Field#setInt(java.lang.Object, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setInt",
- args = {java.lang.Object.class, int.class}
- )
- public void test_setIntLjava_lang_ObjectI() throws Exception{
- // Test for method void java.lang.reflect.Field.setInt(java.lang.Object,
- // int)
- TestField x = new TestField();
- Field f = null;
- int val = 0;
- try {
- f = x.getClass().getDeclaredField("intField");
- f.setInt(x, Integer.MIN_VALUE);
- val = f.getInt(x);
- } catch (Exception e) {
- fail("Exception during setInteger test: " + e.toString());
- }
- assertEquals("Returned incorrect int field value", Integer.MIN_VALUE,
- val);
-
- // test wrong type
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.setInt(x, Integer.MIN_VALUE);
- fail("Accessed field of invalid type");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- // test not accessible
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("intPFField");
- assertFalse(f.isAccessible());
- f.setInt(x, Integer.MIN_VALUE);
- fail("Accessed inaccessible field");
- } catch (IllegalAccessException ex) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- // Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("intField");
- f.setInt(null, Integer.MIN_VALUE);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- // Test setting a static field;
- f = x.getClass().getDeclaredField("intSField");
- f.setInt(null, Integer.MIN_VALUE);
- val = f.getInt(x);
- assertEquals("Returned incorrect int field value",
- Integer.MIN_VALUE, val);
- }
-
- /**
- * @tests java.lang.reflect.Field#setLong(java.lang.Object, long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setLong",
- args = {java.lang.Object.class, long.class}
- )
- public void test_setLongLjava_lang_ObjectJ() throws Exception{
- // Test for method void
- // java.lang.reflect.Field.setLong(java.lang.Object, long)
- TestField x = new TestField();
- Field f = null;
- long val = 0L;
- try {
- f = x.getClass().getDeclaredField("longField");
- f.setLong(x, Long.MIN_VALUE);
- val = f.getLong(x);
- } catch (Exception e) {
- fail("Exception during setLong test : " + e.getMessage());
- }
- assertEquals("Returned incorrect long field value", Long.MIN_VALUE, val);
-
- // test wrong type
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.setLong(x, Long.MIN_VALUE);
- fail("Accessed field of invalid type");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- // test not accessible
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("longPFField");
- assertFalse(f.isAccessible());
- f.setLong(x, Long.MIN_VALUE);
- fail("Accessed inaccessible field");
- } catch (IllegalAccessException ex) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- // Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("longField");
- f.setLong(null, Long.MIN_VALUE);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- // Test setting a static field;
- f = x.getClass().getDeclaredField("longSField");
- f.setLong(null, Long.MIN_VALUE);
- val = f.getLong(x);
- assertEquals("Returned incorrect long field value",
- Long.MIN_VALUE, val);
- }
-
- /**
- * @tests java.lang.reflect.Field#setShort(java.lang.Object, short)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setShort",
- args = {java.lang.Object.class, short.class}
- )
- public void test_setShortLjava_lang_ObjectS() throws Exception{
- // Test for method void
- // java.lang.reflect.Field.setShort(java.lang.Object, short)
- TestField x = new TestField();
- Field f = null;
- short val = 0;
- try {
- f = x.getClass().getDeclaredField("shortField");
- f.setShort(x, Short.MIN_VALUE);
- val = f.getShort(x);
- } catch (Exception e) {
- fail("Exception during setShort test : " + e.getMessage());
- }
- assertEquals("Returned incorrect short field value", Short.MIN_VALUE,
- val);
-
- // test wrong type
- boolean thrown = false;
- try {
- f = x.getClass().getDeclaredField("booleanField");
- f.setShort(x, Short.MIN_VALUE);
- fail("Accessed field of invalid type");
- } catch (IllegalArgumentException ex) {
- thrown = true;
- }
- assertTrue("IllegalArgumentException expected but not thrown", thrown);
-
- // test not accessible
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("shortPFField");
- assertFalse(f.isAccessible());
- f.setShort(x, Short.MIN_VALUE);
- fail("Accessed inaccessible field");
- } catch (IllegalAccessException ex) {
- thrown = true;
- }
- assertTrue("IllegalAccessException expected but not thrown", thrown);
-
- // Test NPE
- thrown = false;
- try {
- f = x.getClass().getDeclaredField("shortField");
- f.setShort(null, Short.MIN_VALUE);
- fail("NullPointerException expected but not thrown");
- } catch (NullPointerException ex) {
- thrown = true;
- } catch (Exception ex) {
- fail("NullPointerException expected but not thrown");
- }
- assertTrue("NullPointerException expected but not thrown", thrown);
-
- // Test setting a static field;
- f = x.getClass().getDeclaredField("shortSField");
- f.setShort(null, Short.MIN_VALUE);
- val = f.getShort(x);
- assertEquals("Returned incorrect short field value",
- Short.MIN_VALUE, val);
- }
-
- /**
- * @tests java.lang.reflect.Field#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.lang.reflect.Field.toString()
- Field f = null;
-
- try {
- f = TestField.class.getDeclaredField("x");
- } catch (Exception e) {
- fail("Exception getting field : " + e.getMessage());
- }
- assertEquals("Field returned incorrect string",
- "private static final int tests.api.java.lang.reflect.FieldTest$TestField.x",
- f.toString());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaredAnnotations",
- args = {}
- )
- public void test_getDeclaredAnnotations() throws Exception {
- Field field = TestClass.class.getField("annotatedField");
- Annotation[] annotations = field.getDeclaredAnnotations();
- assertEquals(2, annotations.length);
-
- Set<Class<?>> ignoreOrder = new HashSet<Class<?>>();
- ignoreOrder.add(annotations[0].annotationType());
- ignoreOrder.add(annotations[1].annotationType());
-
- assertTrue("Missing @AnnotationRuntime0", ignoreOrder
- .contains(AnnotationRuntime0.class));
- assertTrue("Missing @AnnotationRuntime1", ignoreOrder
- .contains(AnnotationRuntime1.class));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isEnumConstant",
- args = {}
- )
- public void test_isEnumConstant() throws Exception {
- Field field = TestEnum.class.getDeclaredField("A");
- assertTrue("Enum constant not recognized", field.isEnumConstant());
-
- field = TestEnum.class.getDeclaredField("field");
- assertFalse("Non enum constant wrongly stated as enum constant", field
- .isEnumConstant());
-
- field = TestClass.class.getDeclaredField("annotatedField");
- assertFalse("Non enum constant wrongly stated as enum constant", field
- .isEnumConstant());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isSynthetic",
- args = {}
- )
- public void test_isSynthetic() throws Exception {
- Field[] fields = TestClass.Inner.class.getDeclaredFields();
- assertEquals("Not exactly one field returned", 1, fields.length);
-
- assertTrue("Enum constant not recognized", fields[0].isSynthetic());
-
- Field field = TestEnum.class.getDeclaredField("field");
- assertFalse("Non synthetic field wrongly stated as synthetic", field
- .isSynthetic());
-
- field = TestClass.class.getDeclaredField("annotatedField");
- assertFalse("Non synthetic field wrongly stated as synthetic", field
- .isSynthetic());
- }
-
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getGenericType",
- args = {}
- )
- public void test_getGenericType() throws Exception {
- Field field = GenericField.class.getDeclaredField("field");
- Type type = field.getGenericType();
- @SuppressWarnings("unchecked")
- TypeVariable typeVar = (TypeVariable) type;
- assertEquals("Wrong type name returned", "S", typeVar.getName());
-
- Field boundedField = GenericField.class.getDeclaredField("boundedField");
- Type boundedType = boundedField.getGenericType();
- @SuppressWarnings("unchecked")
- TypeVariable boundedTypeVar = (TypeVariable) boundedType;
- assertEquals("Wrong type name returned", "T", boundedTypeVar.getName());
- assertEquals("More than one bound found", 1,
- boundedTypeVar.getBounds().length);
- assertEquals("Wrong bound returned", Number.class,
- boundedTypeVar.getBounds()[0]);
- }
-
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toGenericString",
- args = {}
- )
- public void test_toGenericString() throws Exception {
- Field field = GenericField.class.getDeclaredField("field");
- assertEquals("Wrong generic string returned",
- "S tests.api.java.lang.reflect.FieldTest$GenericField.field",
- field.toGenericString());
-
- Field boundedField = GenericField.class
- .getDeclaredField("boundedField");
- assertEquals(
- "Wrong generic string returned",
- "T tests.api.java.lang.reflect.FieldTest$GenericField.boundedField",
- boundedField.toGenericString());
-
- Field ordinary = GenericField.class.getDeclaredField("intField");
- assertEquals(
- "Wrong generic string returned",
- "int tests.api.java.lang.reflect.FieldTest$GenericField.intField",
- ordinary.toGenericString());
- }
-
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() throws Exception {
- Field field = TestClass.class.getDeclaredField("annotatedField");
- assertEquals("Wrong hashCode returned", field.getName().hashCode()
- ^ field.getDeclaringClass().getName().hashCode(), field
- .hashCode());
- }
-
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
-
-class TestAccess {
- private static int xxx;
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/GenericArrayTypeTest.java b/luni/src/test/java/tests/api/java/lang/reflect/GenericArrayTypeTest.java
deleted file mode 100644
index f7fb876..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/GenericArrayTypeTest.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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 tests.api.java.lang.reflect;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.GenericArrayType;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-
-/**
- * Tests generic reflection on arrays with generic or parameterized component types.
- */
-@TestTargetClass(GenericArrayType.class)
-public class GenericArrayTypeTest extends GenericReflectionTestsBase {
-
- static class A<T> {
- T[] array;
- }
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Missing tests for TypeNotPresentException, MalformedParameterizedTypeException",
- method = "getGenericComponentType",
- args = {}
- )
- public void testGetGenericComponentType() throws Exception {
- @SuppressWarnings("unchecked")
- Class<? extends A> clazz = GenericArrayTypeTest.A.class;
- Field field = clazz.getDeclaredField("array");
- Type genericType = field.getGenericType();
- assertInstanceOf(GenericArrayType.class, genericType);
- Type componentType = ((GenericArrayType) genericType).getGenericComponentType();
- assertEquals(getTypeParameter(clazz), componentType);
- assertInstanceOf(TypeVariable.class, componentType);
- TypeVariable<?> componentTypeVariable = (TypeVariable<?>) componentType;
- assertEquals("T", componentTypeVariable.getName());
- assertEquals(clazz, componentTypeVariable.getGenericDeclaration());
- }
-
- static class B<T> {
- B<T>[] array;
- }
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Missing tests for TypeNotPresentException, MalformedParameterizedTypeException",
- method = "getGenericComponentType",
- args = {}
- )
- public void testParameterizedComponentType() throws Exception {
- @SuppressWarnings("unchecked")
- Class<? extends B> clazz = GenericArrayTypeTest.B.class;
- Field field = clazz.getDeclaredField("array");
- Type genericType = field.getGenericType();
-
- assertInstanceOf(GenericArrayType.class, genericType);
- GenericArrayType arrayType = (GenericArrayType) genericType;
- Type componentType = arrayType.getGenericComponentType();
- assertInstanceOf(ParameterizedType.class, componentType);
- ParameterizedType parameteriezdType = (ParameterizedType) componentType;
- assertEquals(clazz, parameteriezdType.getRawType());
- assertEquals(clazz.getTypeParameters()[0], parameteriezdType.getActualTypeArguments()[0]);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/GenericMethodsTests.java b/luni/src/test/java/tests/api/java/lang/reflect/GenericMethodsTests.java
deleted file mode 100644
index 6a8db2a..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/GenericMethodsTests.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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 tests.api.java.lang.reflect;
-
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.lang.reflect.Method;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-
-
-/**
- * Tests unbounded type parameters declared on methods.
- */
-@TestTargetClass(Method.class)
-public class GenericMethodsTests extends GenericReflectionTestsBase{
-
- static class GenericMethods {
-
- public <T> void noParamNoReturn() {}
-
- public <T> void paramNoReturn(T param) {}
-
- @SuppressWarnings("unchecked")
- public <T> T noParamReturn() { return (T) new Object(); }
-
- public <T> T paramReturn(T param) {return param;}
- }
-
- private static Class<? extends GenericMethods> clazz = GenericMethodsTests.GenericMethods.class;
-
- /**
- * Tests that there are no Type Parameters on the Class itself.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getTypeParameters",
- args = {}
- )
- public void testGenericMethods() {
- assertLenghtZero(clazz.getTypeParameters());
- }
-
- /**
- * Tests whether the specified method declares a type parameter T.
- * @param method the method
- */
- private void checkTypeParameter(Method method) {
- TypeVariable<Method> typeParameter = getTypeParameter(method);
- assertEquals("T", typeParameter.getName());
- assertEquals(method, typeParameter.getGenericDeclaration());
- }
-
- /**
- * Tests whether the specified method declares a parameter with the
- * type of the type parameter.
- * @param method the method
- */
- private void checkParameterType(Method method) {
- TypeVariable<Method> typeParameter = getTypeParameter(method);
- assertLenghtOne(method.getGenericParameterTypes());
- Type genericParameterType = method.getGenericParameterTypes()[0];
- assertEquals(typeParameter, genericParameterType);
- assertInstanceOf(TypeVariable.class, genericParameterType);
- assertEquals(method, ((TypeVariable<?>) genericParameterType).getGenericDeclaration());
- }
-
- /**
- * Tests whether the type of the return type is the declared type parameter.
- * @param method the declaring method
- */
- private void checkReturnType(Method method) {
- TypeVariable<Method> typeParameter = getTypeParameter(method);
- Type genericReturnType = method.getGenericReturnType();
- assertEquals(typeParameter, genericReturnType);
- assertInstanceOf(TypeVariable.class, genericReturnType);
- assertEquals(method, ((TypeVariable<?>) genericReturnType).getGenericDeclaration());
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getTypeParameters",
- args = {}
- )
- public void testNoParamNoReturn() throws Exception {
- Method method = clazz.getMethod("noParamNoReturn");
- checkTypeParameter(method);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getTypeParameters",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getGenericParameterTypes",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getParameterTypes",
- args = {}
- )
- })
- public void testParamNoReturn() throws Exception {
- Method method = clazz.getMethod("paramNoReturn", Object.class);
- checkTypeParameter(method);
- checkParameterType(method);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getGenericParameterTypes",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getGenericReturnType",
- args = {}
- )
- })
- public void testNoParamReturn() throws Exception {
- Method method = clazz.getMethod("noParamReturn");
- checkTypeParameter(method);
- assertLenghtZero(method.getGenericParameterTypes());
- checkReturnType(method);
- }
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getTypeParameters",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getParameterTypes",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getGenericReturnType",
- args = {}
- )
- })
- public void testParamReturn() throws Exception {
- Method method = clazz.getMethod("paramReturn", Object.class);
- checkTypeParameter(method);
- checkParameterType(method);
- checkReturnType(method);
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "getTypeParameters",
- args = {}
- )
- public void testIndependencyOfMethodTypeParameters() throws Exception {
- Method method0 = clazz.getMethod("paramNoReturn", Object.class);
- TypeVariable<Method> typeParameter0 = method0.getTypeParameters()[0];
-
- Method method1 = clazz.getMethod("noParamNoReturn");
- TypeVariable<Method> typeParameter1 = method1.getTypeParameters()[0];
-
- //Generic method type parameters NAMES are equal
- assertEquals(typeParameter0.getName(), typeParameter1.getName());
- //Generic method type PARAMETERS are not equal
- assertNotEquals(typeParameter0, typeParameter1);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/GenericReflectionCornerCases.java b/luni/src/test/java/tests/api/java/lang/reflect/GenericReflectionCornerCases.java
deleted file mode 100644
index a0af46e..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/GenericReflectionCornerCases.java
+++ /dev/null
@@ -1,287 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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 tests.api.java.lang.reflect;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.lang.reflect.Method;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-import java.lang.reflect.WildcardType;
-
-/**
- * Tests generic reflection in more complicated cases. In particular: Scoping of
- * type parameters, equality of type parameters, wildcard types, parameterized
- * types and multiple bounds.
- */
-@TestTargetClass(Method.class)
-public class GenericReflectionCornerCases extends GenericReflectionTestsBase {
-
- static class Pair<T, S> {}
-
- static class WildcardEquality<T> {
- void wildcardEquality(Pair<? extends T, ? extends T> param) {}
- }
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getTypeParameters",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getGenericParameterTypes",
- args = {}
- )
- })
- @SuppressWarnings("unchecked")
- public void testWildcardEquality() throws Exception {
- Class<? extends WildcardEquality> clazz = WildcardEquality.class;
-
- Method method = clazz.getDeclaredMethod("wildcardEquality", Pair.class);
- TypeVariable<?>[] typeParameters = clazz.getTypeParameters();
- assertLenghtOne(typeParameters);
- TypeVariable<?> typeParameter = typeParameters[0];
-
- Type[] parameterTypes = method.getGenericParameterTypes();
- assertLenghtOne(parameterTypes);
- Type parameter = parameterTypes[0];
- assertInstanceOf(ParameterizedType.class, parameter);
- ParameterizedType paramType = (ParameterizedType) parameter;
- Type[] actualTypeArguments = paramType.getActualTypeArguments();
- assertEquals(2, actualTypeArguments.length);
-
- Type firstArgument = actualTypeArguments[0];
- assertInstanceOf(WildcardType.class, firstArgument);
- WildcardType firstWildcardArgument = (WildcardType) firstArgument;
- Type secondArgument = actualTypeArguments[1];
- assertInstanceOf(WildcardType.class, secondArgument);
- WildcardType secondWildcardArgument = (WildcardType) secondArgument;
-
- assertEquals(firstWildcardArgument, secondWildcardArgument);
-
- Type[] firstWildcardArgumentUpperBounds = firstWildcardArgument.getUpperBounds();
- assertLenghtOne(firstWildcardArgumentUpperBounds);
- Type firstWildcardArgumentUpperBoundsType = firstWildcardArgumentUpperBounds[0];
-
- Type[] secondWildcardArgumentUpperBounds = secondWildcardArgument.getUpperBounds();
- assertLenghtOne(secondWildcardArgumentUpperBounds);
- Type secondWildcardArgumentUpperBoundsType = secondWildcardArgumentUpperBounds[0];
-
- assertEquals(firstWildcardArgumentUpperBoundsType, secondWildcardArgumentUpperBoundsType);
-
- assertEquals(typeParameter, firstWildcardArgumentUpperBoundsType);
- assertEquals(typeParameter, secondWildcardArgumentUpperBoundsType);
- }
-
- static class WildcardUnEquality<T> {
- void wildcardUnEquality(Pair<? extends T, ? super T> param) {}
- }
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getTypeParameters",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getGenericParameterTypes",
- args = {}
- )
- })
- @SuppressWarnings("unchecked")
- public void testWildcardUnEquality() throws Exception {
- Class<? extends WildcardUnEquality> clazz = WildcardUnEquality.class;
-
- Method method = clazz.getDeclaredMethod("wildcardUnEquality", Pair.class);
- TypeVariable<?>[] typeParameters = clazz.getTypeParameters();
- assertLenghtOne(typeParameters);
- TypeVariable<?> typeParameter = typeParameters[0];
-
- Type[] parameterTypes = method.getGenericParameterTypes();
- assertLenghtOne(parameterTypes);
- Type parameter = parameterTypes[0];
- assertInstanceOf(ParameterizedType.class, parameter);
- ParameterizedType paramType = (ParameterizedType) parameter;
- Type[] actualTypeArguments = paramType.getActualTypeArguments();
- assertEquals(2, actualTypeArguments.length);
-
- Type firstArgument = actualTypeArguments[0];
- assertInstanceOf(WildcardType.class, firstArgument);
- WildcardType firstWildcardArgument = (WildcardType) firstArgument;
- Type secondArgument = actualTypeArguments[1];
- assertInstanceOf(WildcardType.class, secondArgument);
- WildcardType secondWildcardArgument = (WildcardType) secondArgument;
-
- assertNotEquals(firstWildcardArgument, secondWildcardArgument);
-
- Type[] firstWildcardArgumentUpperBounds = firstWildcardArgument.getUpperBounds();
- assertLenghtOne(firstWildcardArgumentUpperBounds);
- Type firstWildcardArgumentUpperBoundsType = firstWildcardArgumentUpperBounds[0];
-
- Type[] secondWildcardArgumentLowerBounds = secondWildcardArgument.getLowerBounds();
- assertLenghtOne(secondWildcardArgumentLowerBounds);
- Type secondWildcardArgumentLoweroundsType = secondWildcardArgumentLowerBounds[0];
-
- assertEquals(firstWildcardArgumentUpperBoundsType, secondWildcardArgumentLoweroundsType);
- assertEquals(typeParameter, firstWildcardArgumentUpperBoundsType);
- assertEquals(typeParameter, secondWildcardArgumentLoweroundsType);
- }
-
- static class MultipleBoundedWildcardUnEquality<T extends Object & Comparable<MultipleBoundedWildcardUnEquality<T>>> {
- void multipleBoundedWildcardUnEquality(Pair<? extends T, ? super T> param) {}
- }
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getTypeParameters",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getGenericParameterTypes",
- args = {}
- )
- })
- @SuppressWarnings("unchecked")
- public void testMultipleBoundedWildcardUnEquality() throws Exception {
- Class<? extends MultipleBoundedWildcardUnEquality> clazz = MultipleBoundedWildcardUnEquality.class;
-
- // new WildcardEquality<Object>().wildcardEquality(new Pair<String,
- // Integer>());
-
- Method method = clazz.getDeclaredMethod("multipleBoundedWildcardUnEquality", Pair.class);
- TypeVariable<?>[] typeParameters = clazz.getTypeParameters();
- assertLenghtOne(typeParameters);
- TypeVariable<?> typeParameter = typeParameters[0];
- Type[] typeParameterBounds = typeParameter.getBounds();
- assertEquals(2, typeParameterBounds.length);
- assertEquals(Object.class, typeParameterBounds[0]);
- assertInstanceOf(ParameterizedType.class, typeParameterBounds[1]);
- ParameterizedType parameterizedType = (ParameterizedType) typeParameterBounds[1];
- assertEquals(Comparable.class, parameterizedType.getRawType());
- Type[] typeArguments = parameterizedType.getActualTypeArguments();
- assertLenghtOne(typeArguments);
- assertInstanceOf(ParameterizedType.class, typeArguments[0]);
- ParameterizedType type = (ParameterizedType) typeArguments[0];
- assertEquals(typeParameter, type.getActualTypeArguments()[0]);
- assertEquals(MultipleBoundedWildcardUnEquality.class, type.getRawType());
-
- Type[] parameterTypes = method.getGenericParameterTypes();
- assertLenghtOne(parameterTypes);
- Type parameter = parameterTypes[0];
- assertInstanceOf(ParameterizedType.class, parameter);
- ParameterizedType paramType = (ParameterizedType) parameter;
- Type[] actualTypeArguments = paramType.getActualTypeArguments();
- assertEquals(2, actualTypeArguments.length);
-
- Type firstArgument = actualTypeArguments[0];
- assertInstanceOf(WildcardType.class, firstArgument);
- WildcardType firstWildcardArgument = (WildcardType) firstArgument;
- Type secondArgument = actualTypeArguments[1];
- assertInstanceOf(WildcardType.class, secondArgument);
- WildcardType secondWildcardArgument = (WildcardType) secondArgument;
-
- assertNotEquals(firstWildcardArgument, secondWildcardArgument);
-
- Type[] firstWildcardArgumentUpperBounds = firstWildcardArgument.getUpperBounds();
- assertLenghtOne(firstWildcardArgumentUpperBounds);
- Type firstWildcardArgumentUpperBoundsType = firstWildcardArgumentUpperBounds[0];
-
- Type[] secondWildcardArgumentLowerBounds = secondWildcardArgument.getLowerBounds();
- assertLenghtOne(secondWildcardArgumentLowerBounds);
- Type secondWildcardArgumentLoweroundsType = secondWildcardArgumentLowerBounds[0];
-
- assertEquals(firstWildcardArgumentUpperBoundsType, secondWildcardArgumentLoweroundsType);
- }
-
- static class MultipleBoundedWildcardEquality<T extends Object & Comparable<MultipleBoundedWildcardEquality<T>>> {
- void multipleBoundedWildcardEquality(Pair<? extends T, ? extends T> param) {}
- }
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getTypeParameters",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "getGenericParameterTypes",
- args = {}
- )
- })
- @SuppressWarnings("unchecked")
- public void testMultipleBoundedWildcard() throws Exception {
- Class<? extends MultipleBoundedWildcardEquality> clazz = MultipleBoundedWildcardEquality.class;
-
- Method method = clazz.getDeclaredMethod("multipleBoundedWildcardEquality", Pair.class);
- TypeVariable<?>[] typeParameters = clazz.getTypeParameters();
- assertLenghtOne(typeParameters);
- TypeVariable<?> typeParameter = typeParameters[0];
- Type[] typeParameterBounds = typeParameter.getBounds();
- assertEquals(2, typeParameterBounds.length);
- assertEquals(Object.class, typeParameterBounds[0]);
- assertInstanceOf(ParameterizedType.class, typeParameterBounds[1]);
- ParameterizedType parameterizedType = (ParameterizedType) typeParameterBounds[1];
- assertEquals(Comparable.class, parameterizedType.getRawType());
- Type[] typeArguments = parameterizedType.getActualTypeArguments();
- assertLenghtOne(typeArguments);
- assertInstanceOf(ParameterizedType.class, typeArguments[0]);
- ParameterizedType type = (ParameterizedType) typeArguments[0];
- assertEquals(typeParameter, type.getActualTypeArguments()[0]);
- assertEquals(MultipleBoundedWildcardEquality.class, type.getRawType());
-
- Type[] parameterTypes = method.getGenericParameterTypes();
- assertLenghtOne(parameterTypes);
- Type parameter = parameterTypes[0];
- assertInstanceOf(ParameterizedType.class, parameter);
- ParameterizedType paramType = (ParameterizedType) parameter;
- Type[] actualTypeArguments = paramType.getActualTypeArguments();
- assertEquals(2, actualTypeArguments.length);
-
- Type firstArgument = actualTypeArguments[0];
- assertInstanceOf(WildcardType.class, firstArgument);
- WildcardType firstWildcardArgument = (WildcardType) firstArgument;
- Type secondArgument = actualTypeArguments[1];
- assertInstanceOf(WildcardType.class, secondArgument);
- WildcardType secondWildcardArgument = (WildcardType) secondArgument;
-
- assertEquals(firstWildcardArgument, secondWildcardArgument);
-
- Type[] firstWildcardArgumentUpperBounds = firstWildcardArgument.getUpperBounds();
- assertLenghtOne(firstWildcardArgumentUpperBounds);
- Type firstWildcardArgumentUpperBoundsType = firstWildcardArgumentUpperBounds[0];
-
- Type[] secondWildcardArgumentUpperBounds = secondWildcardArgument.getUpperBounds();
- assertLenghtOne(secondWildcardArgumentUpperBounds);
- Type secondWildcardArgumentLoweroundsType = secondWildcardArgumentUpperBounds[0];
-
- assertEquals(firstWildcardArgumentUpperBoundsType, secondWildcardArgumentLoweroundsType);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/GenericReflectionTestsBase.java b/luni/src/test/java/tests/api/java/lang/reflect/GenericReflectionTestsBase.java
deleted file mode 100644
index b9f8da5..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/GenericReflectionTestsBase.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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 tests.api.java.lang.reflect;
-
-import java.lang.reflect.Method;
-import java.lang.reflect.TypeVariable;
-
-import junit.framework.TestCase;
-
-public class GenericReflectionTestsBase extends TestCase{
-
- /**
- * Returns the type parameter of the declaring method.
- *
- * @param method
- * the declaring method
- * @return the type parameter of the method
- */
- public TypeVariable<Method> getTypeParameter(Method method) {
- TypeVariable<Method>[] typeParameters = method.getTypeParameters();
- assertLenghtOne(typeParameters);
- TypeVariable<Method> typeParameter = typeParameters[0];
- return typeParameter;
- }
-
- /**
- * Returns the type parameter of the declaring class.
- *
- * @param method
- * the declaring method.
- * @return the type parameter of the method.
- */
- @SuppressWarnings("unchecked")
- public TypeVariable<Class> getTypeParameter(Class<?> clazz) {
- TypeVariable[] typeParameters = clazz.getTypeParameters();
- assertLenghtOne(typeParameters);
- TypeVariable<Class> typeVariable = typeParameters[0];
- assertEquals(clazz, typeVariable.getGenericDeclaration());
- assertEquals("T", typeVariable.getName());
- return typeVariable;
- }
-
- public static void assertLenghtOne(Object[] array) {
- TestCase.assertEquals("Array does NOT contain exactly one element.", 1, array.length);
- }
-
- public static void assertLenghtZero(Object[] array) {
- TestCase.assertEquals("Array has more than zero elements.", 0, array.length);
- }
-
- public static void assertInstanceOf(Class<?> expectedClass, Object actual) {
- TestCase.assertTrue(actual.getClass().getName() + " is not instance of :" + expectedClass.getName(), expectedClass
- .isInstance(actual));
- }
-
- public static void assertNotEquals(Object expected, Object actual) {
- TestCase.assertFalse(actual.toString() + " has not to be equal to " + expected.toString(), expected.equals(actual));
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/GenericSignatureFormatErrorTest.java b/luni/src/test/java/tests/api/java/lang/reflect/GenericSignatureFormatErrorTest.java
deleted file mode 100644
index eb5cead..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/GenericSignatureFormatErrorTest.java
+++ /dev/null
@@ -1,110 +0,0 @@
-package tests.api.java.lang.reflect;
-
-import dalvik.annotation.AndroidOnly;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.system.DexFile;
-
-import junit.framework.TestCase;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.lang.reflect.GenericSignatureFormatError;
-import java.lang.reflect.TypeVariable;
-
-@TestTargetClass(GenericSignatureFormatError.class)
-public class GenericSignatureFormatErrorTest extends TestCase{
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "GenericSignatureFormatError",
- args = {}
- )
- public void test_Constructor() {
- assertNotNull(new GenericSignatureFormatError());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "GenericSignatureFormatError",
- args = {}
- )
- public void test_readResource() throws Exception {
- File tf = File.createTempFile("classes", ".dex");
- // System.out.println("GenericSignatureFormatErrorTest:"
- // +tf.getAbsolutePath()+", canRead: "+tf.canRead()
- // +", canWrite: "+tf.canWrite());
- InputStream is = this.getClass().getResourceAsStream("dex1.bytes");
- assertNotNull(is);
- }
-
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "GenericSignatureFormatError",
- args = {}
- )
- @AndroidOnly("Uses Android specific class dalvik.system.DexFile " +
- "for loading classes.")
- public void test_signatureFormatError() throws Exception {
- /*
- * dex1.bytes is a jar file with a classes.dex in it.
- * the classes.dex was javac'ed, dx'ed and patched
- * with the following java file:
- *
- * package demo;
- * public class HelloWorld<U> {
- * public HelloWorld(U t) {}
- * }
- *
- * patch:
- * the string constant (class generics signature string)
- * "<U:" was changed to "<<:"
- *
- */
-
- File tf = File.createTempFile("classes", ".dex");
- // System.out.println("GenericSignatureFormatErrorTest:" +
- // tf.getAbsolutePath() + ", canRead: " + tf.canRead() +
- // ", canWrite: "+tf.canWrite());
- InputStream is = this.getClass().getResourceAsStream("dex1.bytes");
- assertNotNull(is);
- OutputStream fos = new FileOutputStream(tf);
- copy(is, fos);
- fos.close();
-
-
- // class signature string "<U:" was changed to "<<:"
- //System.out.println("file length:"+tf.length());
- try {
- DexFile df = new DexFile(tf);
- Class clazz = df.loadClass("demo/HelloWorld", this.getClass().getClassLoader());
- TypeVariable[] tvs = clazz.getTypeParameters();
- fail("expecting a GenericSignatureFormatError");
- // for (TypeVariable tv : tvs) {
- // System.out.println("tv:"+tv.toString());
- // }
- } catch (GenericSignatureFormatError gsfe) {
- // expected
- }
- }
-
- private void copy(InputStream is, OutputStream os) {
- try {
- int b;
- while ((b = is.read()) != -1) {
- os.write(b);
- }
- is.close();
- } catch (IOException ex) {
- throw new RuntimeException("io error", ex);
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/GenericTypesTest.java b/luni/src/test/java/tests/api/java/lang/reflect/GenericTypesTest.java
deleted file mode 100644
index d02a1ba..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/GenericTypesTest.java
+++ /dev/null
@@ -1,288 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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 tests.api.java.lang.reflect;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Method;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-
-
-/**
- * Tests type parameters declared on classes.
- */
-@TestTargetClass(Constructor.class)
-public class GenericTypesTest extends GenericReflectionTestsBase {
-
- static class GenericType<T>{
- T methodGenericType(T t){ return t;}
- @SuppressWarnings("hiding")
- <T> T hidingMethodGenericType(T t){ return t;}
- static <T> T staticMethodGenericType(T t){ return t;}
- }
-
- static class MultipleBoundedGenericTypes<T,S extends T>{
- void multipleBoundedGenericTypesTS(T t, S s){}
- }
-
- static class SimpleInheritance <T> extends GenericType<T>{}
-
- static class ConstructorGenericType<T>{
- ConstructorGenericType(T t){}
- }
-
- static class InnerClassTest<T>{
- class InnerClass {
- InnerClass(T t) {}
- void innerMethod(T t){}
- }
- }
-
- static class ExceptionTest<T extends Exception>{
- void exceptionTest() throws T{}
- class InnerClass{
- void innerExceptionTest() throws T{}
- }
- }
-
- static interface InterfaceTest<T>{}
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Check positive functionality.",
- method = "getGenericParameterTypes",
- args = {}
- )
- @SuppressWarnings("unchecked")
- public void testConstructorGenericType() throws Exception {
- Class<? extends ConstructorGenericType> clazz = ConstructorGenericType.class;
- TypeVariable<Class> typeVariable = getTypeParameter(clazz);
- Constructor<?> constructor = clazz.getDeclaredConstructor(Object.class);
- Type[] genericParameterTypes = constructor.getGenericParameterTypes();
- assertLenghtOne(genericParameterTypes);
- Type parameterType = genericParameterTypes[0];
-
- assertEquals(typeVariable, parameterType);
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "getGenericParameterTypes",
- args = {}
- )
- @SuppressWarnings("unchecked")
- public void testStaticMethodGenericType() throws Exception {
- Class<? extends GenericType> clazz = GenericType.class;
- TypeVariable<Class> typeVariable = getTypeParameter(clazz);
-
- Method method = clazz.getDeclaredMethod("staticMethodGenericType", Object.class);
- Type[] genericParameterTypes = method.getGenericParameterTypes();
- assertLenghtOne(genericParameterTypes);
- Type parameterType = genericParameterTypes[0];
- assertNotEquals(typeVariable, parameterType);
- assertInstanceOf(TypeVariable.class, parameterType);
- assertEquals(method, ((TypeVariable)parameterType).getGenericDeclaration());
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "getGenericParameterTypes",
- args = {}
- )
- @SuppressWarnings("unchecked")
- public void testHidingMethodGenericType() throws Exception {
- Class<? extends GenericType> clazz = GenericType.class;
- TypeVariable<Class> typeVariable = getTypeParameter(clazz);
-
- Method method = clazz.getDeclaredMethod("hidingMethodGenericType", Object.class);
- Type[] genericParameterTypes = method.getGenericParameterTypes();
- assertLenghtOne(genericParameterTypes);
- Type parameterType = genericParameterTypes[0];
- assertNotEquals(typeVariable, parameterType);
- assertInstanceOf(TypeVariable.class, parameterType);
- assertEquals(method, ((TypeVariable)parameterType).getGenericDeclaration());
- }
-
- static class MultipleGenericTypes<T,S>{
- void multipleGenericTypesT(T t){}
- void multipleGenericTypesS(S s){}
- void multipleGenericTypesTS(T t, S s){}
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "getGenericParameterTypes",
- args = {}
- )
- @SuppressWarnings("unchecked")
- public void testMultipleGenericTypes() throws Exception {
- //Type parameters
- Class<? extends MultipleGenericTypes> clazz = MultipleGenericTypes.class;
- TypeVariable<?>[] typeParameters = clazz.getTypeParameters();
- assertEquals(2, typeParameters.length);
- TypeVariable<?> typeVariableT = typeParameters[0];
- assertEquals(clazz, typeVariableT.getGenericDeclaration());
- assertEquals("T", typeVariableT.getName());
- TypeVariable<?> typeVariableS = typeParameters[1];
- assertEquals("S", typeVariableS.getName());
- assertEquals(clazz, typeVariableS.getGenericDeclaration());
-
- // multipleGenericTypesT
- Method multipleGenericTypesT = clazz.getDeclaredMethod("multipleGenericTypesT", new Class[]{Object.class});
- Type[] multipleGenericTypesTTypes = multipleGenericTypesT.getGenericParameterTypes();
- assertLenghtOne(multipleGenericTypesTTypes);
- Type multipleGenericTypesTType = multipleGenericTypesTTypes[0];
- assertEquals(typeVariableT, multipleGenericTypesTType);
-
- // multipleGenericTypesS
- Method multipleGenericTypesS = clazz.getDeclaredMethod("multipleGenericTypesS", new Class[]{Object.class});
- Type[] multipleGenericTypesSTypes = multipleGenericTypesS.getGenericParameterTypes();
- assertLenghtOne(multipleGenericTypesSTypes);
- Type multipleGenericTypesSType = multipleGenericTypesSTypes[0];
- assertEquals(typeVariableS, multipleGenericTypesSType);
-
- // multipleGenericTypesS
- Method multipleGenericTypesTS = clazz.getDeclaredMethod("multipleGenericTypesTS", new Class[]{Object.class, Object.class});
- Type[] multipleGenericTypesTSTypes = multipleGenericTypesTS.getGenericParameterTypes();
- assertEquals(2, multipleGenericTypesTSTypes.length);
- Type multipleGenericTypesTSTypeT = multipleGenericTypesTSTypes[0];
- assertEquals(typeVariableT, multipleGenericTypesTSTypeT);
- Type multipleGenericTypesTSTypeS = multipleGenericTypesTSTypes[1];
- assertEquals(typeVariableS, multipleGenericTypesTSTypeS);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTypeParameters",
- args = {}
- )
- @SuppressWarnings("unchecked")
- public void testMultipleBoundedGenericTypes() throws Exception {
- //Type parameters
- Class<? extends MultipleBoundedGenericTypes> clazz = MultipleBoundedGenericTypes.class;
- TypeVariable<?>[] typeParameters = clazz.getTypeParameters();
- assertEquals(2, typeParameters.length);
- TypeVariable<?> typeVariableT = typeParameters[0];
- assertEquals(clazz, typeVariableT.getGenericDeclaration());
- assertEquals("T", typeVariableT.getName());
- TypeVariable<?> typeVariableS = typeParameters[1];
- assertEquals("S", typeVariableS.getName());
- assertEquals(clazz, typeVariableS.getGenericDeclaration());
- Type[] boundsS = typeVariableS.getBounds();
- assertLenghtOne(boundsS);
- Type boundS = boundsS[0];
- assertEquals(typeVariableT, boundS);
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- method = "getGenericParameterTypes",
- args = {}
- )
- @SuppressWarnings("unchecked")
- public void testSimpleInheritance() throws Exception {
- Class<? extends SimpleInheritance> clazz = SimpleInheritance.class;
- TypeVariable<Class> subTypeVariable = getTypeParameter(clazz);
-
- assertInstanceOf(ParameterizedType.class, clazz.getGenericSuperclass());
- ParameterizedType parameterizedSuperType = (ParameterizedType) clazz.getGenericSuperclass();
- assertInstanceOf(Class.class, parameterizedSuperType.getRawType());
-
- TypeVariable<Class> superTypeParameter = getTypeParameter((Class<?>)parameterizedSuperType.getRawType());
- TypeVariable<Class> typeParameter = getTypeParameter(GenericType.class);
- assertEquals(superTypeParameter, typeParameter);
-
- assertNotEquals(subTypeVariable, superTypeParameter);
-
- Type[] actualTypeArguments = parameterizedSuperType.getActualTypeArguments();
- assertLenghtOne(actualTypeArguments);
- assertInstanceOf(TypeVariable.class, actualTypeArguments[0]);
- TypeVariable actualSuperTypeVariable = (TypeVariable) actualTypeArguments[0];
- assertEquals(subTypeVariable, actualSuperTypeVariable);
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Doesn't check exceptions.",
- method = "getGenericParameterTypes",
- args = {}
- )
- @SuppressWarnings("unchecked")
- public void testInnerClassTest() throws Exception {
- Class<? extends InnerClassTest> clazz =InnerClassTest.class;
- TypeVariable<Class> typeVariable = getTypeParameter(clazz);
-
- Class<?>[] declaredClasses = clazz.getDeclaredClasses();
- assertLenghtOne(declaredClasses);
- Class<?> innerClazz = declaredClasses[0];
- assertEquals(InnerClassTest.InnerClass.class, innerClazz);
-
- //constructor
- Constructor<?>[] declaredConstructors = innerClazz.getDeclaredConstructors();
- assertLenghtOne(declaredConstructors);
- Constructor<?> declaredConstructor = declaredConstructors[0];
- Type[] genericParameterTypes = declaredConstructor.getGenericParameterTypes();
- assertLenghtOne(genericParameterTypes);
- assertEquals(typeVariable, genericParameterTypes[0]);
- assertInstanceOf(TypeVariable.class, genericParameterTypes[0]);
- TypeVariable<?> constructorTypeVariable = (TypeVariable<?>) genericParameterTypes[0];
- assertEquals(clazz ,constructorTypeVariable.getGenericDeclaration());
-
- //method
- Method declaredMethods = innerClazz.getDeclaredMethod("innerMethod", Object.class);
- Type[] methodParameterTypes = declaredMethods.getGenericParameterTypes();
- assertLenghtOne(methodParameterTypes);
- assertEquals(typeVariable, methodParameterTypes[0]);
- assertInstanceOf(TypeVariable.class, methodParameterTypes[0]);
- TypeVariable<?> methodTypeVariable = (TypeVariable<?>) methodParameterTypes[0];
- assertEquals(clazz, methodTypeVariable.getGenericDeclaration());
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Exceptions are not verified.",
- method = "getGenericExceptionTypes",
- args = {}
- )
- @SuppressWarnings("unchecked")
- public void testException() throws Exception {
- Class<? extends ExceptionTest> clazz = ExceptionTest.class;
- TypeVariable<Class> typeVariable = getTypeParameter(clazz);
- Method method = clazz.getDeclaredMethod("exceptionTest");
- Type[] genericExceptionTypes = method.getGenericExceptionTypes();
- assertLenghtOne(genericExceptionTypes);
- assertEquals(typeVariable, genericExceptionTypes[0]);
-
- Class<?>[] declaredClasses = clazz.getDeclaredClasses();
- assertLenghtOne(declaredClasses);
- Class<?> innerClazz = declaredClasses[0];
- assertEquals(ExceptionTest.InnerClass.class, innerClazz);
-
- //method
- Method declaredMethods = innerClazz.getDeclaredMethod("innerExceptionTest");
- Type[] exceptionTypes = declaredMethods.getGenericExceptionTypes();
- assertLenghtOne(exceptionTypes);
- assertEquals(typeVariable, exceptionTypes[0]);
- assertInstanceOf(TypeVariable.class, exceptionTypes[0]);
- TypeVariable<?> methodTypeVariable = (TypeVariable<?>) exceptionTypes[0];
- assertEquals(clazz, methodTypeVariable.getGenericDeclaration());
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/InvocationTargetExceptionTest.java b/luni/src/test/java/tests/api/java/lang/reflect/InvocationTargetExceptionTest.java
deleted file mode 100644
index 54fa42a..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/InvocationTargetExceptionTest.java
+++ /dev/null
@@ -1,359 +0,0 @@
-/*
- * 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 tests.api.java.lang.reflect;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.ByteArrayOutputStream;
-import java.io.CharArrayWriter;
-import java.io.PrintStream;
-import java.io.PrintWriter;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-
-@TestTargetClass(InvocationTargetException.class)
-public class InvocationTargetExceptionTest extends junit.framework.TestCase {
-
- static class TestMethod {
- public TestMethod() {
- }
-
- public void voidMethod() throws IllegalArgumentException {
- }
-
- public void parmTest(int x, short y, String s, boolean bool, Object o,
- long l, byte b, char c, double d, float f) {
- }
-
- public int intMethod() {
- return 1;
- }
-
- public static final void printTest(int x, short y, String s,
- boolean bool, Object o, long l, byte b, char c, double d,
- float f) {
- }
-
- public double doubleMethod() {
- return 1.0;
- }
-
- public short shortMethod() {
- return (short) 1;
- }
-
- public byte byteMethod() {
- return (byte) 1;
- }
-
- public float floatMethod() {
- return 1.0f;
- }
-
- public long longMethod() {
- return 1l;
- }
-
- public char charMethod() {
- return 'T';
- }
-
- public Object objectMethod() {
- return new Object();
- }
-
- private static void prstatic() {
- }
-
- public static void pustatic() {
- }
-
- public static synchronized void pustatsynch() {
- }
-
- public static int invokeStaticTest() {
- return 1;
- }
-
- public int invokeInstanceTest() {
- return 1;
- }
-
- private int privateInvokeTest() {
- return 1;
- }
-
- public int invokeExceptionTest() throws NullPointerException {
- throw new NullPointerException();
- }
-
- public static synchronized native void pustatsynchnat();
-
- }
-
- abstract class AbstractTestMethod {
- public abstract void puabs();
- }
-
- class SubInvocationTargetException extends InvocationTargetException {}
-
- /**
- * @tests java.lang.reflect.InvocationTargetException#InvocationTargetException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InvocationTargetException",
- args = {}
- )
- public void test_Constructor() throws Exception {
- Constructor<InvocationTargetException> ctor = InvocationTargetException.class
- .getDeclaredConstructor();
- assertNotNull("Parameterless constructor does not exist.", ctor);
- assertTrue("Constructor is not protected", Modifier.isProtected(ctor
- .getModifiers()));
- //create an instance of a subtype using this constructor
- SubInvocationTargetException subException = new SubInvocationTargetException();
- }
-
- /**
- * @tests java.lang.reflect.InvocationTargetException#InvocationTargetException(java.lang.Throwable)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InvocationTargetException",
- args = {java.lang.Throwable.class}
- )
- public void test_ConstructorLjava_lang_Throwable() {
- // Test for method
- // java.lang.reflect.InvocationTargetException(java.lang.Throwable)
- try {
- Method mth = TestMethod.class.getDeclaredMethod(
- "invokeExceptionTest", new Class[0]);
- Object[] args = { Object.class };
- Object ret = mth.invoke(new TestMethod(), new Object[0]);
- } catch (InvocationTargetException e) {
- // Correct behaviour
- return;
- } catch (NoSuchMethodException e) {
- } catch (IllegalAccessException e) {
- }
- fail("Failed to throw exception");
- }
-
- /**
- * @tests java.lang.reflect.InvocationTargetException#InvocationTargetException(java.lang.Throwable,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InvocationTargetException",
- args = {java.lang.Throwable.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_ThrowableLjava_lang_String() {
- // Test for method
- // java.lang.reflect.InvocationTargetException(java.lang.Throwable,
- // java.lang.String)
- try {
- Method mth = TestMethod.class.getDeclaredMethod(
- "invokeExceptionTest", new Class[0]);
- Object[] args = { Object.class };
- Object ret = mth.invoke(new TestMethod(), new Object[0]);
- } catch (InvocationTargetException e) {
- // Correct behaviour
- return;
- } catch (NoSuchMethodException e) {
- ;
- } catch (IllegalAccessException e) {
- }
- fail("Failed to throw exception");
- }
-
- /**
- * @tests java.lang.reflect.InvocationTargetException#getTargetException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTargetException",
- args = {}
- )
- public void test_getTargetException() {
- // Test for method java.lang.Throwable
- // java.lang.reflect.InvocationTargetException.getTargetException()
- try {
- Method mth = TestMethod.class.getDeclaredMethod(
- "invokeExceptionTest", new Class[0]);
- Object[] args = { Object.class };
- Object ret = mth.invoke(new TestMethod(), new Object[0]);
- } catch (InvocationTargetException e) {
- // Correct behaviour
- assertTrue("Returned incorrect target exception", e
- .getTargetException() instanceof NullPointerException);
- return;
- } catch (Exception e) {
- fail("Exception during constructor test : " + e.getMessage());
- }
- fail("Failed to throw exception");
- }
-
- /**
- * @tests java.lang.reflect.InvocationTargetException#getCause()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCause",
- args = {}
- )
- public void test_getCause() {
- // java.lang.reflect.InvocationTargetException.getCause()
- try {
- Method mth = TestMethod.class.getDeclaredMethod(
- "invokeExceptionTest", new Class[0]);
- Object[] args = {Object.class};
- Object ret = mth.invoke(new TestMethod(), new Object[0]);
- } catch (InvocationTargetException e) {
- // Correct behaviour
- assertTrue("Returned incorrect cause",
- e.getCause() instanceof NullPointerException);
- return;
- } catch (Exception e) {
- fail("Exception during InvocationTargetException test : "
- + e.getMessage());
- }
- fail("Failed to throw exception");
- }
-
- /**
- * @tests java.lang.reflect.InvocationTargetException#printStackTrace()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "printStackTrace",
- args = {}
- )
- public void test_printStackTrace() {
- // Test for method void
- // java.lang.reflect.InvocationTargetException.printStackTrace()
- try {
- ByteArrayOutputStream bao = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(bao);
- PrintStream oldErr = System.err;
- System.setErr(ps);
- InvocationTargetException ite = new InvocationTargetException(null);
- ite.printStackTrace();
- System.setErr(oldErr);
-
- String s = new String(bao.toByteArray());
-
- assertTrue("Incorrect Stack trace: " + s, s != null
- && s.length() > 300);
- } catch (Exception e) {
- fail("printStackTrace() caused exception : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.lang.reflect.InvocationTargetException#printStackTrace(java.io.PrintStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "printStackTrace",
- args = {java.io.PrintStream.class}
- )
- public void test_printStackTraceLjava_io_PrintStream() {
- // Test for method void
- // java.lang.reflect.InvocationTargetException.printStackTrace(java.io.PrintStream)
- assertTrue("Tested via test_printStackTrace().", true);
- ByteArrayOutputStream bao = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(bao);
- InvocationTargetException ite = new InvocationTargetException(
- new InvocationTargetException(null));
- ite.printStackTrace(ps);
- String s = bao.toString();
- assertTrue("printStackTrace failed." + s.length(), s != null
- && s.length() > 400);
- }
-
- /**
- * @tests java.lang.reflect.InvocationTargetException#printStackTrace(java.io.PrintWriter)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "printStackTrace",
- args = {java.io.PrintWriter.class}
- )
- public void test_printStackTraceLjava_io_PrintWriter() {
- // Test for method void
- // java.lang.reflect.InvocationTargetException.printStackTrace(java.io.PrintWriter)
- try {
- PrintWriter pw;
- InvocationTargetException ite;
- String s;
- CharArrayWriter caw = new CharArrayWriter();
- pw = new PrintWriter(caw);
- ite = new InvocationTargetException(new InvocationTargetException(
- null));
- ite.printStackTrace(pw);
-
- s = caw.toString();
- assertTrue("printStackTrace failed." + s.length(), s != null
- && s.length() > 400);
- pw.close();
-
- ByteArrayOutputStream bao = new ByteArrayOutputStream();
- pw = new PrintWriter(bao);
- ite = new InvocationTargetException(new InvocationTargetException(
- null));
- ite.printStackTrace(pw);
-
- pw.flush(); // Test will fail if this line removed.
- s = bao.toString();
- assertTrue("printStackTrace failed." + s.length(), s != null
- && s.length() > 400);
-
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/MalformedParameterizedTypeExceptionTests.java b/luni/src/test/java/tests/api/java/lang/reflect/MalformedParameterizedTypeExceptionTests.java
deleted file mode 100644
index 1bb83cd..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/MalformedParameterizedTypeExceptionTests.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package tests.api.java.lang.reflect;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.MalformedParameterizedTypeException;
-import java.lang.reflect.Modifier;
-
-@TestTargetClass(MalformedParameterizedTypeException.class)
-public class MalformedParameterizedTypeExceptionTests extends junit.framework.TestCase {
-
- /**
- * @tests java.lang.reflect.MalformedParameterizedTypeException#MalformedParameterizedTypeException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Since this constructor is never invoked, this test only verifies its existence.",
- method = "MalformedParameterizedTypeException",
- args = {}
- )
- public void test_Constructor() throws Exception {
- Constructor<MalformedParameterizedTypeException> ctor = MalformedParameterizedTypeException.class
- .getDeclaredConstructor();
- assertNotNull("Parameterless constructor does not exist.", ctor);
- assertTrue("Constructor is not protected", Modifier.isPublic(ctor
- .getModifiers()));
- assertNotNull(ctor.newInstance());
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/MethodTest.java b/luni/src/test/java/tests/api/java/lang/reflect/MethodTest.java
deleted file mode 100644
index 884bc8c..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/MethodTest.java
+++ /dev/null
@@ -1,980 +0,0 @@
-/*
- * 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 tests.api.java.lang.reflect;
-
-import java.lang.annotation.Annotation;
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-import java.util.HashSet;
-import java.util.Set;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(Method.class)
-public class MethodTest extends junit.framework.TestCase {
-
- static class TestMethod {
- public TestMethod() {
- }
-
- public void voidMethod() throws IllegalArgumentException {
- }
-
- public void parmTest(int x, short y, String s, boolean bool, Object o,
- long l, byte b, char c, double d, float f) {
- }
-
- public int intMethod() {
- return 1;
- }
-
- public static final void printTest(int x, short y, String s,
- boolean bool, Object o, long l, byte b, char c, double d,
- float f) {
- }
-
- public double doubleMethod() {
- return 1.0;
- }
-
- public short shortMethod() {
- return (short) 1;
- }
-
- public byte byteMethod() {
- return (byte) 1;
- }
-
- public float floatMethod() {
- return 1.0f;
- }
-
- public long longMethod() {
- return 1l;
- }
-
- public char charMethod() {
- return 'T';
- }
-
- public Object objectMethod() {
- return new Object();
- }
-
- private static void prstatic() {
- }
-
- public static void pustatic() {
- }
-
- public static synchronized void pustatsynch() {
- }
-
- public static int invokeStaticTest() {
- return 1;
- }
-
- public int invokeInstanceTest() {
- return 1;
- }
-
- private int privateInvokeTest() {
- return 1;
- }
-
- public int invokeExceptionTest() throws NullPointerException {
- throw new NullPointerException();
- }
-
- public static synchronized native void pustatsynchnat();
-
- public void publicVoidVarargs(Object... param){}
- public void publicVoidArray(Object[] param){}
-
- public void annotatedParameter(@TestAnno @Deprecated int a,
- @Deprecated int b, int c) {
- }
-
- @Deprecated
- @TestAnno
- public void annotatedMethod(){}
-
- public void hashCodeTest(int i){}
- public void hashCodeTest(String s){}
-
- public void invokeCastTest1(byte param) {
- }
-
- public void invokeCastTest1(short param) {
- }
-
- public void invokeCastTest1(int param) {
- }
-
- public void invokeCastTest1(long param) {
- }
-
- public void invokeCastTest1(float param) {
- }
-
- public void invokeCastTest1(double param) {
- }
-
- public void invokeCastTest1(char param) {
- }
-
- public void invokeCastTest1(boolean param) {
- }
- }
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target({ElementType.PARAMETER, ElementType.METHOD})
- public static @interface TestAnno{
- public static final String DEFAULT_VALUE = "DEFAULT_VALUE";
-
- String value() default DEFAULT_VALUE;
- }
-
- abstract class AbstractTestMethod {
- public abstract void puabs();
- }
-
- class TestMethodSub extends TestMethod {
- public int invokeInstanceTest() {
- return 0;
- }
- }
-
- static interface IBrigeTest<T>{
- T m();
- }
-
- static class BrigeTest implements IBrigeTest<String> {
- public String m(){ return null; }
- }
-
- static class ExceptionTest<T extends Exception>{
- @SuppressWarnings("unused")
- void exceptionTest() throws T{}
- }
-
- static class GenericReturnType<T> {
- T returnGeneric(){return null;}
- }
-
- static class GenericString<T> {
- public static final String GENERIC =
- "T tests.api.java.lang.reflect.MethodTest$GenericString.genericString(T)";
- T genericString(T t) {
- return null;
- }
- }
-
- /**
- * @tests java.lang.reflect.Method#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean
- // java.lang.reflect.Method.equals(java.lang.Object)
-
- Method m1 = null, m2 = null;
- try {
- m1 = TestMethod.class.getMethod("invokeInstanceTest", new Class[0]);
- m2 = TestMethodSub.class.getMethod("invokeInstanceTest",
- new Class[0]);
- } catch (Exception e) {
- fail("Exception during equals test : " + e.getMessage());
- }
- assertTrue("Overriden method returned equal", !m1.equals(m2));
- assertTrue("Same method returned not-equal", m1.equals(m1));
- try {
- m1 = TestMethod.class.getMethod("invokeStaticTest", new Class[0]);
- m2 = TestMethodSub.class
- .getMethod("invokeStaticTest", new Class[0]);
- } catch (Exception e) {
- fail("Exception during equals test : " + e.getMessage());
- }
- assertTrue("Inherited method returned not-equal", m1.equals(m2));
- }
-
- /**
- * @tests java.lang.reflect.Method#getDeclaringClass()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaringClass",
- args = {}
- )
- public void test_getDeclaringClass() {
- // Test for method java.lang.Class
- // java.lang.reflect.Method.getDeclaringClass()
-
- Method[] mths;
-
- try {
- mths = TestMethod.class.getDeclaredMethods();
- assertTrue("Returned incorrect declaring class: "
- + mths[0].getDeclaringClass().toString(), mths[0]
- .getDeclaringClass().equals(TestMethod.class));
- } catch (Exception e) {
- fail("Exception during getDeclaringClass test: "
- + e.toString());
- }
- }
-
- /**
- * @tests java.lang.reflect.Method#getExceptionTypes()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getExceptionTypes",
- args = {}
- )
- public void test_getExceptionTypes() {
- // Test for method java.lang.Class []
- // java.lang.reflect.Method.getExceptionTypes()
-
- try {
- Method mth = TestMethod.class.getMethod("voidMethod", new Class[0]);
- Class[] ex = mth.getExceptionTypes();
- assertEquals("Returned incorrect number of exceptions",
- 1, ex.length);
- assertTrue("Returned incorrect exception type", ex[0]
- .equals(IllegalArgumentException.class));
- mth = TestMethod.class.getMethod("intMethod", new Class[0]);
- ex = mth.getExceptionTypes();
- assertEquals("Returned incorrect number of exceptions",
- 0, ex.length);
- } catch (Exception e) {
- fail("Exception during getExceptionTypes: " + e.toString());
- }
-
- }
-
- /**
- * @tests java.lang.reflect.Method#getModifiers()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getModifiers",
- args = {}
- )
- public void test_getModifiers() {
- // Test for method int java.lang.reflect.Method.getModifiers()
-
- Class cl = TestMethod.class;
- int mods = 0;
- Method mth = null;
- int mask = 0;
- try {
- mth = cl.getMethod("pustatic", new Class[0]);
- mods = mth.getModifiers();
- } catch (Exception e) {
- fail("Exception during getModfiers test: " + e.toString());
- }
- mask = Modifier.PUBLIC | Modifier.STATIC;
- assertTrue("Incorrect modifiers returned", (mods | mask) == mask);
- try {
- mth = cl.getDeclaredMethod("prstatic", new Class[0]);
- mods = mth.getModifiers();
- } catch (Exception e) {
- fail("Exception during getModfiers test: " + e.toString());
- }
- mask = Modifier.PRIVATE | Modifier.STATIC;
- assertTrue("Incorrect modifiers returned", (mods | mask) == mask);
- try {
- mth = cl.getDeclaredMethod("pustatsynch", new Class[0]);
- mods = mth.getModifiers();
- } catch (Exception e) {
- fail("Exception during getModfiers test: " + e.toString());
- }
- mask = (Modifier.PUBLIC | Modifier.STATIC) | Modifier.SYNCHRONIZED;
- assertTrue("Incorrect modifiers returned", (mods | mask) == mask);
- try {
- mth = cl.getDeclaredMethod("pustatsynchnat", new Class[0]);
- mods = mth.getModifiers();
- } catch (Exception e) {
- fail("Exception during getModfiers test: " + e.toString());
- }
- mask = ((Modifier.PUBLIC | Modifier.STATIC) | Modifier.SYNCHRONIZED)
- | Modifier.NATIVE;
- assertTrue("Incorrect modifiers returned", (mods | mask) == mask);
- cl = AbstractTestMethod.class;
- try {
- mth = cl.getDeclaredMethod("puabs", new Class[0]);
- mods = mth.getModifiers();
- } catch (Exception e) {
- fail("Exception during getModfiers test: " + e.toString());
- }
- mask = Modifier.PUBLIC | Modifier.ABSTRACT;
- assertTrue("Incorrect modifiers returned", (mods | mask) == mask);
- }
-
- /**
- * @tests java.lang.reflect.Method#getName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getName",
- args = {}
- )
- public void test_getName() {
- // Test for method java.lang.String java.lang.reflect.Method.getName()
- Method mth = null;
- try {
- mth = TestMethod.class.getMethod("voidMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getMethodName(): " + e.toString());
- }
- assertEquals("Returned incorrect method name",
- "voidMethod", mth.getName());
- }
-
- /**
- * @tests java.lang.reflect.Method#isVarArgs()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isVarArgs",
- args = {}
- )
- public void test_isVarArgs() throws Exception {
- Method mth = TestMethod.class.getMethod("publicVoidVarargs",
- Object[].class);
- assertTrue("Varargs method stated as non vararg.", mth.isVarArgs());
-
- mth = TestMethod.class.getDeclaredMethod("publicVoidArray",
- Object[].class);
- assertFalse("Non varargs method stated as vararg.", mth.isVarArgs());
- }
-
- /**
- * @tests java.lang.reflect.Method#isBridge()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isBridge",
- args = {}
- )
- public void test_isBridge() throws Exception {
- Method[] declaredMethods = BrigeTest.class.getDeclaredMethods();
- assertEquals("Bridge method not generated.", 2, declaredMethods.length);
- boolean foundBridgeMethod = false;
- for (Method method : declaredMethods) {
- if (method.getReturnType().equals(Object.class)) {
- assertTrue("Bridge method not stated as bridge.", method
- .isBridge());
- foundBridgeMethod = true;
- }
- }
- assertTrue("Bridge method not found.", foundBridgeMethod);
- }
-
- /**
- * @tests java.lang.reflect.Method#isSynthetic()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isSynthetic",
- args = {}
- )
- public void test_isSynthetic() throws Exception {
- Method[] declaredMethods = BrigeTest.class.getDeclaredMethods();
- assertEquals("Synthetic method not generated.", 2,
- declaredMethods.length);
- boolean foundSyntheticMethod = false;
- for (Method method : declaredMethods) {
- if (method.getReturnType().equals(Object.class)) {
- assertTrue("Synthetic method not stated as synthetic.", method
- .isSynthetic());
- foundSyntheticMethod = true;
- }
- }
- assertTrue("Synthetic method not found.", foundSyntheticMethod);
- }
- /**
- * @tests java.lang.reflect.Method#getParameterAnnotations()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getParameterAnnotations",
- args = {}
- )
- public void test_getParameterAnnotations() throws Exception {
- Method method = TestMethod.class.getDeclaredMethod(
- "annotatedParameter", new Class[] {
- int.class, int.class, int.class});
- Annotation[][] annotations = method.getParameterAnnotations();
- assertEquals(3, annotations.length);
- assertEquals(
- "Wrong number of annotations returned for first parameter", 2,
- annotations[0].length);
- Set<Class<?>> annotationSet = new HashSet<Class<?>>();
- annotationSet.add(annotations[0][0].annotationType());
- annotationSet.add(annotations[0][1].annotationType());
- assertTrue("Missing TestAnno annotation", annotationSet
- .contains(TestAnno.class));
- assertTrue("Missing Deprecated annotation", annotationSet
- .contains(Deprecated.class));
-
- assertEquals(
- "Wrong number of annotations returned for second parameter",
- 1, annotations[1].length);
- annotationSet = new HashSet<Class<?>>();
- annotationSet.add(annotations[1][0].annotationType());
- assertTrue("Missing Deprecated annotation", annotationSet
- .contains(Deprecated.class));
- assertEquals(
- "Wrong number of annotations returned for third parameter", 0,
- annotations[2].length);
- }
-
- /**
- * @tests java.lang.reflect.Method#getDeclaredAnnotations()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaredAnnotations",
- args = {}
- )
- public void test_getDeclaredAnnotations() throws Exception {
- Method method = TestMethod.class.getDeclaredMethod("annotatedMethod");
- Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
- assertEquals(2, declaredAnnotations.length);
-
- Set<Class<?>> annotationSet = new HashSet<Class<?>>();
- annotationSet.add(declaredAnnotations[0].annotationType());
- annotationSet.add(declaredAnnotations[1].annotationType());
- assertTrue("Missing TestAnno annotation", annotationSet
- .contains(TestAnno.class));
- assertTrue("Missing Deprecated annotation", annotationSet
- .contains(Deprecated.class));
- }
-
- /**
- * @tests java.lang.reflect.Method#getDefaultValue()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Missing tests for TypeNotPresentException",
- method = "getDefaultValue",
- args = {}
- )
- public void test_getDefaultValue() throws Exception {
- Method method = TestAnno.class.getDeclaredMethod("value");
- assertEquals("Wrong default value returned", TestAnno.DEFAULT_VALUE,
- method.getDefaultValue());
- }
-
- /**
- * @tests java.lang.reflect.Method#getDefaultValue()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Missing tests for GenericSignatureFormatError,TypeNotPresentException, MalformedParameterizedTypeException",
- method = "getGenericExceptionTypes",
- args = {}
- )
- public void test_getGenericExceptionTypes() throws Exception {
- Method method = ExceptionTest.class.getDeclaredMethod("exceptionTest");
- Type[] genericExceptionTypes = method.getGenericExceptionTypes();
- assertEquals(1, genericExceptionTypes.length);
- assertTrue(genericExceptionTypes[0] instanceof TypeVariable<?>);
- @SuppressWarnings("unchecked")
- TypeVariable<Class<ExceptionTest<?>>> tv =
- (TypeVariable<Class<ExceptionTest<?>>>) genericExceptionTypes[0];
- assertEquals("T", tv.getName());
- }
-
- /**
- * @tests java.lang.reflect.Method#getGenericReturnType()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Missing tests for GenericSignatureFormatError,TypeNotPresentException, MalformedParameterizedTypeException",
- method = "getGenericReturnType",
- args = {}
- )
- public void test_getGenericReturnType() throws Exception {
- Method method = GenericReturnType.class
- .getDeclaredMethod("returnGeneric");
- Type returnType = method.getGenericReturnType();
- assertNotNull("getGenericReturnType returned null", returnType);
- assertTrue(returnType instanceof TypeVariable<?>);
- @SuppressWarnings("unchecked")
- TypeVariable<Class<ExceptionTest<?>>> tv =
- (TypeVariable<Class<ExceptionTest<?>>>) returnType;
- assertEquals("T", tv.getName());
- }
-
-
- /**
- * @tests java.lang.reflect.Method#toGenericString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toGenericString",
- args = {}
- )
- public void test_toGenericString() throws Exception {
- Method method = GenericString.class.getDeclaredMethod("genericString",
- Object.class);
- assertEquals("Wrong generic String returned", GenericString.GENERIC,
- method.toGenericString());
- }
-
-
-
-
-
-
- /**
- * @tests java.lang.reflect.Method#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() throws Exception {
- Method mth0 = TestMethod.class.getMethod("hashCodeTest", String.class);
- Method mth1 = TestMethod.class.getDeclaredMethod("hashCodeTest",
- int.class);
- assertEquals("Methods with same name did not return same hashCode.",
- mth0.hashCode(), mth1.hashCode());
- }
-
- /**
- * @tests java.lang.reflect.Method#getParameterTypes()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getParameterTypes",
- args = {}
- )
- public void test_getParameterTypes() {
- // Test for method java.lang.Class []
- // java.lang.reflect.Method.getParameterTypes()
- Class cl = TestMethod.class;
- Method mth = null;
- Class[] parms = null;
- Method[] methods = null;
- Class[] plist = { int.class, short.class, String.class, boolean.class,
- Object.class, long.class, byte.class, char.class, double.class,
- float.class };
- try {
- mth = cl.getMethod("voidMethod", new Class[0]);
- parms = mth.getParameterTypes();
- } catch (Exception e) {
- fail("Exception during getParameterTypes test: "
- + e.toString());
- }
- assertEquals("Returned incorrect parameterTypes", 0, parms.length);
- try {
- mth = cl.getMethod("parmTest", plist);
- parms = mth.getParameterTypes();
- } catch (Exception e) {
- fail("Exception during getParameterTypes test: "
- + e.toString());
- }
- assertTrue("Invalid number of parameters returned",
- plist.length == parms.length);
- for (int i = 0; i < plist.length; i++)
- assertTrue("Incorrect parameter returned", plist[i]
- .equals(parms[i]));
-
- // Test same method. but this time pull it from the list of methods
- // rather than asking for it explicitly
- methods = cl.getDeclaredMethods();
-
- int i;
- for (i = 0; i < methods.length; i++)
- if (methods[i].getName().equals("parmTest")) {
- mth = methods[i];
- i = methods.length + 1;
- }
- if (i < methods.length) {
- parms = mth.getParameterTypes();
- assertTrue("Incorrect number of parameters returned",
- parms.length == plist.length);
- for (i = 0; i < plist.length; i++)
- assertTrue("Incorrect parameter returned", plist[i]
- .equals(parms[i]));
- }
- }
-
- /**
- * @tests java.lang.reflect.Method#getReturnType()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getReturnType",
- args = {}
- )
- public void test_getReturnType() {
- // Test for method java.lang.Class
- // java.lang.reflect.Method.getReturnType()
- Class cl = TestMethod.class;
- Method mth = null;
- try {
- mth = cl.getMethod("charMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getReturnType test : " + e.getMessage());
- }
- assertTrue("Gave incorrect returne type, wanted char", mth
- .getReturnType().equals(char.class));
- try {
- mth = cl.getMethod("longMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getReturnType test : " + e.getMessage());
- }
- assertTrue("Gave incorrect returne type, wanted long", mth
- .getReturnType().equals(long.class));
- try {
- mth = cl.getMethod("shortMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getReturnType test : " + e.getMessage());
- }
- assertTrue("Gave incorrect returne type, wanted short", mth
- .getReturnType().equals(short.class));
- try {
- mth = cl.getMethod("intMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getReturnType test : " + e.getMessage());
- }
- assertTrue("Gave incorrect returne type, wanted int: "
- + mth.getReturnType(), mth.getReturnType().equals(int.class));
- try {
- mth = cl.getMethod("doubleMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getReturnType test : " + e.getMessage());
- }
- assertTrue("Gave incorrect returne type, wanted double", mth
- .getReturnType().equals(double.class));
- try {
- mth = cl.getMethod("byteMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getReturnType test : " + e.getMessage());
- }
- assertTrue("Gave incorrect returne type, wanted byte", mth
- .getReturnType().equals(byte.class));
- try {
- mth = cl.getMethod("byteMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getReturnType test:" + e.toString());
- }
- assertTrue("Gave incorrect returne type, wanted byte", mth
- .getReturnType().equals(byte.class));
- try {
- mth = cl.getMethod("objectMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getReturnType test : " + e.getMessage());
- }
- assertTrue("Gave incorrect returne type, wanted Object", mth
- .getReturnType().equals(Object.class));
-
- try {
- mth = cl.getMethod("voidMethod", new Class[0]);
- } catch (Exception e) {
- fail("Exception during getReturnType test : " + e.getMessage());
- }
- assertTrue("Gave incorrect returne type, wanted void", mth
- .getReturnType().equals(void.class));
- }
-
- /**
- * @tests java.lang.reflect.Method#invoke(java.lang.Object,
- * java.lang.Object[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "invoke",
- args = {java.lang.Object.class, java.lang.Object[].class}
- )
- public void test_invokeLjava_lang_Object$Ljava_lang_Object() throws Exception{
- // Test for method java.lang.Object
- // java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object
- // [])
- Class cl = TestMethod.class;
- Class[] dcl = new Class[0];
-
- // Get and invoke a static method
- Method mth = cl.getDeclaredMethod("invokeStaticTest", dcl);
- Object ret = mth.invoke(null, new Object[0]);
- assertEquals("Invoke returned incorrect value", 1, ((Integer) ret)
- .intValue());
-
- // Get and invoke an instance method
- mth = cl.getDeclaredMethod("invokeInstanceTest", dcl);
- ret = mth.invoke(new TestMethod(), new Object[0]);
- assertEquals("Invoke returned incorrect value", 1, ((Integer) ret)
- .intValue());
-
- // Get and attempt to invoke a private method
- mth = cl.getDeclaredMethod("privateInvokeTest", dcl);
- try {
- ret = mth.invoke(new TestMethod(), new Object[0]);
- } catch (IllegalAccessException e) {
- // Correct behaviour
- } catch (Exception e) {
- fail("Exception during invoke test : " + e.getMessage());
- }
- // Generate an IllegalArgumentException
- mth = cl.getDeclaredMethod("invokeInstanceTest", dcl);
-
- try {
- Object[] args = { Object.class };
- ret = mth.invoke(new TestMethod(), args);
- } catch (IllegalArgumentException e) {
- // Correct behaviour
- } catch (Exception e) {
- fail("Exception during invoke test : " + e.getMessage());
- }
-
- // Generate a NullPointerException
- mth = cl.getDeclaredMethod("invokeInstanceTest", dcl);
-
- try {
- ret = mth.invoke(null, new Object[0]);
- } catch (NullPointerException e) {
- // Correct behaviour
- } catch (Exception e) {
- fail("Exception during invoke test : " + e.getMessage());
- }
-
- // Generate an InvocationTargetException
- mth = cl.getDeclaredMethod("invokeExceptionTest", dcl);
- try {
- ret = mth.invoke(new TestMethod(), new Object[0]);
- } catch (InvocationTargetException e) {
- // Correct behaviour
- } catch (Exception e) {
- fail("Exception during invoke test : " + e.getMessage());
- }
-
- TestMethod testMethod = new TestMethod();
- Method methods[] = cl.getMethods();
- for (int i = 0; i < methods.length; i++) {
- if (methods[i].getName().startsWith("invokeCastTest1")) {
- Class param = methods[i].getParameterTypes()[0];
-
- try {
- methods[i].invoke(testMethod, new Object[] { new Byte(
- (byte) 1) });
- assertTrue("invalid invoke with Byte: " + methods[i],
- param == Byte.TYPE || param == Short.TYPE
- || param == Integer.TYPE
- || param == Long.TYPE
- || param == Float.TYPE
- || param == Double.TYPE);
- } catch (Exception e) {
- assertTrue("Byte invalid exception: " + e,
- e instanceof IllegalArgumentException);
- assertTrue("Byte invalid failure: " + methods[i],
- param == Boolean.TYPE || param == Character.TYPE);
- }
-
- try {
- methods[i].invoke(testMethod, new Object[] { new Short(
- (short) 1) });
- assertTrue("invalid invoke with Short: " + methods[i],
- param == Short.TYPE || param == Integer.TYPE
- || param == Long.TYPE
- || param == Float.TYPE
- || param == Double.TYPE);
- } catch (Exception e) {
- assertTrue("Short invalid exception: " + e,
- e instanceof IllegalArgumentException);
- assertTrue("Short invalid failure: " + methods[i],
- param == Byte.TYPE || param == Boolean.TYPE
- || param == Character.TYPE);
- }
-
- try {
- methods[i].invoke(testMethod,
- new Object[] { new Integer(1) });
- assertTrue("invalid invoke with Integer: " + methods[i],
- param == Integer.TYPE || param == Long.TYPE
- || param == Float.TYPE
- || param == Double.TYPE);
- } catch (Exception e) {
- assertTrue("Integer invalid exception: " + e,
- e instanceof IllegalArgumentException);
- assertTrue("Integer invalid failure: " + methods[i],
- param == Byte.TYPE || param == Short.TYPE
- || param == Boolean.TYPE
- || param == Character.TYPE);
- }
-
- try {
- methods[i].invoke(testMethod, new Object[] { new Long(1) });
- assertTrue("invalid invoke with Long: " + methods[i],
- param == Long.TYPE || param == Float.TYPE
- || param == Double.TYPE);
- } catch (Exception e) {
- assertTrue("Long invalid exception: " + e,
- e instanceof IllegalArgumentException);
- assertTrue("Long invalid failure: " + methods[i],
- param == Byte.TYPE || param == Short.TYPE
- || param == Integer.TYPE
- || param == Boolean.TYPE
- || param == Character.TYPE);
- }
-
- try {
- methods[i].invoke(testMethod, new Object[] { new Character(
- 'a') });
- assertTrue("invalid invoke with Character: " + methods[i],
- param == Character.TYPE || param == Integer.TYPE
- || param == Long.TYPE
- || param == Float.TYPE
- || param == Double.TYPE);
- } catch (Exception e) {
- assertTrue("Character invalid exception: " + e,
- e instanceof IllegalArgumentException);
- assertTrue("Character invalid failure: " + methods[i],
- param == Byte.TYPE || param == Short.TYPE
- || param == Boolean.TYPE);
- }
-
- try {
- methods[i]
- .invoke(testMethod, new Object[] { new Float(1) });
- assertTrue("invalid invoke with Float: " + methods[i],
- param == Float.TYPE || param == Double.TYPE);
- } catch (Exception e) {
- assertTrue("Float invalid exception: " + e,
- e instanceof IllegalArgumentException);
- assertTrue("Float invalid failure: " + methods[i],
- param == Byte.TYPE || param == Short.TYPE
- || param == Integer.TYPE
- || param == Long.TYPE
- || param == Boolean.TYPE
- || param == Character.TYPE);
- }
-
- try {
- methods[i].invoke(testMethod,
- new Object[] { new Double(1) });
- assertTrue("invalid invoke with Double: " + methods[i],
- param == Double.TYPE);
- } catch (Exception e) {
- assertTrue("Double invalid exception: " + e,
- e instanceof IllegalArgumentException);
- assertTrue("Double invalid failure: " + methods[i],
- param == Byte.TYPE || param == Short.TYPE
- || param == Integer.TYPE
- || param == Long.TYPE
- || param == Boolean.TYPE
- || param == Character.TYPE
- || param == Float.TYPE);
- }
-
- try {
- methods[i].invoke(testMethod, new Object[] { new Boolean(
- true) });
- assertTrue("invalid invoke with Boolean: " + methods[i],
- param == Boolean.TYPE);
- } catch (Exception e) {
- assertTrue("Boolean invalid exception: " + e,
- e instanceof IllegalArgumentException);
- assertTrue("Boolean invalid failure: " + methods[i],
- param == Byte.TYPE || param == Short.TYPE
- || param == Integer.TYPE
- || param == Long.TYPE
- || param == Character.TYPE
- || param == Float.TYPE
- || param == Double.TYPE);
- }
- }
- }
- }
-
- /**
- * @tests java.lang.reflect.Method#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.lang.reflect.Method.toString()
- Method mth = null;
- Class[] parms = { int.class, short.class, String.class, boolean.class,
- Object.class, long.class, byte.class, char.class, double.class,
- float.class };
- try {
-
- mth = TestMethod.class.getDeclaredMethod("printTest", parms);
- } catch (Exception e) {
- fail("Exception during toString test : " + e.getMessage());
- }
-
- assertTrue(
- "Returned incorrect string for method: " + mth.toString(),
- mth
- .toString()
- .equals(
- "public static final void tests.api.java.lang.reflect.MethodTest$TestMethod.printTest(int,short,java.lang.String,boolean,java.lang.Object,long,byte,char,double,float)"));
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/ModifierTest.java b/luni/src/test/java/tests/api/java/lang/reflect/ModifierTest.java
deleted file mode 100644
index ab6e14b..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/ModifierTest.java
+++ /dev/null
@@ -1,289 +0,0 @@
-/*
- * 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 tests.api.java.lang.reflect;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.lang.reflect.Modifier;
-
-@TestTargetClass(Modifier.class)
-public class ModifierTest extends junit.framework.TestCase {
-
- private static final int ALL_FLAGS = 0x7FF;
-
- /**
- * @tests java.lang.reflect.Modifier#Modifier()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "The only thing I can do",
- method = "Modifier",
- args = {}
- )
- public void test_Constructor() {
- assertNotNull(new Modifier());
- }
-
- /**
- * @tests java.lang.reflect.Modifier#isAbstract(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isAbstract",
- args = {int.class}
- )
- public void test_isAbstractI() {
- // Test for method boolean java.lang.reflect.Modifier.isAbstract(int)
- assertTrue("ABSTRACT returned false", Modifier.isAbstract(ALL_FLAGS));
- assertTrue("ABSTRACT returned false", Modifier
- .isAbstract(Modifier.ABSTRACT));
- assertTrue("Non-ABSTRACT returned true", !Modifier
- .isAbstract(Modifier.TRANSIENT));
- }
-
- /**
- * @tests java.lang.reflect.Modifier#isFinal(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isFinal",
- args = {int.class}
- )
- public void test_isFinalI() {
- // Test for method boolean java.lang.reflect.Modifier.isFinal(int)
- assertTrue("FINAL returned false", Modifier.isFinal(ALL_FLAGS));
- assertTrue("FINAL returned false", Modifier.isFinal(Modifier.FINAL));
- assertTrue("Non-FINAL returned true", !Modifier
- .isFinal(Modifier.TRANSIENT));
- }
-
- /**
- * @tests java.lang.reflect.Modifier#isInterface(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isInterface",
- args = {int.class}
- )
- public void test_isInterfaceI() {
- // Test for method boolean java.lang.reflect.Modifier.isInterface(int)
- assertTrue("INTERFACE returned false", Modifier.isInterface(ALL_FLAGS));
- assertTrue("INTERFACE returned false", Modifier
- .isInterface(Modifier.INTERFACE));
- assertTrue("Non-INTERFACE returned true", !Modifier
- .isInterface(Modifier.TRANSIENT));
- }
-
- /**
- * @tests java.lang.reflect.Modifier#isNative(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isNative",
- args = {int.class}
- )
- public void test_isNativeI() {
- // Test for method boolean java.lang.reflect.Modifier.isNative(int)
- assertTrue("NATIVE returned false", Modifier.isNative(ALL_FLAGS));
- assertTrue("NATIVE returned false", Modifier.isNative(Modifier.NATIVE));
- assertTrue("Non-NATIVE returned true", !Modifier
- .isNative(Modifier.TRANSIENT));
- }
-
- /**
- * @tests java.lang.reflect.Modifier#isPrivate(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isPrivate",
- args = {int.class}
- )
- public void test_isPrivateI() {
- // Test for method boolean java.lang.reflect.Modifier.isPrivate(int)
- assertTrue("PRIVATE returned false", Modifier.isPrivate(ALL_FLAGS));
- assertTrue("PRIVATE returned false", Modifier
- .isPrivate(Modifier.PRIVATE));
- assertTrue("Non-PRIVATE returned true", !Modifier
- .isPrivate(Modifier.TRANSIENT));
- }
-
- /**
- * @tests java.lang.reflect.Modifier#isProtected(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isProtected",
- args = {int.class}
- )
- public void test_isProtectedI() {
- // Test for method boolean java.lang.reflect.Modifier.isProtected(int)
- assertTrue("PROTECTED returned false", Modifier.isProtected(ALL_FLAGS));
- assertTrue("PROTECTED returned false", Modifier
- .isProtected(Modifier.PROTECTED));
- assertTrue("Non-PROTECTED returned true", !Modifier
- .isProtected(Modifier.TRANSIENT));
- }
-
- /**
- * @tests java.lang.reflect.Modifier#isPublic(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isPublic",
- args = {int.class}
- )
- public void test_isPublicI() {
- // Test for method boolean java.lang.reflect.Modifier.isPublic(int)
- assertTrue("PUBLIC returned false", Modifier.isPublic(ALL_FLAGS));
- assertTrue("PUBLIC returned false", Modifier.isPublic(Modifier.PUBLIC));
- assertTrue("Non-PUBLIC returned true", !Modifier
- .isPublic(Modifier.TRANSIENT));
- }
-
- /**
- * @tests java.lang.reflect.Modifier#isStatic(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isStatic",
- args = {int.class}
- )
- public void test_isStaticI() {
- // Test for method boolean java.lang.reflect.Modifier.isStatic(int)
- assertTrue("STATIC returned false", Modifier.isStatic(ALL_FLAGS));
- assertTrue("STATIC returned false", Modifier.isStatic(Modifier.STATIC));
- assertTrue("Non-STATIC returned true", !Modifier
- .isStatic(Modifier.TRANSIENT));
- }
-
- /**
- * @tests java.lang.reflect.Modifier#isStrict(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isStrict",
- args = {int.class}
- )
- public void test_isStrictI() {
- // Test for method boolean java.lang.reflect.Modifier.isStrict(int)
- assertTrue("STRICT returned false", Modifier.isStrict(Modifier.STRICT));
- assertTrue("Non-STRICT returned true", !Modifier
- .isStrict(Modifier.TRANSIENT));
- }
-
- /**
- * @tests java.lang.reflect.Modifier#isSynchronized(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isSynchronized",
- args = {int.class}
- )
- public void test_isSynchronizedI() {
- // Test for method boolean
- // java.lang.reflect.Modifier.isSynchronized(int)
- assertTrue("Synchronized returned false", Modifier
- .isSynchronized(ALL_FLAGS));
- assertTrue("Non-Synchronized returned true", !Modifier
- .isSynchronized(Modifier.VOLATILE));
- }
-
- /**
- * @tests java.lang.reflect.Modifier#isTransient(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isTransient",
- args = {int.class}
- )
- public void test_isTransientI() {
- // Test for method boolean java.lang.reflect.Modifier.isTransient(int)
- assertTrue("Transient returned false", Modifier.isTransient(ALL_FLAGS));
- assertTrue("Transient returned false", Modifier
- .isTransient(Modifier.TRANSIENT));
- assertTrue("Non-Transient returned true", !Modifier
- .isTransient(Modifier.VOLATILE));
- }
-
- /**
- * @tests java.lang.reflect.Modifier#isVolatile(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isVolatile",
- args = {int.class}
- )
- public void test_isVolatileI() {
- // Test for method boolean java.lang.reflect.Modifier.isVolatile(int)
- assertTrue("Volatile returned false", Modifier.isVolatile(ALL_FLAGS));
- assertTrue("Volatile returned false", Modifier
- .isVolatile(Modifier.VOLATILE));
- assertTrue("Non-Volatile returned true", !Modifier
- .isVolatile(Modifier.TRANSIENT));
- }
-
- /**
- * @tests java.lang.reflect.Modifier#toString(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {int.class}
- )
- public void test_toStringI() {
- // Test for method java.lang.String
- // java.lang.reflect.Modifier.toString(int)
- assertTrue("Returned incorrect string value: "
- + Modifier.toString(java.lang.reflect.Modifier.PUBLIC
- + java.lang.reflect.Modifier.ABSTRACT), Modifier
- .toString(
- java.lang.reflect.Modifier.PUBLIC
- + java.lang.reflect.Modifier.ABSTRACT).equals(
- "public abstract"));
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/ParameterizedTypeTest.java b/luni/src/test/java/tests/api/java/lang/reflect/ParameterizedTypeTest.java
deleted file mode 100644
index adeb9e2..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/ParameterizedTypeTest.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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 tests.api.java.lang.reflect;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-
-/**
- * Tests parameterized types and their properties.
- */
-@TestTargetClass(ParameterizedType.class)
-public class ParameterizedTypeTest extends GenericReflectionTestsBase {
-
- static class A<T>{}
- static class B extends A<String>{}
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Missing tests for TypeNotPresentException, MalformedParametrizedTypeException",
- method = "getActualTypeArguments",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Missing tests for TypeNotPresentException, MalformedParametrizedTypeException",
- method = "getOwnerType",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Missing tests for TypeNotPresentException, MalformedParametrizedTypeException",
- method = "getRawType",
- args = {}
- )
- })
- public void testStringParameterizedSuperClass() {
- Class<? extends B> clazz = B.class;
- Type genericSuperclass = clazz.getGenericSuperclass();
- assertInstanceOf(ParameterizedType.class, genericSuperclass);
- ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
- assertEquals(ParameterizedTypeTest.class, parameterizedType.getOwnerType());
- assertEquals(A.class, parameterizedType.getRawType());
-
- Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
- assertLenghtOne(actualTypeArguments);
- assertEquals(String.class, actualTypeArguments[0]);
- }
-
- static class C<T>{}
- static class D<T> extends C<T>{}
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Missing tests for TypeNotPresentException, MalformedParametrizedTypeException",
- method = "getActualTypeArguments",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Missing tests for TypeNotPresentException, MalformedParametrizedTypeException",
- method = "getOwnerType",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Missing tests for TypeNotPresentException, MalformedParametrizedTypeException",
- method = "getRawType",
- args = {}
- )
- })
- public void testTypeParameterizedSuperClass() {
- Class<? extends D> clazz = D.class;
- Type genericSuperclass = clazz.getGenericSuperclass();
- assertInstanceOf(ParameterizedType.class, genericSuperclass);
- ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
- assertEquals(ParameterizedTypeTest.class, parameterizedType.getOwnerType());
- assertEquals(C.class, parameterizedType.getRawType());
-
- Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
- assertLenghtOne(actualTypeArguments);
- assertEquals(getTypeParameter(D.class), actualTypeArguments[0]);
- }
-
- static class E<T>{}
- static class F<T>{
- E<T> e;
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Missing tests for TypeNotPresentException, MalformedParametrizedTypeException",
- method = "getActualTypeArguments",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Missing tests for TypeNotPresentException, MalformedParametrizedTypeException",
- method = "getOwnerType",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Missing tests for TypeNotPresentException, MalformedParametrizedTypeException",
- method = "getRawType",
- args = {}
- )
- })
- public void testParameterizedMemeber() throws Exception{
- Class<? extends F> clazz = F.class;
- Field field = clazz.getDeclaredField("e");
- assertInstanceOf(ParameterizedType.class, field.getGenericType());
- ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
- assertEquals(ParameterizedTypeTest.class, parameterizedType.getOwnerType());
- assertEquals(E.class, parameterizedType.getRawType());
-
- Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
- assertLenghtOne(actualTypeArguments);
- assertEquals(getTypeParameter(clazz), actualTypeArguments[0]);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/ProxyTest.java b/luni/src/test/java/tests/api/java/lang/reflect/ProxyTest.java
deleted file mode 100644
index 051d5b2..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/ProxyTest.java
+++ /dev/null
@@ -1,395 +0,0 @@
-/*
- * 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 tests.api.java.lang.reflect;
-
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.lang.reflect.UndeclaredThrowableException;
-
-import tests.support.Support_Proxy_I1;
-import tests.support.Support_Proxy_I2;
-import tests.support.Support_Proxy_ParentException;
-import tests.support.Support_Proxy_SubException;
-
-@TestTargetClass(
- value = Proxy.class,
- untestedMethods= {
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "Interface without implementation. Whether method is " +
- "called from proxy is tested by ProxyTest.",
- clazz = InvocationHandler.class,
- method = "invoke",
- args = { Object.class, Method.class, Object[].class }
- )
- }
-)
-public class ProxyTest extends junit.framework.TestCase {
-
- /*
- * When multiple interfaces define the same method, the list of thrown
- * exceptions are those which can be mapped to another exception in the
- * other method:
- *
- * String foo(String s) throws SubException, LinkageError;
- *
- * UndeclaredThrowableException wrappers any checked exception which is not
- * in the merged list. So ParentException would be wrapped, BUT LinkageError
- * would not be since its not an Error/RuntimeException.
- *
- * interface I1 { String foo(String s) throws ParentException, LinkageError; }
- * interface I2 { String foo(String s) throws SubException, Error; }
- */
-
- interface Broken1 {
- public float method(float _number0, float _number1);
- }
-
- class Broken1Invoke implements InvocationHandler {
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- return args[1];
- }
- }
-
- class ProxyCoonstructorTest extends Proxy {
- protected ProxyCoonstructorTest(InvocationHandler h) {
- super(h);
- }
- }
-
- /**
- * @tests java.lang.reflect.Proxy#getProxyClass(java.lang.ClassLoader,
- * java.lang.Class[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getProxyClass",
- args = {java.lang.ClassLoader.class, java.lang.Class[].class}
- )
- @KnownFailure("Needs investigation")
- public void test_getProxyClassLjava_lang_ClassLoader$Ljava_lang_Class() {
- Class proxy = Proxy.getProxyClass(Support_Proxy_I1.class
- .getClassLoader(), new Class[] { Support_Proxy_I1.class });
-
- assertTrue("Did not create a Proxy subclass ",
- proxy.getSuperclass() == Proxy.class);
- assertTrue("Does not believe its a Proxy class ", Proxy
- .isProxyClass(proxy));
-
- assertTrue("Does not believe it's a Proxy class ", Proxy
- .isProxyClass(Proxy.getProxyClass(null,
- new Class[] { Comparable.class })));
-
- boolean aborted = false;
- try {
- Proxy.getProxyClass(null, new Class[] { Support_Proxy_I1.class,
- Support_Proxy_I2.class });
- } catch (IllegalArgumentException e) {
- aborted = true;
- }
- assertTrue("Default classLoader should not see app class ", aborted);
-
- aborted = false;
- try {
- Proxy.getProxyClass(Support_Proxy_I1.class.getClassLoader(),
- (Class<?>[]) null);
- fail("NPE expected");
- } catch (NullPointerException e) {
- aborted = true;
- }
- assertTrue("NPE not thrown", aborted);
-
- aborted = false;
- try {
- Proxy.getProxyClass(Support_Proxy_I1.class.getClassLoader(),
- new Class<?>[] {Support_Proxy_I1.class, null});
- fail("NPE expected");
- } catch (NullPointerException e) {
- aborted = true;
- }
- assertTrue("NPE not thrown", aborted);
- }
-
- /**
- * @tests java.lang.reflect.Proxy#Proxy(java.lang.reflect.InvocationHandler)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Proxy",
- args = {java.lang.reflect.InvocationHandler.class}
- )
- public void test_ProxyLjava_lang_reflect_InvocationHandler() {
- assertNotNull(new ProxyCoonstructorTest(new InvocationHandler() {
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- return null;
- }
- }));
- }
-
-
-
- /**
- * @tests java.lang.reflect.Proxy#newProxyInstance(java.lang.ClassLoader,
- * java.lang.Class[], java.lang.reflect.InvocationHandler)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "newProxyInstance",
- args = {java.lang.ClassLoader.class, java.lang.Class[].class, java.lang.reflect.InvocationHandler.class}
- )
- public void test_newProxyInstanceLjava_lang_ClassLoader$Ljava_lang_ClassLjava_lang_reflect_InvocationHandler() {
- Object p = Proxy.newProxyInstance(Support_Proxy_I1.class
- .getClassLoader(), new Class[] { Support_Proxy_I1.class,
- Support_Proxy_I2.class }, new InvocationHandler() {
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- if (method.getName().equals("equals"))
- return new Boolean(proxy == args[0]);
- if (method.getName().equals("array"))
- return new int[] { (int) ((long[]) args[0])[1], -1 };
- if (method.getName().equals("string")) {
- if ("".equals(args[0]))
- throw new Support_Proxy_SubException();
- if ("clone".equals(args[0]))
- throw new Support_Proxy_ParentException();
- if ("error".equals(args[0]))
- throw new ArrayStoreException();
- if ("any".equals(args[0]))
- throw new IllegalAccessException();
- }
- return null;
- }
- });
-
- Support_Proxy_I1 proxy = (Support_Proxy_I1) p;
- assertTrue("Failed identity test ", proxy.equals(proxy));
- assertTrue("Failed not equals test ", !proxy.equals(""));
- int[] result = (int[]) proxy.array(new long[] { 100L, -200L });
- assertEquals("Failed primitive type conversion test ", -200, result[0]);
-
- boolean worked = false;
- try {
- proxy.string("");
- } catch (Support_Proxy_SubException e) {
- worked = true;
- } catch (Support_Proxy_ParentException e) { // is never thrown
- }
- assertTrue("Problem converting exception ", worked);
-
- worked = false;
- try {
- proxy.string("clone");
- } catch (Support_Proxy_ParentException e) { // is never thrown
- } catch (UndeclaredThrowableException e) {
- worked = true;
- }
- assertTrue("Problem converting exception ", worked);
-
- worked = false;
- try {
- proxy.string("error");
- } catch (Support_Proxy_ParentException e) { // is never thrown
- } catch (UndeclaredThrowableException e) {
- } catch (RuntimeException e) {
- worked = e.getClass() == ArrayStoreException.class;
- }
- assertTrue("Problem converting exception ", worked);
-
- worked = false;
- try {
- proxy.string("any");
- } catch (Support_Proxy_ParentException e) { // is never thrown
- } catch (UndeclaredThrowableException e) {
- worked = true;
- }
- assertTrue("Problem converting exception ", worked);
-
- Broken1 proxyObject = null;
- try {
- proxyObject = (Broken1) Proxy.newProxyInstance(Broken1.class
- .getClassLoader(), new Class[] { Broken1.class },
- new Broken1Invoke());
- } catch (Throwable e) {
- fail("Failed to create proxy for class: " + Broken1.class + " - "
- + e);
- }
- float brokenResult = proxyObject.method(2.1f, 5.8f);
- assertTrue("Invalid invoke result", brokenResult == 5.8f);
- }
-
- /**
- * @tests java.lang.reflect.Proxy#isProxyClass(java.lang.Class)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isProxyClass",
- args = {java.lang.Class.class}
- )
- public void test_isProxyClassLjava_lang_Class() {
- Class proxy = Proxy.getProxyClass(Support_Proxy_I1.class
- .getClassLoader(), new Class[] { Support_Proxy_I1.class });
-
- class Fake extends Proxy {
- Fake() {
- super(null);
- }
- }
-
- Proxy fake = new Proxy(new InvocationHandler() {
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- return null;
- }
- }) {
- };
-
- assertTrue("Does not believe its a Proxy class ", Proxy
- .isProxyClass(proxy));
- assertTrue("Proxy subclasses do not count ", !Proxy
- .isProxyClass(Fake.class));
- assertTrue("Is not a runtime generated Proxy class ", !Proxy
- .isProxyClass(fake.getClass()));
- boolean thrown = false;
- try{
- Proxy.isProxyClass(null);
- } catch (NullPointerException ex){
- thrown = true;
- }
- assertTrue("NPE not thrown.", thrown);
- }
-
- /**
- * @tests java.lang.reflect.Proxy#getInvocationHandler(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInvocationHandler",
- args = {java.lang.Object.class}
- )
- public void test_getInvocationHandlerLjava_lang_Object() {
- InvocationHandler handler = new InvocationHandler() {
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- return null;
- }
- };
-
- Object p = Proxy.newProxyInstance(Support_Proxy_I1.class
- .getClassLoader(), new Class[] { Support_Proxy_I1.class },
- handler);
-
- assertTrue("Did not return invocation handler ", Proxy
- .getInvocationHandler(p) == handler);
- boolean aborted = false;
- try {
- Proxy.getInvocationHandler("");
- } catch (IllegalArgumentException e) {
- aborted = true;
- }
- assertTrue("Did not detect non proxy object ", aborted);
- }
-
- //Regression Test for HARMONY-2355
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Regression test. Exceptions are not verified.",
- method = "newProxyInstance",
- args = {java.lang.ClassLoader.class, java.lang.Class[].class, java.lang.reflect.InvocationHandler.class}
- )
- public void test_newProxyInstance_withCompatibleReturnTypes() {
- Object o = Proxy
- .newProxyInstance(this.getClass().getClassLoader(),
- new Class[] { ITestReturnObject.class,
- ITestReturnString.class },
- new TestProxyHandler(new TestProxyImpl()));
- assertNotNull(o);
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "IllegalArgumentException is verified.",
- method = "newProxyInstance",
- args = {java.lang.ClassLoader.class, java.lang.Class[].class, java.lang.reflect.InvocationHandler.class}
- )
- public void test_newProxyInstance_withNonCompatibleReturnTypes() {
- try {
- Proxy.newProxyInstance(this.getClass().getClassLoader(),
- new Class[] { ITestReturnInteger.class,
- ITestReturnString.class }, new TestProxyHandler(
- new TestProxyImpl()));
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- }
-
- public static interface ITestReturnObject {
- Object f();
- }
-
- public static interface ITestReturnString {
- String f();
- }
-
- public static interface ITestReturnInteger {
- Integer f();
- }
-
- public static class TestProxyImpl implements ITestReturnObject,
- ITestReturnString {
- public String f() {
- // do nothing
- return null;
- }
- }
-
- public static class TestProxyHandler implements InvocationHandler {
- private Object proxied;
-
- public TestProxyHandler(Object object) {
- proxied = object;
- }
-
- public Object invoke(Object object, Method method, Object[] args)
- throws Throwable {
- // do nothing
- return method.invoke(proxied, args);
- }
-
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/ReflectPermissionTest.java b/luni/src/test/java/tests/api/java/lang/reflect/ReflectPermissionTest.java
deleted file mode 100644
index ed38d80..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/ReflectPermissionTest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * 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 tests.api.java.lang.reflect;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.lang.reflect.ReflectPermission;
-
-@TestTargetClass(ReflectPermission.class)
-public class ReflectPermissionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.lang.reflect.ReflectPermission#ReflectPermission(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ReflectPermission",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.lang.reflect.ReflectPermission(java.lang.String)
- String permString = new ReflectPermission("Blah").toString();
- assertTrue("Incorrect permission constructed", permString.indexOf(
- "java.lang.reflect.ReflectPermission Blah") >= 0);
- }
-
- /**
- * @tests java.lang.reflect.ReflectPermission#ReflectPermission(java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ReflectPermission",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_String() {
- // Test for method java.lang.reflect.ReflectPermission(java.lang.String,
- // java.lang.String)
- assertTrue("Incorrect permission constructed", new ReflectPermission(
- "Blah", "suppressAccessChecks").toString().indexOf(
- "java.lang.reflect.ReflectPermission Blah") >= 0);
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/TypeVariableTest.java b/luni/src/test/java/tests/api/java/lang/reflect/TypeVariableTest.java
deleted file mode 100644
index d316966..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/TypeVariableTest.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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 tests.api.java.lang.reflect;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.Serializable;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Method;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-
-/**
- * Tests type variables and their properties.
- */
-@TestTargetClass(TypeVariable.class)
-public class TypeVariableTest extends GenericReflectionTestsBase {
-
- static class A<T>{}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Tests getGenericDeclaration of a type variable on a class.",
- method = "getGenericDeclaration",
- args = {}
- )
- public void testSimpleTypeVariableOnClass(){
- Class<? extends A> clazz = A.class;
- TypeVariable[] typeParameters = clazz.getTypeParameters();
- assertLenghtOne(typeParameters);
- TypeVariable<Class> typeVariable = typeParameters[0];
- assertEquals(clazz, typeVariable.getGenericDeclaration());
- assertEquals("T", typeVariable.getName());
- Type[] bounds = typeVariable.getBounds();
- assertLenghtOne(bounds);
- assertEquals(Object.class, bounds[0]);
- }
-
- static class B{
- <T> void b(){};
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Tests getGenericDeclaration of a type variable on a method.",
- method = "getGenericDeclaration",
- args = {}
- )
- public void testSimpleTypeVariableOnMethod() throws Exception{
- Class<? extends B> clazz = B.class;
- Method method = clazz.getDeclaredMethod("b");
- TypeVariable<Method>[] typeParameters = method.getTypeParameters();
- assertLenghtOne(typeParameters);
- TypeVariable<Method> typeVariable = typeParameters[0];
- assertEquals(method, typeVariable.getGenericDeclaration());
- assertEquals("T", typeVariable.getName());
- Type[] bounds = typeVariable.getBounds();
- assertLenghtOne(bounds);
- assertEquals(Object.class, bounds[0]);
- }
-
- static class C {
- <T>C(){}
- }
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Interaction test.",
- method = "getGenericDeclaration",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Interaction test.",
- method = "getBounds",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Interaction test.",
- method = "getName",
- args = {}
- )
- })
- public void testSimpleTypeVariableOnConstructor() throws Exception{
- Class<? extends C> clazz = C.class;
- Constructor<?> constructor = clazz.getDeclaredConstructor();
- TypeVariable<?>[] typeParameters = constructor.getTypeParameters();
- assertLenghtOne(typeParameters);
- TypeVariable<?> typeVariable = typeParameters[0];
- assertEquals(constructor, typeVariable.getGenericDeclaration());
- assertEquals("T", typeVariable.getName());
- Type[] bounds = typeVariable.getBounds();
- assertLenghtOne(bounds);
- assertEquals(Object.class, bounds[0]);
- }
-
- static class D<Q,R,S>{}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Interaction test.",
- method = "getGenericDeclaration",
- args = {}
- )
- public void testMultipleTypeVariablesOnClass() throws Exception {
- Class<? extends D> clazz = D.class;
- TypeVariable<?>[] typeParameters = clazz.getTypeParameters();
- assertEquals(3, typeParameters.length);
- assertEquals("Q", typeParameters[0].getName());
- assertEquals(clazz, typeParameters[0].getGenericDeclaration());
-
- assertEquals("R", typeParameters[1].getName());
- assertEquals(clazz, typeParameters[1].getGenericDeclaration());
-
- assertEquals("S", typeParameters[2].getName());
- assertEquals(clazz, typeParameters[2].getGenericDeclaration());
-
- }
-
- static class E {
- <Q,R,S> void e(){}
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getName",
- args = {}
- )
- public void testMultipleTypeVariablesOnMethod() throws Exception {
- Class<? extends E> clazz = E.class;
- Method method = clazz.getDeclaredMethod("e");
-
- TypeVariable<?>[] typeParameters = method.getTypeParameters();
- assertEquals(3, typeParameters.length);
- assertEquals("Q", typeParameters[0].getName());
- assertEquals(method, typeParameters[0].getGenericDeclaration());
-
- assertEquals("R", typeParameters[1].getName());
- assertEquals(method, typeParameters[1].getGenericDeclaration());
-
- assertEquals("S", typeParameters[2].getName());
- assertEquals(method, typeParameters[2].getGenericDeclaration());
- }
-
- static class F {
- <Q,R,S> F(){}
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getName",
- args = {}
- )
- public void testMultipleTypeVariablesOnConstructor() throws Exception {
- Class<? extends F> clazz = F.class;
- Constructor<?> constructor = clazz.getDeclaredConstructor();
-
- TypeVariable<?>[] typeParameters = constructor.getTypeParameters();
- assertEquals(3, typeParameters.length);
- assertEquals("Q", typeParameters[0].getName());
- assertEquals(constructor, typeParameters[0].getGenericDeclaration());
-
- assertEquals("R", typeParameters[1].getName());
- assertEquals(constructor, typeParameters[1].getGenericDeclaration());
-
- assertEquals("S", typeParameters[2].getName());
- assertEquals(constructor, typeParameters[2].getGenericDeclaration());
- }
-
- static class G <T extends Number>{}
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Interaction test, Missing tests for TypeNotPresentException, MalformedParametrizedTypeException",
- method = "getBounds",
- args = {}
- )
- public void testSingleBound() throws Exception {
- Class<? extends G> clazz = G.class;
- TypeVariable[] typeParameters = clazz.getTypeParameters();
- TypeVariable<Class> typeVariable = typeParameters[0];
- Type[] bounds = typeVariable.getBounds();
- assertLenghtOne(bounds);
- assertEquals(Number.class, bounds[0]);
- }
-
- static class H <T extends Number & Serializable >{}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Interaction test., Missing tests for TypeNotPresentException, MalformedParametrizedTypeException",
- method = "getBounds",
- args = {}
- )
- public void testMultipleBound() throws Exception {
- Class<? extends H> clazz = H.class;
- TypeVariable[] typeParameters = clazz.getTypeParameters();
- TypeVariable<Class> typeVariable = typeParameters[0];
- Type[] bounds = typeVariable.getBounds();
- assertEquals(2, bounds.length);
- assertEquals(Number.class, bounds[0]);
- assertEquals(Serializable.class, bounds[1]);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/UndeclaredThrowableExceptionTests.java b/luni/src/test/java/tests/api/java/lang/reflect/UndeclaredThrowableExceptionTests.java
deleted file mode 100644
index 52ebf6d..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/UndeclaredThrowableExceptionTests.java
+++ /dev/null
@@ -1,83 +0,0 @@
-package tests.api.java.lang.reflect;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.EOFException;
-import java.lang.reflect.UndeclaredThrowableException;
-
-@TestTargetClass(UndeclaredThrowableException.class)
-public class UndeclaredThrowableExceptionTests extends TestCase {
-
- private static EOFException throwable = new EOFException();
- private static String msg = "TEST_MSG";
- /**
- * @tests java.lang.reflect.UndeclaredThrowableException#getCause()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCause",
- args = {}
- )
- public void test_getCause() throws Exception {
- UndeclaredThrowableException ute = new UndeclaredThrowableException(
- throwable);
- assertSame("Wrong cause returned", throwable, ute.getCause());
- }
-
- /**
- * @tests java.lang.reflect.UndeclaredThrowableException#getUndeclaredThrowable()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getUndeclaredThrowable",
- args = {}
- )
- public void test_getUndeclaredThrowable() throws Exception {
- UndeclaredThrowableException ute = new UndeclaredThrowableException(
- throwable);
- assertSame("Wrong undeclared throwable returned", throwable, ute
- .getUndeclaredThrowable());
- }
-
- /**
- * @tests java.lang.reflect.UndeclaredThrowableException#UndeclaredThrowableException(java.lang.Throwable)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UndeclaredThrowableException",
- args = {java.lang.Throwable.class}
- )
- public void test_Constructor_Throwable() throws Exception {
- UndeclaredThrowableException e = new UndeclaredThrowableException(
- throwable);
- assertEquals("Wrong cause returned", throwable, e.getCause());
- assertEquals("Wrong throwable returned", throwable, e
- .getUndeclaredThrowable());
- }
-
- /**
- * @tests java.lang.reflect.UndeclaredThrowableException#UndeclaredThrowableException(java.lang.Throwable, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UndeclaredThrowableException",
- args = {java.lang.Throwable.class, java.lang.String.class}
- )
- public void test_Constructor_Throwable_String() throws Exception {
- UndeclaredThrowableException e = new UndeclaredThrowableException(
- throwable, msg);
- assertEquals("Wrong cause returned", throwable, e.getCause());
- assertEquals("Wrong throwable returned", throwable, e
- .getUndeclaredThrowable());
- assertEquals("Wrong message returned", msg, e.getMessage());
- }
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/WildcardTypeTest.java b/luni/src/test/java/tests/api/java/lang/reflect/WildcardTypeTest.java
deleted file mode 100644
index 9a10405..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/WildcardTypeTest.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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 tests.api.java.lang.reflect;
-
-
-import java.lang.reflect.Method;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-import java.lang.reflect.WildcardType;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-/**
- * Tests bounded type parameters declared on methods and bounded wildcards.
- */
-@TestTargetClass(WildcardType.class)
-public class WildcardTypeTest extends GenericReflectionTestsBase {
- @SuppressWarnings({"unchecked", "hiding"})
- static class BoundedWildcardsGenericMethods<T> {
-
- public <T extends BoundedWildcardsGenericMethods> void lowerBoundedParamNoReturn( BoundedWildcardsGenericMethods<? super T> param) {}
-
- public <T extends BoundedWildcardsGenericMethods> void upperBoundedParamNoReturn( BoundedWildcardsGenericMethods<? extends T> param) {}
-
- public <T extends BoundedWildcardsGenericMethods> T lowerBoundedParamReturn(BoundedWildcardsGenericMethods<? super T> param) { return (T) new Object(); }
-
- public <T extends BoundedWildcardsGenericMethods> T upperBoundedParamReturn(BoundedWildcardsGenericMethods<? extends T> param) { return (T) new Object();}
- }
-
- @SuppressWarnings("unchecked")
- private static Class<? extends BoundedWildcardsGenericMethods> clazz = BoundedWildcardsGenericMethods.class;
-
-// /**
-// * Tests that there are is one Type Parameter on the Class itself.
-// */
-// @TestInfo(
-// level = TestLevel.PARTIAL,
-// purpose = "Doesn't check GenericSignatureFormatError.",
-// targets = {
-// @TestTarget(
-// methodName = "getTypeParameters",
-// methodArgs = {}
-// )
-// })
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "",
- clazz = Class.class,
- method = "getTypeParameters",
- args = {}
- )
- public void testBoundedGenericMethods() {
- assertLenghtOne(clazz.getTypeParameters());
- }
-
- /**
- * Tests whether the type parameter is bounded by BoundedGenericMethods like:
- * <T extends BoundedGenericMethods>.
- * @param method the declaring method
- */
- private void checkBoundedTypeParameter(Method method) {
- TypeVariable<Method> typeParameter = getTypeParameter(method);
- assertEquals("T", typeParameter.getName());
- assertEquals(method, typeParameter.getGenericDeclaration());
-
- Type[] bounds = typeParameter.getBounds();
- assertLenghtOne(bounds);
- Type bound = bounds[0];
- assertEquals(BoundedWildcardsGenericMethods.class, bound);
- }
-
- private void checkLowerBoundedParameter(Method method) {
- Type genericParameterType = method.getGenericParameterTypes()[0];
- assertInstanceOf(ParameterizedType.class, genericParameterType);
-
- ParameterizedType parameterizedType = (ParameterizedType) genericParameterType;
-
- Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
- assertLenghtOne(actualTypeArguments);
- assertInstanceOf(WildcardType.class, actualTypeArguments[0]);
-
- WildcardType wildcardType = (WildcardType) actualTypeArguments[0];
-
- Type[] lowerBounds = wildcardType.getLowerBounds();
- assertLenghtOne(lowerBounds);
- Type lowerBound = lowerBounds[0];
- assertEquals(getTypeParameter(method), lowerBound);
-
- Type[] upperBounds = wildcardType.getUpperBounds();
- assertEquals(Object.class, upperBounds[0]);
- }
-
- private void checkUpperBoundedParameter(Method method) {
- assertLenghtOne(method.getGenericParameterTypes());
- Type genericParameterType = method.getGenericParameterTypes()[0];
- assertInstanceOf(ParameterizedType.class, genericParameterType);
-
- ParameterizedType parameterizedType = (ParameterizedType) genericParameterType;
- Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
- assertLenghtOne(actualTypeArguments);
- assertInstanceOf(WildcardType.class, actualTypeArguments[0]);
-
- WildcardType wildcardType = (WildcardType) actualTypeArguments[0];
- assertLenghtZero(wildcardType.getLowerBounds());
-
- Type[] upperBounds = wildcardType.getUpperBounds();
- assertLenghtOne(upperBounds);
- Type upperBound = upperBounds[0];
- assertEquals(getTypeParameter(method), upperBound);
- }
-
- @SuppressWarnings("unchecked")
- private void checkReturnType(Method method) {
- Type genericReturnType = method.getGenericReturnType();
- assertEquals(getTypeParameter(method), genericReturnType);
- assertTrue(genericReturnType instanceof TypeVariable);
-
- TypeVariable<Method> returnTypeVariable = (TypeVariable<Method>) genericReturnType;
- assertEquals(method, returnTypeVariable.getGenericDeclaration());
-
- Type[] bounds = returnTypeVariable.getBounds();
- assertLenghtOne(bounds);
- Type bound = bounds[0];
-
- assertEquals(BoundedWildcardsGenericMethods.class, bound);
- }
-
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Missing tests for TypeNotPresentException, MalformedParametrizedTypeException",
- method = "getUpperBounds",
- args = {}
- )
- public void testUpperBoundedParamNoReturn() throws Exception {
- Method method = clazz.getMethod("upperBoundedParamNoReturn", BoundedWildcardsGenericMethods.class);
- checkBoundedTypeParameter(method);
- checkUpperBoundedParameter(method);
- }
-
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Missing tests for TypeNotPresentException, MalformedParametrizedTypeException",
- method = "getLowerBounds",
- args = {}
- )
- public void testLowerBoundedParamReturn() throws Exception {
- Method method = clazz.getMethod("lowerBoundedParamReturn", BoundedWildcardsGenericMethods.class);
- checkBoundedTypeParameter(method);
- checkLowerBoundedParameter(method);
- checkReturnType(method);
- }
-
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Missing tests for TypeNotPresentException, MalformedParametrizedTypeException",
- method = "getUpperBounds",
- args = {}
- )
- public void testUpperBoundedParamReturn() throws Exception {
- Method method = clazz.getMethod("upperBoundedParamReturn", BoundedWildcardsGenericMethods.class);
- checkBoundedTypeParameter(method);
- checkUpperBoundedParameter(method);
- checkReturnType(method);
- }
-
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Missing tests for TypeNotPresentException, MalformedParametrizedTypeException",
- method = "getLowerBounds",
- args = {}
- )
- public void testLowerBoundedParamNoReturn() throws Exception {
- Method method = clazz.getMethod("lowerBoundedParamNoReturn", BoundedWildcardsGenericMethods.class);
- checkBoundedTypeParameter(method);
- assertLenghtOne(method.getGenericParameterTypes());
- checkLowerBoundedParameter(method);
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/lang/reflect/dex1.bytes b/luni/src/test/java/tests/api/java/lang/reflect/dex1.bytes
deleted file mode 100644
index 4004a59..0000000
--- a/luni/src/test/java/tests/api/java/lang/reflect/dex1.bytes
+++ /dev/null
Binary files differ
diff --git a/luni/src/test/java/tests/api/java/net/AllTests.java b/luni/src/test/java/tests/api/java/net/AllTests.java
deleted file mode 100644
index 5bcb484..0000000
--- a/luni/src/test/java/tests/api/java/net/AllTests.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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 tests.api.java.net;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-/**
- * This is autogenerated source file. Includes tests for package tests.api.java.net;
- */
-
-public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(AllTests.suite());
- }
-
- public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("All tests for package tests.api.java.net;");
- // $JUnit-BEGIN$
-
- suite.addTestSuite(AuthenticatorRequestorTypeTest.class);
- suite.addTestSuite(AuthenticatorTest.class);
- suite.addTestSuite(BindExceptionTest.class);
- suite.addTestSuite(CacheRequestTest.class);
- suite.addTestSuite(CacheResponseTest.class);
- suite.addTestSuite(ConnectExceptionTest.class);
- suite.addTestSuite(CookieHandlerTest.class);
- suite.addTestSuite(DatagramPacketTest.class);
- suite.addTestSuite(DatagramSocketImplFactoryTest.class);
- suite.addTestSuite(DatagramSocketImplTest.class);
- suite.addTestSuite(DatagramSocketTest.class);
- suite.addTestSuite(ExcludedProxyTest.class);
- suite.addTestSuite(FileNameMapTest.class);
- suite.addTestSuite(HttpRetryExceptionTest.class);
- suite.addTestSuite(JarURLConnectionTest.class);
- suite.addTestSuite(MalformedURLExceptionTest.class);
- suite.addTestSuite(MulticastSocketTest.class);
- suite.addTestSuite(NetPermissionTest.class);
- suite.addTestSuite(NetworkInterfaceTest.class);
- suite.addTestSuite(NoRouteToHostExceptionTest.class);
- suite.addTestSuite(PasswordAuthenticationTest.class);
- suite.addTestSuite(PortUnreachableExceptionTest.class);
- suite.addTestSuite(ProtocolExceptionTest.class);
- suite.addTestSuite(ProxySelectorTest.class);
- suite.addTestSuite(ProxyTest.class);
- suite.addTestSuite(ProxyTypeTest.class);
- suite.addTestSuite(ResponseCacheTest.class);
- suite.addTestSuite(SecureCacheResponseTest.class);
- suite.addTestSuite(ServerSocketTest.class);
- suite.addTestSuite(SocketExceptionTest.class);
- suite.addTestSuite(SocketImplTest.class);
- suite.addTestSuite(SocketImplFactoryTest.class);
- suite.addTestSuite(SocketPermissionTest.class);
- suite.addTestSuite(SocketTest.class);
- suite.addTestSuite(SocketTimeoutExceptionTest.class);
- suite.addTestSuite(URISyntaxExceptionTest.class);
- suite.addTestSuite(URITest.class);
- suite.addTestSuite(URLClassLoaderTest.class);
- suite.addTestSuite(URLDecoderTest.class);
- suite.addTestSuite(URLEncoderTest.class);
- suite.addTestSuite(UnknownHostExceptionTest.class);
- suite.addTestSuite(UnknownServiceExceptionTest.class);
- suite.addTestSuite(URLStreamHandlerFactoryTest.class);
- suite.addTestSuite(URLStreamHandlerTest.class);
-
- // $JUnit-END$
- return suite;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/AuthenticatorRequestorTypeTest.java b/luni/src/test/java/tests/api/java/net/AuthenticatorRequestorTypeTest.java
deleted file mode 100644
index cd7c672..0000000
--- a/luni/src/test/java/tests/api/java/net/AuthenticatorRequestorTypeTest.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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 tests.api.java.net;
-
-import junit.framework.TestCase;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.net.Authenticator;
-
-@TestTargetClass(Authenticator.RequestorType.class)
-public class AuthenticatorRequestorTypeTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {java.lang.String.class}
- )
- public void test_valueOfLjava_lang_String() {
- assertEquals(Authenticator.RequestorType.PROXY,
- Authenticator.RequestorType.valueOf("PROXY"));
- assertEquals(Authenticator.RequestorType.SERVER,
- Authenticator.RequestorType.valueOf("SERVER"));
- try {
- Authenticator.RequestorType.valueOf("TEST");
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
- public void test_values () {
- Authenticator.RequestorType[] expectedTypes = {
- Authenticator.RequestorType.PROXY,
- Authenticator.RequestorType.SERVER
- };
-
- Authenticator.RequestorType[] types =
- Authenticator.RequestorType.values();
- assertEquals(expectedTypes.length, types.length);
-
- for(int i = 0; i < expectedTypes.length; i++) {
- assertEquals(expectedTypes[i], types[i]);
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/AuthenticatorTest.java b/luni/src/test/java/tests/api/java/net/AuthenticatorTest.java
deleted file mode 100644
index 65fd079..0000000
--- a/luni/src/test/java/tests/api/java/net/AuthenticatorTest.java
+++ /dev/null
@@ -1,423 +0,0 @@
-/* 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.Authenticator;
-import java.net.InetAddress;
-import java.net.MalformedURLException;
-import java.net.PasswordAuthentication;
-import java.net.URL;
-import java.net.UnknownHostException;
-import java.net.Authenticator.RequestorType;
-import java.security.Permission;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(value = Authenticator.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getRequestingHost",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getRequestingPort",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getRequestingSite",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getRequestingProtocol",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getRequestingPrompt",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getRequestingScheme",
- args = {}
- )}
- )
-public class AuthenticatorTest extends TestCase {
-
- /**
- * @tests java.net.Authenticator.RequestorType#valueOf(String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Test for checking RequestorType values.",
- method = "!Constants",
- args = {}
- )
- public void test_RequestorType_valueOfLjava_lang_String() throws Exception {
- assertEquals(RequestorType.PROXY, Authenticator.RequestorType
- .valueOf("PROXY"));
- assertEquals(RequestorType.SERVER, Authenticator.RequestorType
- .valueOf("SERVER"));
- try {
- RequestorType rt = Authenticator.RequestorType.valueOf("BADNAME");
- fail("Must throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // correct
- }
- // Some old RIs throw IllegalArgumentException
- // Latest RIs throw NullPointerException.
- try {
- Authenticator.RequestorType.valueOf(null);
- fail("Must throw an exception");
- } catch (NullPointerException e) {
- // May be caused by some compilers' code
- } catch (IllegalArgumentException e) {
- // other compilers will throw this
- }
- }
-
- /**
- * @tests java.net.Authenticator.RequestorType#values()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Test for checking RequestorType values.",
- method = "!Constants",
- args = {}
- )
- public void test_RequestorType_values() throws Exception {
- RequestorType[] rt = RequestorType.values();
- assertEquals(RequestorType.PROXY, rt[0]);
- assertEquals(RequestorType.SERVER, rt[1]);
- }
-
- /**
- * @tests java.net.Authenticator#requestPasswordAuthentication(java.net.InetAddress, int, String, String, String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "requestPasswordAuthentication",
- args = {java.net.InetAddress.class, int.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_requestPasswordAuthentication_InetAddress_int_String_String_String() throws Exception {
- // Regression test for Harmony-2413
- MockAuthenticator mock = new MockAuthenticator();
- InetAddress addr = InetAddress.getLocalHost();
- Authenticator.setDefault(mock);
- Authenticator.requestPasswordAuthentication(addr, -1, "http", "promt", "HTTP");
- assertEquals(mock.getRequestorType(), RequestorType.SERVER);
-
- SecurityManager sm = new SecurityManager() {
- final String permissionName = "requestPasswordAuthentication";
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals(permissionName)) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- Authenticator.requestPasswordAuthentication("test_host", addr, -1,
- "http", "promt", "HTTP");
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- Authenticator.setDefault(null);
- }
- }
-
- /**
- * @tests java.net.Authenticator#requestPasswordAuthentication(String, java.net.InetAddress, int, String, String, String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "requestPasswordAuthentication",
- args = {java.lang.String.class, java.net.InetAddress.class, int.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_requestPasswordAuthentication_String_InetAddress_int_String_String_String() throws Exception {
- // Regression test for Harmony-2413
- MockAuthenticator mock = new MockAuthenticator();
- InetAddress addr = InetAddress.getLocalHost();
- Authenticator.setDefault(mock);
- Authenticator.requestPasswordAuthentication("test_host", addr, -1, "http", "promt", "HTTP");
- assertEquals(mock.getRequestorType(), RequestorType.SERVER);
-
- SecurityManager sm = new SecurityManager() {
- final String permissionName = "requestPasswordAuthentication";
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals(permissionName)) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- Authenticator.requestPasswordAuthentication("test_host", addr, -1,
- "http", "promt", "HTTP");
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- Authenticator.setDefault(null);
- }
- }
-
- /**
- *
- * @tests java.net.Authenticator#
- * requestPasswordAuthentication_String_InetAddress_int_String_String_String_URL_Authenticator_RequestorType()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "requestPasswordAuthentication",
- args = {java.lang.String.class, java.net.InetAddress.class, int.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.net.URL.class, java.net.Authenticator.RequestorType.class}
- )
- public void test_requestPasswordAuthentication_String_InetAddress_int_String_String_String_URL_Authenticator_RequestorType()
- throws UnknownHostException, MalformedURLException {
- MockAuthenticator mock = new MockAuthenticator();
- URL url = new URL("http://127.0.0.1");
- Authenticator.requestPasswordAuthentication("localhost", InetAddress
- .getByName("127.0.0.1"), 80, "HTTP", "", "", url,
- RequestorType.PROXY);
- assertNull(mock.getRequestingURL());
- assertNull(mock.getRequestorType());
-
- SecurityManager sm = new SecurityManager() {
- final String permissionName = "requestPasswordAuthentication";
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals(permissionName)) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- Authenticator.requestPasswordAuthentication("localhost", InetAddress
- .getByName("127.0.0.1"), 80, "HTTP", "", "", url,
- RequestorType.PROXY);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- Authenticator.setDefault(null);
- }
- }
-
- /**
- *
- * @tests java.net.Authenticator#getRequestingURL()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRequestingURL",
- args = {}
- )
- public void test_getRequestingURL() throws Exception {
- MockAuthenticator mock = new MockAuthenticator();
- assertNull(mock.getRequestingURL());
- }
-
- /**
- *
- * @tests java.net.Authenticator#getRequestorType()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRequestorType",
- args = {}
- )
- public void test_getRequestorType() throws Exception {
- MockAuthenticator mock = new MockAuthenticator();
- assertNull(mock.getRequestorType());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setDefault",
- args = {java.net.Authenticator.class}
- )
- public void test_setDefault() {
- StubAuthenticator stub = new StubAuthenticator();
- InetAddress addr;
- try {
- addr = InetAddress.getLocalHost();
- PasswordAuthentication pa = Authenticator.
- requestPasswordAuthentication(addr, 8080, "http", "promt", "HTTP");
- assertNull(pa);
-
- } catch (UnknownHostException e) {
- fail("UnknownHostException was thrown.");
- }
-
- MockAuthenticator mock = new MockAuthenticator();
- Authenticator.setDefault(mock);
-
- try {
- addr = InetAddress.getLocalHost();
- PasswordAuthentication pa = Authenticator.
- requestPasswordAuthentication(addr, 80, "http", "promt", "HTTP");
- assertNull(pa);
-
- } catch (UnknownHostException e) {
- fail("UnknownHostException was thrown.");
- }
- Authenticator.setDefault(null);
-
- SecurityManager sm = new SecurityManager() {
- final String permissionName = "setDefaultAuthenticator";
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals(permissionName)) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- Authenticator.setDefault(stub);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- Authenticator.setDefault(null);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Authenticator",
- args = {}
- )
- public void test_Constructor() {
- MockAuthenticator ma = new MockAuthenticator();
- assertNull(ma.getRequestingURL());
- assertNull(ma.getRequestorType());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPasswordAuthentication",
- args = {}
- )
- public void test_getPasswordAuthentication() {
- MockAuthenticator ma = new MockAuthenticator();
- assertNull(ma.getPasswordAuthentication());
- }
-
- /*
- * Mock Authernticator for test
- */
- class MockAuthenticator extends java.net.Authenticator {
- public MockAuthenticator() {
- super();
- }
-
- public URL getRequestingURL() {
- return super.getRequestingURL();
- }
-
- public Authenticator.RequestorType getRequestorType() {
- return super.getRequestorType();
- }
-
- public PasswordAuthentication getPasswordAuthentication() {
- return super.getPasswordAuthentication();
- }
-
- public String getMockRequestingHost() {
- return super.getRequestingHost();
- }
-
- public int getMockRequestingPort() {
- return super.getRequestingPort();
- }
-
- public String getMockRequestingPrompt() {
- return super.getRequestingPrompt();
- }
-
- public String getMockRequestingProtocol() {
- return super.getRequestingProtocol();
- }
-
- public String getMockRequestingScheme() {
- return super.getRequestingScheme();
- }
-
- public InetAddress getMockRequestingSite() {
- return super.getRequestingSite();
- }
- }
-
- class StubAuthenticator extends java.net.Authenticator {
- public StubAuthenticator() {
- super();
- }
-
- public URL getRequestingURL() {
- return null;
- }
-
- public Authenticator.RequestorType getRequestorType() {
- return null;
- }
-
- public PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication("test",
- new char[] {'t', 'e', 's', 't'});
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/BindExceptionTest.java b/luni/src/test/java/tests/api/java/net/BindExceptionTest.java
deleted file mode 100644
index 711bb23..0000000
--- a/luni/src/test/java/tests/api/java/net/BindExceptionTest.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.BindException;
-
-@TestTargetClass(BindException.class)
-public class BindExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.BindException#BindException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "BindException",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.net.BindException()
- try {
- throw new BindException();
- } catch (BindException e) {
- return;
- } catch (Exception e) {
- fail("Exception during BindException test" + e.toString());
- }
- fail("Failed to generate exception");
- }
-
- /**
- * @tests java.net.BindException#BindException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "BindException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.net.BindException(java.lang.String)
- try {
- throw new BindException("Some error message");
- } catch (BindException e) {
- return;
- } catch (Exception e) {
- fail("Exception during BindException test : " + e.getMessage());
- }
- fail("Failed to generate exception");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/CacheRequestTest.java b/luni/src/test/java/tests/api/java/net/CacheRequestTest.java
deleted file mode 100644
index 9026e58..0000000
--- a/luni/src/test/java/tests/api/java/net/CacheRequestTest.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.net.CacheRequest;
-
-@TestTargetClass(CacheRequest.class)
-public class CacheRequestTest extends TestCase {
-
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "abort",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "CacheRequest",
- args = {}
- )
- })
- public void test_abort() {
- MockCacheRequest mcr = new MockCacheRequest();
- mcr.abort();
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBody",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "CacheRequest",
- args = {}
- )
- })
- public void test_getBody() throws IOException {
- MockCacheRequest mcr = new MockCacheRequest();
- assertNull(mcr.getBody());
- }
-
- class MockCacheRequest extends CacheRequest {
-
- MockCacheRequest() {
- super();
- }
-
- @Override
- public void abort() {
- }
-
- @Override
- public OutputStream getBody() throws IOException {
- return null;
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/CacheResponseTest.java b/luni/src/test/java/tests/api/java/net/CacheResponseTest.java
deleted file mode 100644
index 0163cee..0000000
--- a/luni/src/test/java/tests/api/java/net/CacheResponseTest.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.CacheRequest;
-import java.net.CacheResponse;
-import java.util.List;
-import java.util.Map;
-
-@TestTargetClass(CacheResponse.class)
-public class CacheResponseTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBody",
- args = {}
- )
- public void test_getBody() throws IOException {
- MockCacheResponse mcr = new MockCacheResponse();
- assertNull(mcr.getBody());
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getHeaders",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "CacheResponse",
- args = {}
- )
- })
- public void test_getHeaders() throws IOException {
- MockCacheResponse mcr = new MockCacheResponse();
- assertNull(mcr.getHeaders());
- }
-
- class MockCacheResponse extends CacheResponse {
-
- MockCacheResponse() {
- super();
- }
-
- @Override
- public Map<String,List<String>> getHeaders() throws IOException {
- return null;
- }
-
- @Override
- public InputStream getBody() throws IOException {
- return null;
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/ConnectExceptionTest.java b/luni/src/test/java/tests/api/java/net/ConnectExceptionTest.java
deleted file mode 100644
index 455eed1..0000000
--- a/luni/src/test/java/tests/api/java/net/ConnectExceptionTest.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.ConnectException;
-import java.net.InetAddress;
-import java.net.Socket;
-
-import tests.support.Support_PortManager;
-
-@TestTargetClass(ConnectException.class)
-public class ConnectExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.ConnectException#ConnectException()
- * @tests java.net.ConnectException#ConnectException(java.lang.String)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ConnectException",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ConnectException",
- args = {java.lang.String.class}
- )
- })
- public void test_Constructor() {
- assertNull("Wrong message", new ConnectException().getMessage());
- assertEquals("Wrong message", "message", new ConnectException("message").getMessage());
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/CookieHandlerTest.java b/luni/src/test/java/tests/api/java/net/CookieHandlerTest.java
deleted file mode 100644
index 3d43205..0000000
--- a/luni/src/test/java/tests/api/java/net/CookieHandlerTest.java
+++ /dev/null
@@ -1,236 +0,0 @@
-/* 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 tests.api.java.net;
-
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.CookieHandler;
-import java.net.MalformedURLException;
-import java.net.NetPermission;
-import java.net.URI;
-import java.net.URL;
-import java.net.URLConnection;
-import java.security.Permission;
-import java.util.Map;
-
-import junit.framework.TestCase;
-
-import tests.support.Support_Configuration;
-
-@TestTargetClass(CookieHandler.class)
-public class CookieHandlerTest extends TestCase {
-
- URI getURI, putURI;
- String link = "http://" + Support_Configuration.SpecialInetTestAddress + "/";
- boolean isGetCalled = false;
- boolean isPutCalled = false;
-
- /**
- * @tests java.net.CookieHandler#getDefault()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for getDefault method.",
- method = "getDefault",
- args = {}
- )
- public void test_GetDefault() {
- assertNull(CookieHandler.getDefault());
- }
-
- /**
- * @tests java.net.CookieHandler#setDefault(CookieHandler)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for setDefault method.",
- method = "setDefault",
- args = {java.net.CookieHandler.class}
- )
- public void test_SetDefault_java_net_cookieHandler() {
- MockCookieHandler rc1 = new MockCookieHandler();
- MockCookieHandler rc2 = new MockCookieHandler();
- CookieHandler.setDefault(rc1);
- assertSame(CookieHandler.getDefault(), rc1);
- CookieHandler.setDefault(rc2);
- assertSame(CookieHandler.getDefault(), rc2);
- CookieHandler.setDefault(null);
- assertNull(CookieHandler.getDefault());
- }
-
- /**
- * @tests java.net.CookieHandler#getDefault()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for getDefault method.",
- method = "getDefault",
- args = {}
- )
- public void testGetDefault_Security() {
- SecurityManager old = System.getSecurityManager();
- try {
- System.setSecurityManager(new MockSM());
- } catch (SecurityException e) {
- System.err.println("Unable to reset securityManager,test ignored");
- return;
- }
- try {
- CookieHandler.getDefault();
- fail("should throw SecurityException");
- } catch (SecurityException e) {
- // correct
- } finally {
- System.setSecurityManager(old);
- }
- }
-
- /**
- * @tests java.net.CookieHandler#setDefault(CookieHandler)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for setDefault method.",
- method = "setDefault",
- args = {java.net.CookieHandler.class}
- ) public void testSetDefault_Security() {
- CookieHandler rc = new MockCookieHandler();
- SecurityManager old = System.getSecurityManager();
- try {
- System.setSecurityManager(new MockSM());
- } catch (SecurityException e) {
- System.err.println("Unable to reset securityManager,test ignored");
- return;
- }
-
- try {
- CookieHandler.setDefault(rc);
- fail("should throw SecurityException");
- } catch (SecurityException e) {
- // correct
- } finally {
- System.setSecurityManager(old);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "CookieHandler",
- args = {}
- )
- public void test_CookieHandler() {
- MockCookieHandler mch = new MockCookieHandler();
- assertNull(mch.getDefault());
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {java.net.URI.class, java.util.Map.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "put",
- args = {java.net.URI.class, java.util.Map.class}
- )
- })
- @KnownFailure("Cache is not used")
- public void test_get_put() {
- MockCookieHandler mch = new MockCookieHandler();
- CookieHandler defaultHandler = CookieHandler.getDefault();
- CookieHandler.setDefault(mch);
-
- class TestThread extends Thread {
- public void run() {
- try {
- URL url = new URL(link);
- URLConnection conn = url.openConnection();
- Object obj = conn.getContent();
- url = new URL(link);
- conn = url.openConnection();
- obj = conn.getContent();
- } catch (MalformedURLException e) {
- fail("MalformedURLException was thrown: " + e.toString());
- } catch (IOException e) {
- fail("IOException was thrown.");
- }
- }
- };
- try {
- TestThread thread = new TestThread();
-
- thread.start();
- try {
- thread.join();
- } catch (InterruptedException e) {
- fail("InterruptedException was thrown.");
- }
-
- assertTrue(isGetCalled);
- assertTrue(isPutCalled);
- } finally {
- CookieHandler.setDefault(defaultHandler);
- }
- }
-
- class MockCookieHandler extends CookieHandler {
-
- public Map get(URI uri, Map requestHeaders) throws IOException {
- getURI = uri;
- isGetCalled = true;
- return requestHeaders;
- }
-
- public void put(URI uri, Map responseHeaders) throws IOException {
- putURI = uri;
- isPutCalled = true;
- }
-
- }
-
- class MockSM extends SecurityManager {
- public void checkPermission(Permission permission) {
- if (permission instanceof NetPermission) {
- if ("setCookieHandler".equals(permission.getName())) {
- throw new SecurityException();
- }
- }
-
- if (permission instanceof NetPermission) {
- if ("getCookieHandler".equals(permission.getName())) {
- throw new SecurityException();
- }
- }
-
- if (permission instanceof RuntimePermission) {
- if ("setSecurityManager".equals(permission.getName())) {
- return;
- }
- }
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/DatagramPacketTest.java b/luni/src/test/java/tests/api/java/net/DatagramPacketTest.java
deleted file mode 100644
index a8ed2b6..0000000
--- a/luni/src/test/java/tests/api/java/net/DatagramPacketTest.java
+++ /dev/null
@@ -1,612 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.IOException;
-import java.net.DatagramPacket;
-import java.net.DatagramSocket;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.net.UnknownHostException;
-
-import tests.support.Support_Configuration;
-import tests.support.Support_PortManager;
-
-@TestTargetClass(DatagramPacket.class)
-public class DatagramPacketTest extends junit.framework.TestCase {
-
- DatagramPacket dp;
-
- volatile boolean started = false;
-
- /**
- * @tests java.net.DatagramPacket#DatagramPacket(byte[], int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "DatagramPacket",
- args = {byte[].class, int.class}
- )
- public void test_Constructor$BI() {
- // Test for method java.net.DatagramPacket(byte [], int)
- try {
- dp = new DatagramPacket("Hello".getBytes(), 5);
- assertEquals("Created incorrect packet", "Hello", new String(dp.getData(), 0,
- dp.getData().length));
- assertEquals("Wrong length", 5, dp.getLength());
- } catch (Exception e) {
- fail("Exception during Constructor test: " + e.toString());
- }
- //regression for Harmony-890
- dp = new DatagramPacket(new byte[942],4);
- assertEquals(-1, dp.getPort());
- try{
- dp.getSocketAddress();
- fail("Should throw IllegalArgumentException");
- }catch(IllegalArgumentException e){
- //expected
- }
- }
-
- /**
- * @tests java.net.DatagramPacket#DatagramPacket(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "DatagramPacket",
- args = {byte[].class, int.class, int.class}
- )
- public void test_Constructor$BII() {
- try {
- dp = new DatagramPacket("Hello".getBytes(), 2, 3);
- assertEquals("Created incorrect packet", "Hello", new String(dp.getData(), 0,
- dp.getData().length));
- assertEquals("Wrong length", 3, dp.getLength());
- assertEquals("Wrong offset", 2, dp.getOffset());
- } catch (Exception e) {
- fail("Exception during Constructor test: " + e.toString());
- }
- }
-
- /**
- * @tests java.net.DatagramPacket#DatagramPacket(byte[], int, int,
- * java.net.InetAddress, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "DatagramPacket",
- args = {byte[].class, int.class, int.class, java.net.InetAddress.class, int.class}
- )
- public void test_Constructor$BIILjava_net_InetAddressI() {
- try {
- dp = new DatagramPacket("Hello".getBytes(), 2, 3, InetAddress
- .getLocalHost(), 0);
- assertTrue("Created incorrect packet", dp.getAddress().equals(
- InetAddress.getLocalHost())
- && dp.getPort() == 0);
- assertEquals("Wrong length", 3, dp.getLength());
- assertEquals("Wrong offset", 2, dp.getOffset());
- } catch (Exception e) {
- fail("Exception during Constructor test: " + e.toString());
- }
- }
-
- /**
- * @tests java.net.DatagramPacket#DatagramPacket(byte[], int,
- * java.net.InetAddress, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "DatagramPacket",
- args = {byte[].class, int.class, java.net.InetAddress.class, int.class}
- )
- public void test_Constructor$BILjava_net_InetAddressI() {
- // Test for method java.net.DatagramPacket(byte [], int,
- // java.net.InetAddress, int)
- try {
- dp = new DatagramPacket("Hello".getBytes(), 5, InetAddress
- .getLocalHost(), 0);
- assertTrue("Created incorrect packet", dp.getAddress().equals(
- InetAddress.getLocalHost())
- && dp.getPort() == 0);
- assertEquals("Wrong length", 5, dp.getLength());
- } catch (Exception e) {
- fail("Exception during Constructor test: " + e.toString());
- }
- }
-
- /**
- * @tests java.net.DatagramPacket#getAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAddress",
- args = {}
- )
- public void test_getAddress() {
- // Test for method java.net.InetAddress
- // java.net.DatagramPacket.getAddress()
- try {
- dp = new DatagramPacket("Hello".getBytes(), 5, InetAddress
- .getLocalHost(), 0);
- assertTrue("Incorrect address returned", dp.getAddress().equals(
- InetAddress.getLocalHost()));
- } catch (Exception e) {
- fail("Exception during getAddress test:" + e.toString());
- }
- }
-
- /**
- * @tests java.net.DatagramPacket#getData()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getData",
- args = {}
- )
- public void test_getData() {
- // Test for method byte [] java.net.DatagramPacket.getData()
-
- dp = new DatagramPacket("Hello".getBytes(), 5);
- assertEquals("Incorrect length returned", "Hello", new String(dp.getData(), 0, dp
- .getData().length));
- }
-
- /**
- * @tests java.net.DatagramPacket#getLength()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLength",
- args = {}
- )
- public void test_getLength() {
- // Test for method int java.net.DatagramPacket.getLength()
-
- dp = new DatagramPacket("Hello".getBytes(), 5);
- assertEquals("Incorrect length returned", 5, dp.getLength());
- }
-
- /**
- * @tests java.net.DatagramPacket#getOffset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getOffset",
- args = {}
- )
- public void test_getOffset() {
- dp = new DatagramPacket("Hello".getBytes(), 3, 2);
- assertEquals("Incorrect length returned", 3, dp.getOffset());
- }
-
- /**
- * @tests java.net.DatagramPacket#getPort()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPort",
- args = {}
- )
- public void test_getPort() {
- // Test for method int java.net.DatagramPacket.getPort()
- try {
- dp = new DatagramPacket("Hello".getBytes(), 5, InetAddress
- .getLocalHost(), 1000);
- assertEquals("Incorrect port returned", 1000, dp.getPort());
- } catch (Exception e) {
- fail("Exception during getPort test : " + e.getMessage());
- }
-
- InetAddress localhost = null;
- try {
- localhost = InetAddress.getByName("localhost");
- } catch (UnknownHostException e) {
- fail("Unexpected UnknownHostException : " + e.getMessage());
- }
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- final int port = ports[0];
- final Object lock = new Object();
-
- Thread thread = new Thread(new Runnable() {
- public void run() {
- DatagramSocket socket = null;
- try {
- socket = new DatagramSocket(port);
- synchronized (lock) {
- started = true;
- lock.notifyAll();
- }
- socket.setSoTimeout(3000);
- DatagramPacket packet = new DatagramPacket(new byte[256],
- 256);
- socket.receive(packet);
- socket.send(packet);
- socket.close();
- } catch (IOException e) {
- System.out.println("thread exception: " + e);
- if (socket != null)
- socket.close();
- }
- }
- });
- thread.start();
-
- DatagramSocket socket = null;
- try {
- socket = new DatagramSocket(ports[1]);
- socket.setSoTimeout(3000);
- DatagramPacket packet = new DatagramPacket(new byte[] { 1, 2, 3, 4,
- 5, 6 }, 6, localhost, port);
- synchronized (lock) {
- try {
- if (!started)
- lock.wait();
- } catch (InterruptedException e) {
- fail(e.toString());
- }
- }
- socket.send(packet);
- socket.receive(packet);
- socket.close();
- assertTrue("datagram received wrong port: " + packet.getPort(),
- packet.getPort() == port);
- } catch (IOException e) {
- if (socket != null)
- socket.close();
- System.err.println("port: " + port + " datagram server error: ");
- e.printStackTrace();
- fail("port : " + port + " datagram server error : "
- + e.getMessage());
- }
- }
-
- /**
- * @tests java.net.DatagramPacket#setAddress(java.net.InetAddress)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setAddress",
- args = {java.net.InetAddress.class}
- )
- public void test_setAddressLjava_net_InetAddress() {
- // Test for method void
- // java.net.DatagramPacket.setAddress(java.net.InetAddress)
- try {
- InetAddress ia = InetAddress
- .getByName(Support_Configuration.InetTestIP);
- dp = new DatagramPacket("Hello".getBytes(), 5, InetAddress
- .getLocalHost(), 0);
- dp.setAddress(ia);
- assertTrue("Incorrect address returned", dp.getAddress().equals(ia));
- } catch (Exception e) {
- fail("Exception during getAddress test:" + e.toString());
- }
- }
-
- /**
- * @tests java.net.DatagramPacket#setData(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setData",
- args = {byte[].class, int.class, int.class}
- )
- public void test_setData$BII() {
- dp = new DatagramPacket("Hello".getBytes(), 5);
- dp.setData("Wagga Wagga".getBytes(), 2, 3);
- assertEquals("Incorrect data set", "Wagga Wagga", new String(dp.getData())
- );
- try {
- dp.setData(null, 2, 3);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- /**
- * @tests java.net.DatagramPacket#setData(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setData",
- args = {byte[].class}
- )
- public void test_setData$B() {
- // Test for method void java.net.DatagramPacket.setData(byte [])
- dp = new DatagramPacket("Hello".getBytes(), 5);
- dp.setData("Ralph".getBytes());
- assertEquals("Incorrect data set", "Ralph", new String(dp.getData(), 0, dp
- .getData().length));
-
- try {
- dp.setData(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- /**
- * @tests java.net.DatagramPacket#setLength(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setLength",
- args = {int.class}
- )
- public void test_setLengthI() {
- // Test for method void java.net.DatagramPacket.setLength(int)
- dp = new DatagramPacket("Hello".getBytes(), 5);
- dp.setLength(1);
- assertEquals("Failed to set packet length", 1, dp.getLength());
-
- try {
- new DatagramPacket("Hello".getBytes(), 6);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- new DatagramPacket("Hello".getBytes(), -1);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @tests java.net.DatagramPacket#setPort(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setPort",
- args = {int.class}
- )
- public void test_setPortI() {
- // Test for method void java.net.DatagramPacket.setPort(int)
- try {
- dp = new DatagramPacket("Hello".getBytes(), 5, InetAddress
- .getLocalHost(), 1000);
- dp.setPort(2000);
- assertEquals("Port not set", 2000, dp.getPort());
- } catch (Exception e) {
- fail("Exception during setPort test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.net.DatagramPacket#DatagramPacket(byte[], int,
- * java.net.SocketAddress)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "SocketException checking missed.",
- method = "DatagramPacket",
- args = {byte[].class, int.class, java.net.SocketAddress.class}
- )
- public void test_Constructor$BILjava_net_SocketAddress() {
- class mySocketAddress extends SocketAddress {
-
- public mySocketAddress() {
- }
- }
-
- try {
- // unsupported SocketAddress subclass
- byte buf[] = new byte[1];
- try {
- DatagramPacket thePacket = new DatagramPacket(buf, 1,
- new mySocketAddress());
- fail("No exception when constructing using unsupported SocketAddress subclass");
- } catch (IllegalArgumentException ex) {
- }
-
- // case were we try to pass in null
- // unsupported SocketAddress subclass
-
- try {
- DatagramPacket thePacket = new DatagramPacket(buf, 1, null);
- fail("No exception when constructing address using null");
- } catch (IllegalArgumentException ex) {
- }
-
- // now validate we can construct
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPortForUDP());
- DatagramPacket thePacket = new DatagramPacket(buf, 1, theAddress);
- assertTrue("Socket address not set correctly (1)", theAddress
- .equals(thePacket.getSocketAddress()));
- assertTrue("Socket address not set correctly (2)", theAddress
- .equals(new InetSocketAddress(thePacket.getAddress(),
- thePacket.getPort())));
- } catch (Exception e) {
- fail("Exception during constructor test(1):" + e.toString());
- }
- }
-
- /**
- * @tests java.net.DatagramPacket#DatagramPacket(byte[], int, int,
- * java.net.SocketAddress)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "SocketException checking missed.",
- method = "DatagramPacket",
- args = {byte[].class, int.class, int.class, java.net.SocketAddress.class}
- )
- public void test_Constructor$BIILjava_net_SocketAddress() {
- class mySocketAddress extends SocketAddress {
-
- public mySocketAddress() {
- }
- }
-
- try {
- // unsupported SocketAddress subclass
- byte buf[] = new byte[2];
- try {
- DatagramPacket thePacket = new DatagramPacket(buf, 1, 1,
- new mySocketAddress());
- fail("No exception when constructing using unsupported SocketAddress subclass");
- } catch (IllegalArgumentException ex) {
- }
-
- // case were we try to pass in null
- // unsupported SocketAddress subclass
-
- try {
- DatagramPacket thePacket = new DatagramPacket(buf, 1, 1, null);
- fail("No exception when constructing address using null");
- } catch (IllegalArgumentException ex) {
- }
-
- // now validate we can construct
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPortForUDP());
- DatagramPacket thePacket = new DatagramPacket(buf, 1, 1, theAddress);
- assertTrue("Socket address not set correctly (1)", theAddress
- .equals(thePacket.getSocketAddress()));
- assertTrue("Socket address not set correctly (2)", theAddress
- .equals(new InetSocketAddress(thePacket.getAddress(),
- thePacket.getPort())));
- assertEquals("Offset not set correctly", 1, thePacket.getOffset());
- } catch (Exception e) {
- fail("Exception during constructor test(2):" + e.toString());
- }
- }
-
- /**
- * @tests java.net.DatagramPacket#getSocketAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSocketAddress",
- args = {}
- )
- public void test_getSocketAddress() {
- try {
- byte buf[] = new byte[1];
- DatagramPacket thePacket = new DatagramPacket(buf, 1);
-
- // validate get returns the value we set
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPortForUDP());
- thePacket = new DatagramPacket(buf, 1);
- thePacket.setSocketAddress(theAddress);
- assertTrue("Socket address not set correctly (1)", theAddress
- .equals(thePacket.getSocketAddress()));
- } catch (Exception e) {
- fail(
- "Exception during getSocketAddress test:" + e.toString());
- }
- }
-
- /**
- * @tests java.net.DatagramPacket#setSocketAddress(java.net.SocketAddress)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setSocketAddress",
- args = {java.net.SocketAddress.class}
- )
- public void test_setSocketAddressLjava_net_SocketAddress() {
-
- class mySocketAddress extends SocketAddress {
-
- public mySocketAddress() {
- }
- }
-
- try {
- // unsupported SocketAddress subclass
- byte buf[] = new byte[1];
- DatagramPacket thePacket = new DatagramPacket(buf, 1);
- try {
- thePacket.setSocketAddress(new mySocketAddress());
- fail("No exception when setting address using unsupported SocketAddress subclass");
- } catch (IllegalArgumentException ex) {
- }
-
- // case were we try to pass in null
- // unsupported SocketAddress subclass
- thePacket = new DatagramPacket(buf, 1);
- try {
- thePacket.setSocketAddress(null);
- fail("No exception when setting address using null");
- } catch (IllegalArgumentException ex) {
- }
-
- // now validate we can set it correctly
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPortForUDP());
- thePacket = new DatagramPacket(buf, 1);
- thePacket.setSocketAddress(theAddress);
- assertTrue("Socket address not set correctly (1)", theAddress
- .equals(thePacket.getSocketAddress()));
- assertTrue("Socket address not set correctly (2)", theAddress
- .equals(new InetSocketAddress(thePacket.getAddress(),
- thePacket.getPort())));
- } catch (Exception e) {
- fail(
- "Exception during setSocketAddress test:" + e.toString());
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-
- protected void doneSuite() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/DatagramSocketImplFactoryTest.java b/luni/src/test/java/tests/api/java/net/DatagramSocketImplFactoryTest.java
deleted file mode 100644
index d5ee587..0000000
--- a/luni/src/test/java/tests/api/java/net/DatagramSocketImplFactoryTest.java
+++ /dev/null
@@ -1,257 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.IOException;
-import java.lang.reflect.Field;
-import java.net.DatagramPacket;
-import java.net.DatagramSocket;
-import java.net.DatagramSocketImpl;
-import java.net.DatagramSocketImplFactory;
-import java.net.InetAddress;
-import java.net.NetworkInterface;
-import java.net.SocketAddress;
-import java.net.SocketException;
-
-@TestTargetClass(DatagramSocketImplFactory.class)
-public class DatagramSocketImplFactoryTest extends TestCase {
-
- DatagramSocketImplFactory oldFactory = null;
- Field factoryField = null;
-
- boolean isTestable = false;
-
- boolean isDatagramSocketImplCalled = false;
- boolean isCreateDatagramSocketImpl = false;
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "createDatagramSocketImpl",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies SecurityException.",
- clazz = DatagramSocket.class,
- method = "setDatagramSocketImplFactory",
- args = {java.net.DatagramSocketImplFactory.class}
- )
- })
- public void test_createDatagramSocketImpl() throws IllegalArgumentException,
- IOException {
-
- if(isTestable) {
-
- DatagramSocketImplFactory factory = new TestDatagramSocketImplFactory();
- assertFalse(isCreateDatagramSocketImpl);
- DatagramSocket.setDatagramSocketImplFactory(factory);
-
- try {
- DatagramSocket ds = new java.net.DatagramSocket();
- assertTrue(isCreateDatagramSocketImpl);
- assertTrue(isDatagramSocketImplCalled);
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
-
- }
-
- try {
- DatagramSocket.setDatagramSocketImplFactory(factory);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
-
- try {
- DatagramSocket.setDatagramSocketImplFactory(null);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
-
- } else {
-
- TestDatagramSocketImplFactory dsf = new TestDatagramSocketImplFactory();
- DatagramSocketImpl dsi = dsf.createDatagramSocketImpl();
- try {
- assertNull(dsi.getOption(0));
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- }
-
- }
- }
-
- public void setUp() {
- Field [] fields = DatagramSocket.class.getDeclaredFields();
- int counter = 0;
- for (Field field : fields) {
- if (DatagramSocketImplFactory.class.equals(field.getType())) {
- counter++;
- factoryField = field;
- }
- }
-
- if(counter == 1) {
-
- isTestable = true;
-
- factoryField.setAccessible(true);
- try {
- oldFactory = (DatagramSocketImplFactory) factoryField.get(null);
- } catch (IllegalArgumentException e) {
- fail("IllegalArgumentException was thrown during setUp: "
- + e.getMessage());
- } catch (IllegalAccessException e) {
- fail("IllegalAccessException was thrown during setUp: "
- + e.getMessage());
- }
- }
- }
-
- public void tearDown() {
- if(isTestable) {
- try {
- factoryField.set(null, oldFactory);
- } catch (IllegalArgumentException e) {
- fail("IllegalArgumentException was thrown during tearDown: "
- + e.getMessage());
- } catch (IllegalAccessException e) {
- fail("IllegalAccessException was thrown during tearDown: "
- + e.getMessage());
- }
- }
- }
-
- class TestDatagramSocketImplFactory implements DatagramSocketImplFactory {
- public DatagramSocketImpl createDatagramSocketImpl() {
- isCreateDatagramSocketImpl = true;
- return new TestDatagramSocketImpl();
- }
- }
-
- class TestDatagramSocketImpl extends DatagramSocketImpl {
-
- @Override
- protected void bind(int arg0, InetAddress arg1) throws SocketException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void close() {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void create() throws SocketException {
- isDatagramSocketImplCalled = true;
- }
-
- @Override
- protected byte getTTL() throws IOException {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- protected int getTimeToLive() throws IOException {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- protected void join(InetAddress arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void joinGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void leave(InetAddress arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void leaveGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public int peek(InetAddress arg0) throws IOException {
- // TODO Auto-generated method stub
- return 10;
- }
-
- @Override
- protected int peekData(DatagramPacket arg0) throws IOException {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- protected void receive(DatagramPacket arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void send(DatagramPacket arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void setTTL(byte arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void setTimeToLive(int arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- public Object getOption(int arg0) throws SocketException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public void setOption(int arg0, Object arg1) throws SocketException {
- // TODO Auto-generated method stub
-
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/DatagramSocketImplTest.java b/luni/src/test/java/tests/api/java/net/DatagramSocketImplTest.java
deleted file mode 100644
index 44df544..0000000
--- a/luni/src/test/java/tests/api/java/net/DatagramSocketImplTest.java
+++ /dev/null
@@ -1,347 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.FileDescriptor;
-import java.io.IOException;
-import java.net.DatagramPacket;
-import java.net.DatagramSocketImpl;
-import java.net.InetAddress;
-import java.net.NetworkInterface;
-import java.net.SocketAddress;
-import java.net.SocketException;
-
-/*
- * DatagramSocketImplFactory can be specified only once,
- * therefore we can't check DatagramSocketImpl functionality.
- */
-
-@TestTargetClass(value = DatagramSocketImpl.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "bind",
- args = {int.class, InetAddress.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "close",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "create",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getTimeToLive",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getTTL",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "join",
- args = {InetAddress.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "joinGroup",
- args = { SocketAddress.class, NetworkInterface.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "leave",
- args = { InetAddress.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "leaveGroup",
- args = { SocketAddress.class, NetworkInterface.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "peek",
- args = { InetAddress.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "peekData",
- args = { DatagramPacket.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "receive",
- args = { DatagramPacket.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "send",
- args = { DatagramPacket.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setTimeToLive",
- args = { int.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setTTL",
- args = { byte.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setOption",
- args = { int.class, Object.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getOption",
- args = { int.class }
- )
- })
-public class DatagramSocketImplTest extends junit.framework.TestCase {
-
- MockDatagramSocketImpl ds;
-
- public void setUp() {
- ds = new MockDatagramSocketImpl();
- }
-
- public void tearDown() {
- ds.close();
- ds = null;
- }
- /**
- * @tests java.net.DatagramSocketImpl#DatagramSocketImpl()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "DatagramSocketImpl",
- args = {}
- )
- public void test_Constructor() throws Exception {
- // regression test for Harmony-1117
- MockDatagramSocketImpl impl = new MockDatagramSocketImpl();
- assertNull(impl.getFileDescriptor());
- }
-
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "SocketException is not checked.",
- method = "connect",
- args = {java.net.InetAddress.class, int.class}
- )
- public void test_connect() {
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- //int port = ds.getLocalPort();
- ds.connect(localHost, 0);
- DatagramPacket send = new DatagramPacket(new byte[10], 10,
- localHost, 0);
- ds.send(send);
- } catch (IOException e) {
- fail("Unexpected IOException : " + e.getMessage());
- } finally {
- ds.close();
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "disconnect",
- args = {}
- )
- public void test_disconnect() {
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- //int port = ds.getLocalPort();
- ds.connect(localHost, 0);
- DatagramPacket send = new DatagramPacket(new byte[10], 10,
- localHost, 0);
- ds.send(send);
- ds.disconnect();
- } catch (IOException e) {
- fail("Unexpected IOException : " + e.getMessage());
- } finally {
- ds.close();
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFileDescriptor",
- args = {}
- )
- public void test_getFileDescriptor() {
- assertNull(ds.getFileDescriptor());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalPort",
- args = {}
- )
- public void test_getLocalPort() {
- // RI fails here. RI returns 0. the spec doesn't say what the value for
- // an unbound DatagramSocket should be. The same difference can be seen
- // for Socket.getLocalPort. But there the spec says that unbound
- // Sockets return -1. And for that method also the RI returns 0 which
- // goes against the spec.
- assertEquals(-1, ds.getLocalPort());
- }
-}
-
-class MockDatagramSocketImpl extends DatagramSocketImpl {
-
- @Override
- public FileDescriptor getFileDescriptor() {
- return super.getFileDescriptor();
- }
-
- @Override
- public void bind(int port, InetAddress addr) throws SocketException {
- // empty
- }
-
- @Override
- public void close() {
- // empty
- }
-
- @Override
- public void create() throws SocketException {
- // empty
- }
-
-
- @Override
- public byte getTTL() throws IOException {
- return 0;
- }
-
- @Override
- public int getTimeToLive() throws IOException {
- return 0;
- }
-
- @Override
- public void join(InetAddress addr) throws IOException {
- // empty
- }
-
- @Override
- public void joinGroup(SocketAddress addr, NetworkInterface netInterface)
- throws IOException {
- // empty
- }
-
- @Override
- public void leave(InetAddress addr) throws IOException {
- // empty
- }
-
- @Override
- public void leaveGroup(SocketAddress addr, NetworkInterface netInterface)
- throws IOException {
- // empty
- }
-
- @Override
- public int peek(InetAddress sender) throws IOException {
- return 0;
- }
-
- @Override
- public int peekData(DatagramPacket pack) throws IOException {
- return 0;
- }
-
- @Override
- public void receive(DatagramPacket pack) throws IOException {
- // empty
- }
-
- @Override
- public void send(DatagramPacket pack) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
-
- @Override
- public void setTTL(byte ttl) throws IOException {
- // empty
- }
-
- @Override
- public void setTimeToLive(int ttl) throws IOException {
- // empty
- }
-
- public Object getOption(int optID) throws SocketException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public void setOption(int optID, Object value) throws SocketException {
- // TODO Auto-generated method stub
-
- }
-
- public void connect(InetAddress address, int port) throws SocketException {
- super.connect(address, port);
- }
-
- public void disconnect() {
- super.disconnect();
- }
-
- public int getLocalPort() {
- return super.getLocalPort();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/DatagramSocketTest.java b/luni/src/test/java/tests/api/java/net/DatagramSocketTest.java
deleted file mode 100644
index 1930f53..0000000
--- a/luni/src/test/java/tests/api/java/net/DatagramSocketTest.java
+++ /dev/null
@@ -1,2851 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.IOException;
-import java.io.InterruptedIOException;
-import java.net.BindException;
-import java.net.DatagramPacket;
-import java.net.DatagramSocket;
-import java.net.DatagramSocketImpl;
-import java.net.DatagramSocketImplFactory;
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.NetworkInterface;
-import java.net.PortUnreachableException;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.net.SocketPermission;
-import java.net.SocketTimeoutException;
-import java.net.UnknownHostException;
-import java.nio.channels.DatagramChannel;
-import java.nio.channels.IllegalBlockingModeException;
-import java.security.Permission;
-import java.util.Date;
-import java.util.Vector;
-
-import tests.support.Support_Configuration;
-import tests.support.Support_PortManager;
-
-@TestTargetClass(DatagramSocket.class)
-public class DatagramSocketTest extends SocketTestCase {
-
- java.net.DatagramSocket ds;
-
- java.net.DatagramPacket dp;
-
- DatagramSocket sds = null;
-
- String retval;
-
- String testString = "Test String";
-
- boolean interrupted;
-
- class DatagramServer extends Thread {
-
- public DatagramSocket ms;
-
- boolean running = true;
-
- public volatile byte[] rbuf = new byte[512];
-
- volatile DatagramPacket rdp = null;
-
- public void run() {
- try {
- while (running) {
- try {
- ms.receive(rdp);
- // echo the packet back
- ms.send(rdp);
- } catch (java.io.InterruptedIOException e) {
- Thread.yield();
- }
- ;
- }
- ;
- } catch (java.io.IOException e) {
- System.out.println("DatagramServer server failed: " + e);
- } finally {
- ms.close();
- }
- }
-
- public void stopServer() {
- running = false;
- }
-
- public DatagramServer(int aPort, InetAddress address)
- throws java.io.IOException {
- rbuf = new byte[512];
- rbuf[0] = -1;
- rdp = new DatagramPacket(rbuf, rbuf.length);
- ms = new DatagramSocket(aPort, address);
- ms.setSoTimeout(2000);
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#DatagramSocket()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "SocketException checking missed.",
- method = "DatagramSocket",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.net.DatagramSocket()
- try {
- ds = new java.net.DatagramSocket();
- } catch (Exception e) {
- fail("Could not create DatagramSocket : " + e.getMessage());
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkListen(int port) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new DatagramSocket();
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#DatagramSocket(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "DatagramSocket",
- args = {int.class}
- )
- @KnownFailure("New DatagramSocket(1) doesn't throw an expected exception.")
- public void test_ConstructorI() {
- // Test for method java.net.DatagramSocket(int)
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- assertTrue("Created socket with incorrect port",
- ds.getLocalPort() == portNumber);
- } catch (Exception e) {
- fail("Could not create DatagramSocket : " + e.getMessage());
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkListen(int port) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new DatagramSocket(8080);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- try {
- DatagramSocket ds = new java.net.DatagramSocket(1);
- fail("SocketException was not thrown.");
- } catch (SocketException e) {
- //expected
- }
-
- }
-
- /**
- * @tests java.net.DatagramSocket#DatagramSocket(int, java.net.InetAddress)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "DatagramSocket",
- args = {int.class, java.net.InetAddress.class}
- )
- public void test_ConstructorILjava_net_InetAddress() {
- // Test for method java.net.DatagramSocket(int, java.net.InetAddress)
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber, InetAddress
- .getLocalHost());
- assertTrue("Created socket with incorrect port",
- ds.getLocalPort() == portNumber);
- assertTrue("Created socket with incorrect address", ds
- .getLocalAddress().equals(InetAddress.getLocalHost()));
- } catch (Exception e) {
- fail("Could not create DatagramSocket : " + e.getMessage());
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkListen(int port) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new java.net.DatagramSocket(8080, InetAddress
- .getLocalHost());
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } catch (UnknownHostException e) {
- fail("UnknownHostException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- try {
- new java.net.DatagramSocket(1, InetAddress
- .getLocalHost());
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- } catch (UnknownHostException e) {
- fail("UnknownHostException was thrown.");
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "close",
- args = {}
- )
- public void test_close() {
- // Test for method void java.net.DatagramSocket.close()
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- dp = new DatagramPacket("Test String".getBytes(), 11, InetAddress
- .getLocalHost(), 0);
- ds.close();
- try {
- ds.send(dp);
- fail("IOException was not thrown.");
- } catch(IOException ioe) {
- //expected
- }
- } catch (Exception e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#connect(java.net.InetAddress, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "connect",
- args = {java.net.InetAddress.class, int.class}
- )
- @KnownFailure("An unexpected Exception was thrown in the last part of the test")
- public void test_connectLjava_net_InetAddressI() {
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- assertTrue("Incorrect InetAddress", ds.getInetAddress().equals(
- inetAddress));
- assertTrue("Incorrect Port", ds.getPort() == portNumber);
- ds.disconnect();
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
-
- if ("true".equals(System.getProperty("run.ipv6tests"))) {
- System.out
- .println("Running test_connectLjava_net_InetAddressI" +
- "(DatagramSocketTest) with IPv6GlobalAddressJcl4: "
- + Support_Configuration.IPv6GlobalAddressJcl4);
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress
- .getByName(Support_Configuration.IPv6GlobalAddressJcl4);
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- assertTrue("Incorrect InetAddress", ds.getInetAddress().equals(
- inetAddress));
- assertTrue("Incorrect Port", ds.getPort() == portNumber);
- ds.disconnect();
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- try {
- // Create a connected datagram socket to test
- // PlainDatagramSocketImpl.peek()
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket();
- int port = ds.getLocalPort();
- ds.connect(localHost, port);
- DatagramPacket send = new DatagramPacket(new byte[10], 10,
- localHost, port);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("Wrong size: " + receive.getLength(), receive
- .getLength() == 10);
- assertTrue("Wrong receiver", receive.getAddress().equals(localHost));
- } catch (IOException e) {
- fail("Unexpected IOException : " + e.getMessage());
- }
-
- class DatagramServer extends Thread {
-
- public DatagramSocket ms;
-
- boolean running = true;
-
- public byte[] rbuf = new byte[512];
-
- DatagramPacket rdp = null;
-
- public void run() {
- try {
- while (running) {
- try {
- ms.receive(rdp);
- // echo the packet back
- ms.send(rdp);
- } catch (java.io.InterruptedIOException e) {
- Thread.yield();
- }
-
- }
-
- } catch (java.io.IOException e) {
- System.out.println("Multicast server failed: " + e);
- } finally {
- ms.close();
- }
- }
-
- public void stopServer() {
- running = false;
- }
-
- public DatagramServer(int aPort, InetAddress address)
- throws java.io.IOException {
- rbuf = new byte[512];
- rbuf[0] = -1;
- rdp = new DatagramPacket(rbuf, rbuf.length);
- ms = new DatagramSocket(aPort, address);
- ms.setSoTimeout(2000);
- }
- }
-
- // validate that we get the PortUnreachable exception if we try to
- // send a dgram to a server that is not running and then do a recv
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- DatagramPacket send = new DatagramPacket(new byte[10], 10);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(10000);
- ds.receive(receive);
- ds.close();
- fail(
- "No PortUnreachableException when connected at native level on recv ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when trying to connect at native level on recv: "
- + e.toString(),
- (e instanceof PortUnreachableException));
- }
-
- // validate that we can send/receive with datagram sockets connected at
- // the native level
- DatagramServer server = null;
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(localHost, serverPortNumber);
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("Wrong size data received: " + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("Wrong receiver:" + receive.getAddress() + ":"
- + localHost, receive.getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level:"
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can disconnect
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- ds.disconnect();
- ds.close();
- } catch (Exception e) {
- assertTrue("Unexpected exception when trying to connect at native"
- + e.toString(), (e instanceof PortUnreachableException));
- }
-
- // validate that once connected we cannot send to another address
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- DatagramPacket send = new DatagramPacket(new byte[10], 10,
- inetAddress, portNumber + 1);
- ds.send(send);
- ds.close();
- fail(
- "No Exception when trying to send to a different address on a connected socket ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when trying to send to a different address on a connected socket: "
- + e.toString(),
- (e instanceof IllegalArgumentException));
- }
-
- // validate that we can connect, then disconnect, then connect then
- // send/recv
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(localHost, serverPortNumber + 1);
- ds.disconnect();
- ds.connect(localHost, serverPortNumber);
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue(
- "connect/disconnect/connect - Wrong size data received: "
- + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("connect/disconnect/connect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("connect/disconnect/connect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive
- .getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level after connect/disconnect/connect:"
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can connect/disconnect then send/recv to any address
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(localHost, serverPortNumber + 1);
- ds.disconnect();
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length, localHost, serverPortNumber);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("connect/disconnect - Wrong size data received: "
- + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("connect/disconnect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("connect/disconnect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive
- .getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level after connect/disconnect:"
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can connect on an allready connected socket and then
- // send/recv
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(localHost, serverPortNumber + 1);
- ds.connect(localHost, serverPortNumber);
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("connect/connect - Wrong size data received: "
- + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("connect/connect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("connect/connect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive
- .getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level after connect/connect: "
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // test for when we fail to connect at the native level. Even though we
- // fail at the native level there is no way to return an exception so
- // there should be no exception
- try {
- ds = new java.net.DatagramSocket();
- byte[] addressBytes = { 0, 0, 0, 0 };
- InetAddress inetAddress = InetAddress.getByAddress(addressBytes);
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- } catch (Exception e) {
- fail(
- "Unexcpected exception when trying to connect at native level with bad address for signature with no exception to be returned: "
- + e.toString());
- }
-
- if ("true".equals(System.getProperty("run.ipv6tests"))) {
- System.out
- .println("Running test_connectLjava_net_InetAddressI(DatagramSocketTest) with IPv6 address");
- try {
- ds = new java.net.DatagramSocket();
- byte[] addressBytes = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0 };
- InetAddress inetAddress = InetAddress
- .getByAddress(addressBytes);
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- } catch (Exception e) {
- fail(
- "Unexcpected exception when trying to connect at native level with bad IPv6 address for signature with no exception to be returned: "
- + e.toString());
- }
- }
-
- try {
- byte[] addressBytes = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0 };
- ds = new java.net.DatagramSocket();
- int portNumber = Support_PortManager.getNextPortForUDP();
-
- final InetAddress inetAddress = InetAddress
- .getByAddress(addressBytes);
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- if(perm.getActions().equals("connect,resolve") ) {
- throw new SecurityException();
- }
- }
-
- public void checkListen(int port) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- ds.connect(inetAddress, portNumber);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- } catch(Exception e) {
- fail("Unexpected exception was thrown:" + e.getClass() + ", "
- + e.getMessage());
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#disconnect()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "disconnect",
- args = {}
- )
- public void test_disconnect() {
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- ds.disconnect();
- assertNull("Incorrect InetAddress", ds.getInetAddress());
- assertEquals("Incorrect Port", -1, ds.getPort());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
-
- if ("true".equals(System.getProperty("run.ipv6tests"))) {
- System.out
- .println("Running test_disconnect(DatagramSocketTest) with IPv6GlobalAddressJcl4: "
- + Support_Configuration.IPv6GlobalAddressJcl4);
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress
- .getByName(Support_Configuration.IPv6GlobalAddressJcl4);
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- ds.disconnect();
- assertNull("Incorrect InetAddress", ds.getInetAddress());
- assertEquals("Incorrect Port", -1, ds.getPort());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- }
-
- /**
- * @tests java.net.DatagramSocket#getInetAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInetAddress",
- args = {}
- )
- public void test_getInetAddress() {
- Vector<InetAddress> ias = new Vector<InetAddress>();
- try {
- ias.add(InetAddress.getLocalHost());
- ias.add(InetAddress
- .getByName(Support_Configuration.IPv6GlobalAddressJcl4));
- ias.add(InetAddress
- .getByName(Support_Configuration.InetTestAddress2));
- ias.add(InetAddress
- .getByName(Support_Configuration.InetTestAddress2));
- ias.add(InetAddress
- .getByName(Support_Configuration.InetTestIP));
- } catch(Exception e) {
- fail("Unexpected exception was thrown: " + e.toString());
- }
-
- for(InetAddress ia:ias) {
- int portNumber = Support_PortManager.getNextPortForUDP();
- DatagramSocket ds = null;
- try {
- ds = new DatagramSocket();
- ds.connect(ia, portNumber);
- assertEquals(ia, ds.getInetAddress());
- assertEquals("" + ia, ia, ds.getInetAddress());
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- ds.disconnect();
- ds.close();
- }
- }
-
- try {
- assertNull(new DatagramSocket().getInetAddress());
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- }
-
- }
-
- /**
- * @tests java.net.DatagramSocket#getLocalAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalAddress",
- args = {}
- )
- public void test_getLocalAddress() {
- // Test for method java.net.InetAddress
- // java.net.DatagramSocket.getLocalAddress()
- InetAddress local = null;
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- local = InetAddress.getLocalHost();
- ds = new java.net.DatagramSocket(portNumber, local);
- assertTrue("Returned incorrect address. Got:"
- + ds.getLocalAddress()
- + " wanted: "
- + InetAddress.getByName(InetAddress.getLocalHost()
- .getHostName()), InetAddress.getByName(
- InetAddress.getLocalHost().getHostName()).equals(
- ds.getLocalAddress()));
-
- // now validate thet behaviour when the any address is returned
- String preferIPv4StackValue = System
- .getProperty("java.net.preferIPv4Stack");
- String preferIPv6AddressesValue = System
- .getProperty("java.net.preferIPv6Addresses");
- DatagramSocket s = new DatagramSocket(0);
- if (((preferIPv4StackValue == null) || preferIPv4StackValue
- .equalsIgnoreCase("false"))
- && (preferIPv6AddressesValue != null)
- && (preferIPv6AddressesValue.equals("true"))) {
- assertTrue(
- "ANY address not returned correctly (getLocalAddress) with preferIPv6Addresses=true, preferIPv4Stack=false "
- + s.getLocalSocketAddress(), s
- .getLocalAddress() instanceof Inet6Address);
- } else {
- assertTrue(
- "ANY address not returned correctly (getLocalAddress) with preferIPv6Addresses=true, preferIPv4Stack=true "
- + s.getLocalSocketAddress(), s
- .getLocalAddress() instanceof Inet4Address);
- }
- s.close();
- } catch (Exception e) {
- fail(
- "Exception during getLocalAddress: " + local + " - " + e);
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#getLocalPort()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalPort",
- args = {}
- )
- public void test_getLocalPort() {
- // Test for method int java.net.DatagramSocket.getLocalPort()
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- assertTrue("Returned incorrect port",
- ds.getLocalPort() == portNumber);
- } catch (Exception e) {
- fail("Exception during getLocalAddress : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#getPort()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPort",
- args = {}
- )
- public void test_getPort() {
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- DatagramSocket theSocket = new DatagramSocket(portNumber);
- assertEquals("Expected -1 for remote port as not connected",
- -1, theSocket.getPort());
-
- // now connect the socket and validate that we get the right port
- theSocket.connect(InetAddress.getLocalHost(), portNumber);
- assertTrue("getPort returned wrong value:" + theSocket.getPort()
- + ":Expected:" + portNumber,
- theSocket.getPort() == portNumber);
- } catch (Exception e) {
- fail("unexpected exception during getPort test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#getReceiveBufferSize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getReceiveBufferSize",
- args = {}
- )
- public void test_getReceiveBufferSize() {
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setReceiveBufferSize(130);
- assertTrue("Incorrect buffer size",
- ds.getReceiveBufferSize() >= 130);
- ds.close();
- try {
- ds.getReceiveBufferSize();
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
- } catch (Exception e) {
- handleException(e, SO_RCVBUF);
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#getSendBufferSize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSendBufferSize",
- args = {}
- )
- public void test_getSendBufferSize() {
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setSendBufferSize(134);
- assertTrue("Incorrect buffer size", ds.getSendBufferSize() >= 134);
- ds.close();
- try {
- ds.getSendBufferSize();
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_SNDBUF);
- } catch (Exception e) {
- handleException(e, SO_SNDBUF);
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#getSoTimeout()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSoTimeout",
- args = {}
- )
- public void test_getSoTimeout() {
- // Test for method int java.net.DatagramSocket.getSoTimeout()
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setSoTimeout(100);
- assertEquals("Returned incorrect timeout", 100, ds.getSoTimeout());
- ds.close();
- try {
- ds.getSoTimeout();
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_TIMEOUT);
- } catch (Exception e) {
- handleException(e, SO_TIMEOUT);
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#receive(java.net.DatagramPacket)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "PortUnreachableException,IOException checking missed.",
- method = "receive",
- args = {java.net.DatagramPacket.class}
- )
- public void test_receiveLjava_net_DatagramPacket() {
- // Test for method void
- // java.net.DatagramSocket.receive(java.net.DatagramPacket)
-
- receive_oversize_java_net_DatagramPacket();
- final int[] ports = Support_PortManager.getNextPortsForUDP(2);
- final int portNumber = ports[0];
-
- class TestDGRcv implements Runnable {
- public void run() {
- InetAddress localHost = null;
- try {
- localHost = InetAddress.getLocalHost();
- Thread.sleep(1000);
- DatagramSocket sds = new DatagramSocket(ports[1]);
- DatagramPacket rdp = new DatagramPacket("Test String"
- .getBytes(), 11, localHost, portNumber);
- sds.send(rdp);
- sds.close();
- } catch (Exception e) {
- System.err.println("host " + localHost + " port "
- + portNumber + " failed to send data: " + e);
- e.printStackTrace();
- }
- }
- }
-
- try {
- new Thread(new TestDGRcv(), "DGSender").start();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setSoTimeout(6000);
- byte rbuf[] = new byte[1000];
- DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
- ds.receive(rdp);
- ds.close();
- assertTrue("Send/Receive failed to return correct data: "
- + new String(rbuf, 0, 11), new String(rbuf, 0, 11)
- .equals("Test String"));
- } catch (Exception e) {
- System.err.println("Exception during send test: " + e);
- e.printStackTrace();
- fail("port " + portNumber + " Exception during send test: "
- + e);
- } finally {
- ds.close();
- }
- DatagramSocket socket = null;
- try {
- byte rbuf[] = new byte[1000];
- DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
- SocketAddress address = new InetSocketAddress(portNumber);
- DatagramChannel channel = DatagramChannel.open();
- channel.configureBlocking(false);
- socket = channel.socket();
- socket.receive(rdp);
- fail("IllegalBlockingModeException was not thrown.");
- } catch(IllegalBlockingModeException ibme) {
- //expected
- } catch(IOException ioe) {
- fail("IOException was thrown: " + ioe.getMessage());
- } finally {
- socket.close();
- }
-
- try {
- ds = new java.net.DatagramSocket(portNumber);
- ds.setSoTimeout(1000);
- byte rbuf[] = new byte[1000];
- DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
- ds.receive(rdp);
- fail("SocketTimeoutException was not thrown.");
- } catch(SocketTimeoutException te) {
- //expected
- } catch (Exception e) {
- System.err.println("Exception during send test: " + e);
- e.printStackTrace();
- fail("port " + portNumber + " Exception during send test: "
- + e);
- } finally {
- ds.close();
- }
-
-
-
- try {
- interrupted = false;
- final DatagramSocket ds = new DatagramSocket();
- ds.setSoTimeout(12000);
- Runnable runnable = new Runnable() {
- public void run() {
- try {
- ds.receive(new DatagramPacket(new byte[1], 1));
- } catch (InterruptedIOException e) {
- interrupted = true;
- } catch (IOException e) {
- }
- }
- };
- Thread thread = new Thread(runnable, "DatagramSocket.receive1");
- thread.start();
- try {
- do {
- Thread.sleep(500);
- } while (!thread.isAlive());
- } catch (InterruptedException e) {
- }
- ds.close();
- int c = 0;
- do {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- }
- if (interrupted) {
- fail("received interrupt");
- }
- if (++c > 4) {
- fail("read call did not exit");
- }
- } while (thread.isAlive());
-
- interrupted = false;
- int[] ports1 = Support_PortManager.getNextPortsForUDP(2);
- final int portNum = ports[0];
- final DatagramSocket ds2 = new DatagramSocket(ports[1]);
- ds2.setSoTimeout(12000);
- Runnable runnable2 = new Runnable() {
- public void run() {
- try {
- ds2.receive(new DatagramPacket(new byte[1], 1,
- InetAddress.getLocalHost(), portNum));
- } catch (InterruptedIOException e) {
- interrupted = true;
- } catch (IOException e) {
- }
- }
- };
- Thread thread2 = new Thread(runnable2, "DatagramSocket.receive2");
- thread2.start();
- try {
- do {
- Thread.sleep(500);
- } while (!thread2.isAlive());
- } catch (InterruptedException e) {
- }
- ds2.close();
- int c2 = 0;
- do {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- }
- if (interrupted) {
- fail("receive2 was interrupted");
- }
- if (++c2 > 4) {
- fail("read2 call did not exit");
- }
- } while (thread2.isAlive());
-
- interrupted = false;
- DatagramSocket ds3 = new DatagramSocket();
- ds3.setSoTimeout(500);
- Date start = new Date();
- try {
- ds3.receive(new DatagramPacket(new byte[1], 1));
- } catch (InterruptedIOException e) {
- interrupted = true;
- }
- ds3.close();
- assertTrue("receive not interrupted", interrupted);
- int delay = (int) (new Date().getTime() - start.getTime());
- assertTrue("timeout too soon: " + delay, delay >= 490);
- } catch (IOException e) {
- fail("Unexpected IOException : " + e.getMessage());
- }
-
-
- }
-
- /**
- * @tests java.net.DatagramSocket#send(java.net.DatagramPacket)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "PortUnreachableException,IOExceptions checking missed.",
- method = "send",
- args = {java.net.DatagramPacket.class}
- )
- public void test_sendLjava_net_DatagramPacket() throws Exception {
- // Test for method void
- // java.net.DatagramSocket.send(java.net.DatagramPacket)
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- final int portNumber = ports[0];
-
- class TestDGSend implements Runnable {
- Thread pThread;
-
- public TestDGSend(Thread t) {
- pThread = t;
- }
-
- public void run() {
- try {
- byte[] rbuf = new byte[1000];
-
- sds = new DatagramSocket(portNumber);
- DatagramPacket sdp = new DatagramPacket(rbuf, rbuf.length);
- sds.setSoTimeout(6000);
- sds.receive(sdp);
- retval = new String(rbuf, 0, testString.length());
- pThread.interrupt();
- } catch (java.io.InterruptedIOException e) {
- System.out.println("Recv operation timed out");
- pThread.interrupt();
- ds.close();
- return;
- } catch (Exception e) {
- System.out
- .println("Failed to establish Dgram server: " + e);
- }
- }
- }
- try {
- new Thread(new TestDGSend(Thread.currentThread()), "DGServer")
- .start();
- ds = new java.net.DatagramSocket(ports[1]);
- dp = new DatagramPacket(testString.getBytes(), testString.length(),
- InetAddress.getLocalHost(), portNumber);
- // Wait to allow send to occur
- try {
- Thread.sleep(500);
- ds.send(dp);
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- ds.close();
- assertTrue("Incorrect data sent: " + retval, retval
- .equals(testString));
- }
- } catch (Exception e) {
- fail("Exception during send test : " + e.getMessage());
- } finally {
- ds.close();
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkMulticast(InetAddress maddr) {
- throw new SecurityException();
- }
-
- public void checkConnect(String host,
- int port) {
- throw new SecurityException();
- }
- };
- try {
-
- ds = new java.net.DatagramSocket(ports[1]);
- dp = new DatagramPacket(testString.getBytes(), testString.length(),
- InetAddress.getLocalHost(), portNumber);
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- ds.send(dp);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- } catch(Exception e) {
- fail("Unexpected exception was thrown: " + e.getMessage());
- }
-
- DatagramSocket socket = null;
- try {
- byte rbuf[] = new byte[1000];
- DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
- SocketAddress address = new InetSocketAddress(portNumber);
- DatagramChannel channel = DatagramChannel.open();
- channel.configureBlocking(false);
- socket = channel.socket();
- socket.send(rdp);
- fail("IllegalBlockingModeException was not thrown.");
- } catch(IllegalBlockingModeException ibme) {
- //expected
- } catch(IOException ioe) {
- fail("IOException was thrown: " + ioe.getMessage());
- } finally {
- socket.close();
- }
-
- //Regression for HARMONY-1118
- class testDatagramSocket extends DatagramSocket {
- public testDatagramSocket(DatagramSocketImpl impl){
- super(impl);
- }
- }
- class testDatagramSocketImpl extends DatagramSocketImpl {
- protected void create() throws SocketException {}
- protected void bind(int arg0, InetAddress arg1) throws SocketException {}
- protected void send(DatagramPacket arg0) throws IOException {}
- protected int peek(InetAddress arg0) throws IOException {
- return 0;
- }
- protected int peekData(DatagramPacket arg0) throws IOException {
- return 0;
- }
- protected void receive(DatagramPacket arg0) throws IOException {}
- protected void setTTL(byte arg0) throws IOException {}
- protected byte getTTL() throws IOException {
- return 0;
- }
- protected void setTimeToLive(int arg0) throws IOException {}
- protected int getTimeToLive() throws IOException {
- return 0;
- }
- protected void join(InetAddress arg0) throws IOException {}
- protected void leave(InetAddress arg0) throws IOException {}
- protected void joinGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {}
- protected void leaveGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {}
- protected void close() {}
- public void setOption(int arg0, Object arg1) throws SocketException {}
- public Object getOption(int arg0) throws SocketException {
- return null;
- }
- }
- InetSocketAddress sa = InetSocketAddress.createUnresolved("localhost", 0);
- //no exception expected for next line
- new testDatagramSocket(new testDatagramSocketImpl()).send(new DatagramPacket(new byte[272], 3, sa));
-
- // Regression test for Harmony-2938
- InetAddress i = InetAddress.getByName("127.0.0.1");
- DatagramSocket d = new DatagramSocket(0, i);
- try {
- d.send(new DatagramPacket(new byte[] { 1 }, 1));
- fail("should throw NPE.");
- } catch (NullPointerException e) {
- // expected;
- } finally {
- d.close();
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#setSendBufferSize(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setSendBufferSize",
- args = {int.class}
- )
- public void test_setSendBufferSizeI() {
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setSendBufferSize(134);
- assertTrue("Incorrect buffer size", ds.getSendBufferSize() >= 134);
- ds.close();
- try {
- ds.setSendBufferSize(1);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
-
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_SNDBUF);
- } catch (Exception e) {
- handleException(e, SO_SNDBUF);
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#setReceiveBufferSize(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setReceiveBufferSize",
- args = {int.class}
- )
- public void test_setReceiveBufferSizeI() {
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setReceiveBufferSize(130);
- assertTrue("Incorrect buffer size",
- ds.getReceiveBufferSize() >= 130);
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
- } catch (Exception e) {
- handleException(e, SO_RCVBUF);
- }
-
- try {
- ds.setReceiveBufferSize(0);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- }
-
- try {
- ds.setReceiveBufferSize(-1);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- }
-
- ds.close();
-
- try {
- ds.setReceiveBufferSize(1);
- fail("SocketException was not thrown.");
- } catch(IllegalArgumentException iae) {
- fail("IllegalArgumentException was thrown.");
- } catch (SocketException e) {
- //expected
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#setSoTimeout(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setSoTimeout",
- args = {int.class}
- )
- public void test_setSoTimeoutI() {
- // Test for method void java.net.DatagramSocket.setSoTimeout(int)
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setSoTimeout(5000);
- assertTrue("Set incorrect timeout", ds.getSoTimeout() >= 5000);
- ds.close();
- try {
- ds.setSoTimeout(100);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_TIMEOUT);
- } catch (Exception e) {
- handleException(e, SO_TIMEOUT);
- }
- }
- /**
- * @tests java.net.DatagramSocket#DatagramSocket(java.net.DatagramSocketImpl)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "DatagramSocket",
- args = {java.net.DatagramSocketImpl.class}
- )
- public void test_ConstructorLjava_net_DatagramSocketImpl() {
- class testDatagramSocket extends DatagramSocket {
- public testDatagramSocket(DatagramSocketImpl impl){
- super(impl);
- }
- }
-
- try {
- new testDatagramSocket((DatagramSocketImpl) null);
- fail("exception expected");
- } catch (NullPointerException ex) {
- //expected
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#DatagramSocket(java.net.SocketAddress)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "DatagramSocket",
- args = {java.net.SocketAddress.class}
- )
- public void test_ConstructorLjava_net_SocketAddress() {
- class mySocketAddress extends SocketAddress {
-
- public mySocketAddress() {
- }
- }
-
- try {
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(new InetSocketAddress(
- InetAddress.getLocalHost(), portNumber));
- assertTrue(ds.getBroadcast());
- assertTrue("Created socket with incorrect port", ds
- .getLocalPort() == portNumber);
- assertTrue("Created socket with incorrect address", ds
- .getLocalAddress().equals(InetAddress.getLocalHost()));
- } catch (Exception e) {
- fail("Could not create DatagramSocket : " + e.getMessage());
- }
-
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(new mySocketAddress());
- fail(
- "No exception when constucting datagramSocket with unsupported SocketAddress type");
- } catch (IllegalArgumentException e) {
-
- }
- //regression for Harmony-894
- ds = new DatagramSocket((SocketAddress)null);
- assertTrue(ds.getBroadcast());
- } catch (Exception ex) {
- fail(
- "unexpected exception when datagramSocket SocketAddress constructor test");
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkListen(int port) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new DatagramSocket(new InetSocketAddress(
- InetAddress.getLocalHost(), 1));
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } catch (UnknownHostException e) {
- fail("UnknownHostException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- InetSocketAddress isa = null;
- try {
- isa = new InetSocketAddress(
- InetAddress.getLocalHost(), 1);
- } catch (UnknownHostException e) {
- fail("UnknownHostException was thrown.");
- }
-
- try {
- new java.net.DatagramSocket(isa);
- fail("SocketException was thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#bind(java.net.SocketAddress)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "bind",
- args = {java.net.SocketAddress.class}
- )
- public void test_bindLjava_net_SocketAddress() {
- class mySocketAddress extends SocketAddress {
-
- public mySocketAddress() {
- }
- }
-
- DatagramServer server = null;
- try {
- // now create a socket that is not bound and then bind it
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int portNumber = ports[0];
- int serverPortNumber = ports[1];
- DatagramSocket theSocket = new DatagramSocket(
- new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber));
-
- // validate that the localSocketAddress reflects the address we
- // bound to
- assertTrue("Local address not correct after bind:"
- + theSocket.getLocalSocketAddress().toString()
- + "Expected: "
- + (new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)).toString(), theSocket
- .getLocalSocketAddress().equals(
- new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)));
-
- // now make sure that datagrams sent from this socket appear to come
- // from the address we bound to
- InetAddress localHost = InetAddress.getLocalHost();
- portNumber = ports[2];
- DatagramSocket ds = new DatagramSocket(null);
- ds.bind(new InetSocketAddress(localHost, portNumber));
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for bin datagram socket test ");
- }
-
- ds.connect(new InetSocketAddress(localHost, serverPortNumber));
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length);
- ds.send(send);
- Thread.sleep(1000);
- ds.close();
- assertTrue(
- "Address in packet sent does not match address bound to:"
- + server.rdp.getAddress() + ":"
- + server.rdp.getPort() + ":" + localHost + ":"
- + portNumber, (server.rdp.getAddress()
- .equals(localHost))
- && (server.rdp.getPort() == portNumber));
-
- // validate if we pass in null that it picks an address for us and
- // all is ok
- theSocket = new DatagramSocket(null);
- theSocket.bind(null);
- assertNotNull("Bind with null did not work", theSocket
- .getLocalSocketAddress());
- theSocket.close();
-
- // now check the error conditions
-
- // Address we cannot bind to
- theSocket = new DatagramSocket(null);
- try {
- theSocket
- .bind(new InetSocketAddress(
- InetAddress
- .getByAddress(Support_Configuration.nonLocalAddressBytes),
- Support_PortManager.getNextPortForUDP()));
- fail("No exception when binding to bad address");
- } catch (SocketException ex) {
- }
- theSocket.close();
-
- // Address that we have allready bound to
- ports = Support_PortManager.getNextPortsForUDP(2);
- theSocket = new DatagramSocket(null);
- DatagramSocket theSocket2 = new DatagramSocket(ports[0]);
- try {
- InetSocketAddress theAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), ports[1]);
- theSocket.bind(theAddress);
- theSocket2.bind(theAddress);
- fail("No exception binding to address that is not available");
- } catch (SocketException ex) {
- //expected
- }
- theSocket.close();
- theSocket2.close();
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkListen(int port) {
- throw new SecurityException();
- }
- };
-
- ports = Support_PortManager.getNextPortsForUDP(2);
- ds = new DatagramSocket(null);
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
-
- ds.bind(new InetSocketAddress(localHost, ports[0]));
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- // unsupported SocketAddress subclass
- theSocket = new DatagramSocket(null);
- try {
- theSocket.bind(new mySocketAddress());
- fail("No exception when binding using unsupported SocketAddress subclass");
- } catch (IllegalArgumentException ex) {
- }
- theSocket.close();
-
- } catch (Exception e) {
- fail("Unexpected exception during bind test : " + e.getMessage());
- }
-
- if (server != null) {
- server.stopServer();
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#connect(java.net.SocketAddress)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "connect",
- args = {java.net.SocketAddress.class}
- )
- public void test_connectLjava_net_SocketAddress() {
-
- // validate that we get the PortUnreachable exception if we try to
- // send a dgram to a server that is not running and then do a recv
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(new InetSocketAddress(inetAddress, portNumber));
- DatagramPacket send = new DatagramPacket(new byte[10], 10);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(10000);
- ds.receive(receive);
- ds.close();
- fail(
- "No PortUnreachableException when connected at native level on recv ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when trying to connect at native level on recv: "
- + e.toString(),
- (e instanceof PortUnreachableException));
- }
-
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
-
- ds.connect(new InetSocketAddress("asdfasdf", 1));
- ds.close();
- fail("SocketException was not thrown.");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when trying to connect to unknown host: "
- + e.toString(),
- (e instanceof SocketException));
- }
-
- // validate that we can send/receive with datagram sockets connected at
- // the native level
- DatagramServer server = null;
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber));
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("Wrong size data received: " + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("Wrong receiver:" + receive.getAddress() + ":"
- + localHost, receive.getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level:"
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can disconnect
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(new InetSocketAddress(inetAddress, portNumber));
- ds.disconnect();
- ds.close();
- } catch (Exception e) {
- assertTrue("Unexpected exception when trying to connect at native"
- + e.toString(), (e instanceof PortUnreachableException));
- }
-
- // validate that once connected we cannot send to another address
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(new InetSocketAddress(inetAddress, portNumber));
- DatagramPacket send = new DatagramPacket(new byte[10], 10,
- inetAddress, portNumber + 1);
- ds.send(send);
- ds.close();
- fail(
- "No Exception when trying to send to a different address on a connected socket ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when trying to send to a different address on a connected socket: "
- + e.toString(),
- (e instanceof IllegalArgumentException));
- }
-
- // validate that we can connect, then disconnect, then connect then
- // send/recv
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber + 1));
- ds.disconnect();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber));
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue(
- "connect/disconnect/connect - Wrong size data received: "
- + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("connect/disconnect/connect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("connect/disconnect/connect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive
- .getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level after connect/disconnect/connect:"
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can connect/disconnect then send/recv to any address
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber + 1));
- ds.disconnect();
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length, localHost, serverPortNumber);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("connect/disconnect - Wrong size data received: "
- + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("connect/disconnect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("connect/disconnect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive
- .getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level after connect/disconnect:"
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can connect on an allready connected socket and then
- // send/recv
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber + 1));
- ds.connect(new InetSocketAddress(localHost, serverPortNumber));
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("connect/connect - Wrong size data received: "
- + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("connect/connect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("connect/connect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive
- .getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level after connect/connect: "
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // test for when we fail to connect at the native level. It seems to
- // fail for the any address so we use this. Now to be compatible we
- // don't throw the exception but eat it and then act as if we were
- // connected at the Java level.
- try {
- ds = new java.net.DatagramSocket();
- byte[] addressBytes = { 0, 0, 0, 0 };
- InetAddress inetAddress = InetAddress.getByAddress(addressBytes);
- int portNumber = Support_PortManager.getNextPortForUDP();
- InetAddress localHost = InetAddress.getLocalHost();
- ds.connect(new InetSocketAddress(inetAddress, portNumber));
- assertTrue("Is not connected after connect to inaddr any", ds
- .isConnected());
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length, localHost, portNumber);
- ds.send(send);
- fail(
- "No exception when trying to connect at native level with bad address (exception from send) ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when trying to connect at native level with bad address (exception from send): "
- + e.toString(),
- (e instanceof IllegalArgumentException));
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#isBound()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isBound",
- args = {}
- )
- public void test_isBound() {
- try {
- InetAddress addr = InetAddress.getLocalHost();
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int port = ports[0];
-
- DatagramSocket theSocket = new DatagramSocket(ports[1]);
- assertTrue("Socket indicated not bound when it should be (1)",
- theSocket.isBound());
- theSocket.close();
-
- theSocket = new DatagramSocket(new InetSocketAddress(addr, port));
- assertTrue("Socket indicated not bound when it should be (2)",
- theSocket.isBound());
- theSocket.close();
-
- theSocket = new DatagramSocket(null);
- assertFalse("Socket indicated bound when it should not be (1)",
- theSocket.isBound());
- theSocket.close();
-
- // connect causes implicit bind
- theSocket = new DatagramSocket(null);
- theSocket.connect(new InetSocketAddress(addr, port));
- assertTrue("Socket indicated not bound when it should be (3)",
- theSocket.isBound());
- theSocket.close();
-
- // now test when we bind explicitely
- InetSocketAddress theLocalAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), ports[2]);
- theSocket = new DatagramSocket(null);
- assertFalse("Socket indicated bound when it should not be (2)",
- theSocket.isBound());
- theSocket.bind(theLocalAddress);
- assertTrue("Socket indicated not bound when it should be (4)",
- theSocket.isBound());
- theSocket.close();
- assertTrue("Socket indicated not bound when it should be (5)",
- theSocket.isBound());
- } catch (Exception e) {
- fail("Got exception during isBound tests" + e.toString());
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#isConnected()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isConnected",
- args = {}
- )
- public void test_isConnected() {
- try {
- InetAddress addr = InetAddress.getLocalHost();
- int[] ports = Support_PortManager.getNextPortsForUDP(4);
- int port = ports[0];
-
- // base test
- DatagramSocket theSocket = new DatagramSocket(ports[1]);
- assertFalse("Socket indicated connected when it should not be",
- theSocket.isConnected());
- theSocket.connect(new InetSocketAddress(addr, port));
- assertTrue("Socket indicated not connected when it should be",
- theSocket.isConnected());
-
- // reconnect the socket and make sure we get the right answer
- theSocket.connect(new InetSocketAddress(addr, ports[2]));
- assertTrue("Socket indicated not connected when it should be",
- theSocket.isConnected());
-
- // now disconnect the socket and make sure we get the right answer
- theSocket.disconnect();
- assertFalse("Socket indicated connected when it should not be",
- theSocket.isConnected());
- theSocket.close();
-
- // now check behavior when socket is closed when connected
- theSocket = new DatagramSocket(ports[3]);
- theSocket.connect(new InetSocketAddress(addr, port));
- theSocket.close();
- assertTrue("Socket indicated not connected when it should be",
- theSocket.isConnected());
- } catch (Exception e) {
- fail("Got exception during isConnected tests" + e.toString());
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#getRemoteSocketAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRemoteSocketAddress",
- args = {}
- )
- public void test_getRemoteSocketAddress() {
- try {
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int sport = ports[0];
- int portNumber = ports[1];
- DatagramSocket s = new DatagramSocket(new InetSocketAddress(
- InetAddress.getLocalHost(), portNumber));
- s.connect(new InetSocketAddress(InetAddress.getLocalHost(), sport));
- assertTrue("Returned incorrect InetSocketAddress(1):"
- + s.getLocalSocketAddress().toString(), s
- .getRemoteSocketAddress().equals(
- new InetSocketAddress(InetAddress.getLocalHost(),
- sport)));
- s.close();
-
- // now create one that is not connected and validate that we get the
- // right answer
- DatagramSocket theSocket = new DatagramSocket(null);
- portNumber = ports[2];
- theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber));
- assertNull(
- "Returned incorrect InetSocketAddress -unconnected socket:"
- + "Expected: NULL", theSocket
- .getRemoteSocketAddress());
-
- // now connect and validate we get the right answer
- theSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(),
- sport));
- assertTrue("Returned incorrect InetSocketAddress(2):"
- + theSocket.getRemoteSocketAddress().toString(), theSocket
- .getRemoteSocketAddress().equals(
- new InetSocketAddress(InetAddress.getLocalHost(),
- sport)));
- theSocket.close();
-
- } catch (Exception e) {
- fail("Exception during getRemoteSocketAddress test: " + e);
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#getLocalSocketAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalSocketAddress",
- args = {}
- )
- public void test_getLocalSocketAddress() {
-
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- DatagramSocket s = new DatagramSocket(new InetSocketAddress(
- InetAddress.getLocalHost(), portNumber));
- assertTrue("Returned incorrect InetSocketAddress(1):"
- + s.getLocalSocketAddress().toString()
- + "Expected: "
- + (new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)).toString(), s.getLocalSocketAddress()
- .equals(
- new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)));
- s.close();
-
- InetSocketAddress remoteAddress = (InetSocketAddress) s
- .getRemoteSocketAddress();
-
- // now create a socket that is not bound and validate we get the
- // right answer
- DatagramSocket theSocket = new DatagramSocket(null);
- assertNull(
- "Returned incorrect InetSocketAddress -unbound socket- Expected null",
- theSocket.getLocalSocketAddress());
-
- // now bind the socket and make sure we get the right answer
- portNumber = Support_PortManager.getNextPortForUDP();
- theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber));
- assertTrue("Returned incorrect InetSocketAddress(2):"
- + theSocket.getLocalSocketAddress().toString()
- + "Expected: "
- + (new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)).toString(), theSocket
- .getLocalSocketAddress().equals(
- new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)));
- theSocket.close();
-
- // now validate thet behaviour when the any address is returned
- s = new DatagramSocket(0);
-
- String preferIPv4StackValue = System
- .getProperty("java.net.preferIPv4Stack");
- String preferIPv6AddressesValue = System
- .getProperty("java.net.preferIPv6Addresses");
- if (((preferIPv4StackValue == null) || preferIPv4StackValue
- .equalsIgnoreCase("false"))
- && (preferIPv6AddressesValue != null)
- && (preferIPv6AddressesValue.equals("true"))) {
- assertTrue(
- "ANY address not returned correctly with preferIPv6Addresses=true, preferIPv4Stack=false "
- + s.getLocalSocketAddress(),
- ((InetSocketAddress) s.getLocalSocketAddress())
- .getAddress() instanceof Inet6Address);
- } else {
- assertTrue(
- "ANY address not returned correctly with preferIPv6Addresses=true, preferIPv4Stack=true "
- + s.getLocalSocketAddress(),
- ((InetSocketAddress) s.getLocalSocketAddress())
- .getAddress() instanceof Inet4Address);
- }
- s.close();
- } catch (Exception e) {
- e.printStackTrace();
- fail("Exception during getLocalSocketAddress test: " + e);
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#setReuseAddress(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setReuseAddress",
- args = {boolean.class}
- )
- public void test_setReuseAddressZ() {
- try {
- // test case were we set it to false
- DatagramSocket theSocket1 = null;
- DatagramSocket theSocket2 = null;
- try {
- InetSocketAddress theAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), Support_PortManager
- .getNextPortForUDP());
- theSocket1 = new DatagramSocket(null);
- theSocket2 = new DatagramSocket(null);
- theSocket1.setReuseAddress(false);
- theSocket2.setReuseAddress(false);
- theSocket1.bind(theAddress);
- theSocket2.bind(theAddress);
- fail(
- "No exception when trying to connect to do duplicate socket bind with re-useaddr set to false");
- } catch (BindException e) {
-
- }
- if (theSocket1 != null)
- theSocket1.close();
- if (theSocket2 != null)
- theSocket2.close();
-
- // test case were we set it to true
- try {
- InetSocketAddress theAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), Support_PortManager
- .getNextPortForUDP());
- theSocket1 = new DatagramSocket(null);
- theSocket2 = new DatagramSocket(null);
- theSocket1.setReuseAddress(true);
- theSocket2.setReuseAddress(true);
- theSocket1.bind(theAddress);
- theSocket2.bind(theAddress);
- } catch (Exception e) {
- fail(
- "unexpected exception when trying to connect to do duplicate socket bind with re-useaddr set to true");
- }
- if (theSocket1 != null)
- theSocket1.close();
- if (theSocket2 != null)
- theSocket2.close();
-
- // test the default case which we expect to be the same on all
- // platforms
- try {
- InetSocketAddress theAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), Support_PortManager
- .getNextPortForUDP());
- theSocket1 = new DatagramSocket(null);
- theSocket2 = new DatagramSocket(null);
- theSocket1.bind(theAddress);
- theSocket2.bind(theAddress);
- fail(
- "No exception when trying to connect to do duplicate socket bind with re-useaddr left as default");
- } catch (BindException e) {
-
- }
- if (theSocket1 != null)
- theSocket1.close();
- if (theSocket2 != null)
- theSocket2.close();
-
- try {
- theSocket1.setReuseAddress(true);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
- } catch (Exception e) {
- handleException(e, SO_REUSEADDR);
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#getReuseAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getReuseAddress",
- args = {}
- )
- public void test_getReuseAddress() {
- try {
- DatagramSocket theSocket = new DatagramSocket();
- theSocket.setReuseAddress(true);
- assertTrue("getReuseAddress false when it should be true",
- theSocket.getReuseAddress());
- theSocket.setReuseAddress(false);
- assertFalse("getReuseAddress true when it should be false",
- theSocket.getReuseAddress());
- theSocket.close();
- try {
- theSocket.getReuseAddress();
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
- } catch (Exception e) {
- handleException(e, SO_REUSEADDR);
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#setBroadcast(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setBroadcast",
- args = {boolean.class}
- )
- public void test_setBroadcastZ() {
-
- try {
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- DatagramSocket theSocket = new DatagramSocket(ports[0]);
- theSocket.setBroadcast(false);
- byte theBytes[] = { -1, -1, -1, -1 };
-
- // validate we cannot connect to the broadcast address when
- // setBroadcast is false
- try {
- theSocket.connect(new InetSocketAddress(InetAddress
- .getByAddress(theBytes), ports[1]));
- assertFalse(
- "No exception when connecting to broadcast address with setBroadcast(false)",
- theSocket.getBroadcast());
- } catch (SocketException ex) {
- //expected
- }
-
- // now validate that we can connect to the broadcast address when
- // setBroadcast is true
- theSocket.setBroadcast(true);
- theSocket
- .connect(new InetSocketAddress(InetAddress
- .getByAddress(theBytes), ports[2]));
-
- theSocket.close();
- try {
- theSocket.setBroadcast(false);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_BROADCAST);
- } catch (Exception e) {
- handleException(e, SO_BROADCAST);
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#getBroadcast()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBroadcast",
- args = {}
- )
- public void test_getBroadcast() {
- try {
- DatagramSocket theSocket = new DatagramSocket();
- theSocket.setBroadcast(true);
- assertTrue("getBroadcast false when it should be true", theSocket
- .getBroadcast());
- theSocket.setBroadcast(false);
- assertFalse("getBroadcast true when it should be False", theSocket
- .getBroadcast());
- theSocket.close();
- try {
- theSocket.getBroadcast();
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_BROADCAST);
- } catch (Exception e) {
- handleException(e, SO_BROADCAST);
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#setTrafficClass(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setTrafficClass",
- args = {int.class}
- )
- public void test_setTrafficClassI() {
- try {
- int IPTOS_LOWCOST = 0x2;
- int IPTOS_RELIABILTY = 0x4;
- int IPTOS_THROUGHPUT = 0x8;
- int IPTOS_LOWDELAY = 0x10;
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
-
- new InetSocketAddress(InetAddress.getLocalHost(),
- ports[0]);
- DatagramSocket theSocket = new DatagramSocket(ports[1]);
-
- // validate that value set must be between 0 and 255
- try {
- theSocket.setTrafficClass(256);
- fail("No exception when traffic class set to 256");
- } catch (IllegalArgumentException e) {
- }
-
- try {
- theSocket.setTrafficClass(-1);
- fail("No exception when traffic class set to -1");
- } catch (IllegalArgumentException e) {
- }
-
- // now validate that we can set it to some good values
- theSocket.setTrafficClass(IPTOS_LOWCOST);
- theSocket.setTrafficClass(IPTOS_THROUGHPUT);
-
- theSocket.close();
- try {
- theSocket.setTrafficClass(1);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
-
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(IP_TOS);
- } catch (Exception e) {
- handleException(e, IP_TOS);
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#getTrafficClass()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTrafficClass",
- args = {}
- )
- public void test_getTrafficClass() {
- try {
- int IPTOS_LOWCOST = 0x2;
- int IPTOS_RELIABILTY = 0x4;
- int IPTOS_THROUGHPUT = 0x8;
- int IPTOS_LOWDELAY = 0x10;
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
-
- new InetSocketAddress(InetAddress.getLocalHost(),
- ports[0]);
- DatagramSocket theSocket = new DatagramSocket(ports[1]);
-
- /*
- * we cannot actually check that the values are set as if a platform
- * does not support the option then it may come back unset even
- * though we set it so just get the value to make sure we can get it
- */
- int trafficClass = theSocket.getTrafficClass();
-
- theSocket.close();
- try {
- theSocket.getTrafficClass();
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- } catch (Exception e) {
- handleException(e, IP_TOS);
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#isClosed()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isClosed",
- args = {}
- )
- public void test_isClosed() {
- try {
- DatagramSocket theSocket = new DatagramSocket();
-
- // validate isClosed returns expected values
- assertFalse("Socket should indicate it is not closed(1):",
- theSocket.isClosed());
- theSocket.close();
- assertTrue("Socket should indicate it is not closed(1):", theSocket
- .isClosed());
-
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPortForUDP());
- theSocket = new DatagramSocket(theAddress);
- assertFalse("Socket should indicate it is not closed(2):",
- theSocket.isClosed());
- theSocket.close();
- assertTrue("Socket should indicate it is not closed(2):", theSocket
- .isClosed());
- } catch (Exception e) {
- fail("Got exception during isClosed tests" + e.toString());
- }
- }
-
- /**
- * @tests java.net.DatagramSocket#getChannel()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getChannel",
- args = {}
- )
- public void test_getChannel() throws Exception {
- assertNull(new DatagramSocket().getChannel());
-
- int portNumber = Support_PortManager.getNextPortForUDP();
- DatagramSocket ds = null;
- try {
- InetAddress ia = InetAddress
- .getByName(Support_Configuration.IPv6GlobalAddressJcl4);
- ds = new DatagramSocket();
- assertNull(ds.getChannel());
- ds.connect(ia, portNumber);
- assertNull(ds.getChannel());
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- ds.disconnect();
- ds.close();
- }
- portNumber = Support_PortManager.getNextPortForUDP();
- SocketAddress address = new InetSocketAddress(portNumber);
- DatagramChannel channel = DatagramChannel.open();
- DatagramSocket socket = channel.socket();
- assertEquals(channel, socket.getChannel());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies SecurityException.",
- method = "setDatagramSocketImplFactory",
- args = {java.net.DatagramSocketImplFactory.class}
- )
- public void test_setDatagramSocketImplFactory() {
- TestDatagramSocketImplFactory dsf = new TestDatagramSocketImplFactory();
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkSetFactory() {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- DatagramSocket.setDatagramSocketImplFactory(dsf);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } catch (IOException e) {
- fail("IOException was thrown.");
- e.printStackTrace();
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- class TestDatagramSocketImplFactory implements DatagramSocketImplFactory {
- public DatagramSocketImpl createDatagramSocketImpl() {
- return new TestDatagramSocketImpl();
- }
- }
-
- class TestDatagramSocketImpl extends DatagramSocketImpl {
-
- @Override
- protected void bind(int arg0, InetAddress arg1) throws SocketException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void close() {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void create() throws SocketException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected byte getTTL() throws IOException {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- protected int getTimeToLive() throws IOException {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- protected void join(InetAddress arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void joinGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void leave(InetAddress arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void leaveGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected int peek(InetAddress arg0) throws IOException {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- protected int peekData(DatagramPacket arg0) throws IOException {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- protected void receive(DatagramPacket arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void send(DatagramPacket arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void setTTL(byte arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void setTimeToLive(int arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- public Object getOption(int arg0) throws SocketException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public void setOption(int arg0, Object arg1) throws SocketException {
- // TODO Auto-generated method stub
-
- }
-
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- retval = "Bogus retval";
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- try {
- ds.close();
- sds.close();
- } catch (Exception e) {
- }
- }
-
- protected void receive_oversize_java_net_DatagramPacket() {
- final int[] ports = Support_PortManager.getNextPortsForUDP(2);
- final int portNumber = ports[0];
-
- class TestDGRcvOver implements Runnable {
- public void run() {
- InetAddress localHost = null;
- try {
- localHost = InetAddress.getLocalHost();
- Thread.sleep(1000);
- DatagramSocket sds = new DatagramSocket(ports[1]);
- DatagramPacket rdp = new DatagramPacket("0123456789"
- .getBytes(), 10, localHost, portNumber);
- sds.send(rdp);
- sds.close();
- } catch (Exception e) {
- System.err.println("host " + localHost + " port "
- + portNumber + " failed to send oversize data: "
- + e);
- e.printStackTrace();
- }
- }
- }
-
- try {
- new Thread(new TestDGRcvOver(), "DGSenderOver").start();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setSoTimeout(6000);
- byte rbuf[] = new byte[5];
- DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
- ;
- ds.receive(rdp);
- ds.close();
- assertTrue("Send/Receive oversize failed to return correct data: "
- + new String(rbuf, 0, 5), new String(rbuf, 0, 5)
- .equals("01234"));
- } catch (Exception e) {
- System.err.println("Exception during send test: " + e);
- e.printStackTrace();
- fail("port " + portNumber + " Exception: " + e
- + " during oversize send test");
- } finally {
- ds.close();
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/ExcludedProxyTest.java b/luni/src/test/java/tests/api/java/net/ExcludedProxyTest.java
deleted file mode 100644
index ae76723..0000000
--- a/luni/src/test/java/tests/api/java/net/ExcludedProxyTest.java
+++ /dev/null
@@ -1,238 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.BrokenTest;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.Socket;
-import java.net.InetSocketAddress;
-import java.net.Proxy;
-import java.net.SocketAddress;
-import java.net.URL;
-import java.net.URLConnection;
-
-import tests.support.Support_Configuration;
-import tests.support.resource.Support_Resources;
-import junit.framework.TestCase;
-
-/*
- * This test is designed for collecting all the testcases which needs a proxy
- * server. They will be moved to corresponding test class when ProxyHandler of
- * Jetty is ready in the future.
- *
- */
-
-@TestTargetClass(Proxy.class)
-public class ExcludedProxyTest extends TestCase {
- /**
- * @tests java.net.HttpURLConnection#usingProxy()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Tests Proxy functionality. Indirect test.",
- method = "Proxy",
- args = {java.net.Proxy.Type.class, java.net.SocketAddress.class}
- )
- @BrokenTest("the host address isn't working anymore")
- public void test_usingProxy() throws Exception {
- try {
- System.setProperty("http.proxyHost",
- Support_Configuration.ProxyServerTestHost);
-
- URL u1 = new URL("http://" + Support_Configuration.HomeAddress);
- URLConnection conn1 = u1.openConnection();
- conn1.getInputStream();
-
- boolean exception = false;
- try {
- System.setProperty("http.proxyPort", "81");
- URL u3 = new URL("http://"
- + Support_Configuration.InetTestAddress);
- URLConnection conn3 = u3.openConnection();
- conn3.getInputStream();
- fail("Should throw IOException");
- } catch (IOException e) {
- // expected
- }
-
- System.setProperty("http.proxyPort", "80");
-
- URL u2 = new URL("http://"
- + Support_Configuration.ProxyServerTestHost
- + "/cgi-bin/test.pl");
- java.net.HttpURLConnection conn2 = (java.net.HttpURLConnection) u2
- .openConnection();
- conn2.setDoOutput(true);
- conn2.setRequestMethod("POST");
- OutputStream out2 = conn2.getOutputStream();
- String posted2 = "this is a test";
- out2.write(posted2.getBytes());
- out2.close();
- conn2.getResponseCode();
- InputStream is2 = conn2.getInputStream();
- String response2 = "";
- byte[] b2 = new byte[1024];
- int count2 = 0;
- while ((count2 = is2.read(b2)) > 0)
- response2 += new String(b2, 0, count2);
- assertTrue("Response to POST method invalid", response2
- .equals(posted2));
-
- String posted4 = "just a test";
- URL u4 = new URL("http://"
- + Support_Configuration.ProxyServerTestHost
- + "/cgi-bin/test.pl");
- java.net.HttpURLConnection conn4 = (java.net.HttpURLConnection) u4
- .openConnection();
- conn4.setDoOutput(true);
- conn4.setRequestMethod("POST");
- conn4.setRequestProperty("Content-length", String.valueOf(posted4
- .length()));
- OutputStream out = conn4.getOutputStream();
- out.write(posted4.getBytes());
- out.close();
- conn4.getResponseCode();
- InputStream is = conn4.getInputStream();
- String response = "";
- byte[] b4 = new byte[1024];
- int count = 0;
- while ((count = is.read(b4)) > 0)
- response += new String(b4, 0, count);
- assertTrue("Response to POST method invalid", response
- .equals(posted4));
- } finally {
- System.setProperties(null);
- }
- }
-
- /**
- * @tests java.net.SocketImpl#SocketImpl()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Tests Proxy functionality. Indirect test.",
- method = "Proxy",
- args = {java.net.Proxy.Type.class, java.net.SocketAddress.class}
- )
- @BrokenTest("the host address isn't working anymore")
- public void test_Constructor() {
- try {
- try {
- System.setProperty("socksProxyHost",
- Support_Configuration.SocksServerTestHost);
- System.setProperty("socksProxyPort", String
- .valueOf(Support_Configuration.SocksServerTestPort));
- Socket s = new Socket(Support_Configuration.HomeAddress, 80);
- OutputStream os = s.getOutputStream();
- os.write("GET / HTTP/1.0\r\n\r\n".getBytes());
- s.getInputStream();
- } catch (IOException e) {
- fail("Could not open socket: "
- + Support_Configuration.HomeAddress + " " + e);
- }
- boolean exception = false;
- try {
- System.setProperty("socksProxyHost",
- Support_Configuration.SocksServerTestHost);
- System
- .setProperty(
- "socksProxyPort",
- String
- .valueOf(Support_Configuration.SocksServerTestPort + 1));
- Socket s = new Socket(Support_Configuration.HomeAddress, 80);
- OutputStream os = s.getOutputStream();
- os.write("GET / HTTP/1.0\r\n\r\n".getBytes());
- s.getInputStream();
- } catch (IOException e) {
- exception = true;
- }
- assertTrue("Exception should have been thrown", exception);
- } finally {
- System.setProperties(null);
- }
- }
-
- /**
- * @tests java.net.URL#openConnection(Proxy)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Tests Proxy functionality. Indirect test.",
- method = "Proxy",
- args = {java.net.Proxy.Type.class, java.net.SocketAddress.class}
- )
- @BrokenTest("the host address isn't working anymore")
- public void test_openConnectionLjava_net_Proxy() throws IOException {
- SocketAddress addr1 = new InetSocketAddress(
- Support_Configuration.ProxyServerTestHost, 808);
- SocketAddress addr2 = new InetSocketAddress(
- Support_Configuration.ProxyServerTestHost, 1080);
- Proxy proxy1 = new Proxy(Proxy.Type.HTTP, addr1);
- Proxy proxy2 = new Proxy(Proxy.Type.SOCKS, addr2);
- Proxy proxyList[] = { proxy1, proxy2 };
- for (int i = 0; i < proxyList.length; ++i) {
- String posted = "just a test";
- URL u = new URL("http://"
- + Support_Configuration.ProxyServerTestHost
- + "/cgi-bin/test.pl");
- java.net.HttpURLConnection conn = (java.net.HttpURLConnection) u
- .openConnection(proxyList[i]);
- conn.setDoOutput(true);
- conn.setRequestMethod("POST");
- conn.setRequestProperty("Content-length", String.valueOf(posted
- .length()));
- OutputStream out = conn.getOutputStream();
- out.write(posted.getBytes());
- out.close();
- conn.getResponseCode();
- InputStream is = conn.getInputStream();
- String response = "";
- byte[] b = new byte[1024];
- int count = 0;
- while ((count = is.read(b)) > 0) {
- response += new String(b, 0, count);
- }
- assertTrue("Response to POST method invalid", response
- .equals(posted));
- }
-
- URL httpUrl = new URL("http://abc.com");
- URL jarUrl = new URL("jar:"
- + Support_Resources.getResourceURL("/JUC/lf.jar!/plus.bmp"));
- URL ftpUrl = new URL("ftp://" + Support_Configuration.FTPTestAddress
- + "/nettest.txt");
- URL fileUrl = new URL("file://abc");
- URL[] urlList = { httpUrl, jarUrl, ftpUrl, fileUrl };
- for (int i = 0; i < urlList.length; ++i) {
- try {
- urlList[i].openConnection(null);
- } catch (IllegalArgumentException iae) {
- // expected
- }
- }
- // should not throw exception
- fileUrl.openConnection(Proxy.NO_PROXY);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/FileNameMapTest.java b/luni/src/test/java/tests/api/java/net/FileNameMapTest.java
deleted file mode 100644
index 4972dae..0000000
--- a/luni/src/test/java/tests/api/java/net/FileNameMapTest.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.net.FileNameMap;
-import java.net.URLConnection;
-
-@TestTargetClass(FileNameMap.class)
-public class FileNameMapTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getContentTypeFor",
- args = {java.lang.String.class}
- )
- public void test_getContentTypeFor() {
- String [] files = {"text", "txt", "htm", "html"};
-
- String [] mimeTypes = {"text/plain", "text/plain",
- "text/html", "text/html"};
-
- FileNameMap fileNameMap = URLConnection.getFileNameMap();
-
- for(int i = 0; i < files.length; i++) {
- String mimeType = fileNameMap.getContentTypeFor("test." + files[i]);
- assertEquals("getContentTypeFor returns incorrect MIME type for " +
- files[i], mimeTypes[i], mimeType);
- }
- }
-}
-
diff --git a/luni/src/test/java/tests/api/java/net/HttpRetryExceptionTest.java b/luni/src/test/java/tests/api/java/net/HttpRetryExceptionTest.java
deleted file mode 100644
index eae0c52..0000000
--- a/luni/src/test/java/tests/api/java/net/HttpRetryExceptionTest.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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 tests.api.java.net;
-
-import junit.framework.TestCase;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.net.FileNameMap;
-import java.net.HttpRetryException;
-
-@TestTargetClass(HttpRetryException.class)
-public class HttpRetryExceptionTest extends TestCase {
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "HttpRetryException",
- args = {java.lang.String.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "responseCode",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getReason",
- args = {}
- )
- })
- public void test_ConstructorLStringI() {
- String [] message = {"Test message", "", "Message", "~!@#$% &*(", null};
- int [] codes = {400, 404, 200, 500, 0};
-
- for(int i = 0; i < message.length; i++) {
- HttpRetryException hre = new HttpRetryException(message[i],
- codes[i]);
- assertEquals(message[i], hre.getReason());
- assertTrue("responseCode is incorrect: " + hre.responseCode(),
- hre.responseCode() == codes[i]);
- }
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "HttpRetryException",
- args = {java.lang.String.class, int.class, java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocation",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "responseCode",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getReason",
- args = {}
- )
- })
- public void test_ConstructorLStringILString() {
- String [] message = {"Test message", "", "Message", "~!@#$% &*(", null};
- int [] codes = {400, -1, Integer.MAX_VALUE, Integer.MIN_VALUE, 0};
- String [] locations = {"file:\\error.txt", "http:\\localhost",
- "", null, ""};
-
- for(int i = 0; i < message.length; i++) {
- HttpRetryException hre = new HttpRetryException(message[i],
- codes[i], locations[i]);
- assertEquals(message[i], hre.getReason());
- assertTrue("responseCode is incorrect: " + hre.responseCode(),
- hre.responseCode() == codes[i]);
- assertEquals(locations[i], hre.getLocation());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/JarURLConnectionTest.java b/luni/src/test/java/tests/api/java/net/JarURLConnectionTest.java
deleted file mode 100644
index 8303db3..0000000
--- a/luni/src/test/java/tests/api/java/net/JarURLConnectionTest.java
+++ /dev/null
@@ -1,548 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.JarURLConnection;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLConnection;
-import java.security.cert.Certificate;
-import java.util.Collection;
-import java.util.Map;
-import java.util.Set;
-import java.util.jar.Attributes;
-import java.util.jar.JarEntry;
-import java.util.jar.JarFile;
-import java.util.jar.JarOutputStream;
-import java.util.jar.Manifest;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipFile;
-
-import tests.support.resource.Support_Resources;
-
-@TestTargetClass(JarURLConnection.class)
-public class JarURLConnectionTest extends junit.framework.TestCase {
-
- JarURLConnection juc;
-
- URLConnection uc;
-
- private static final URL BASE = getBaseURL();
-
- private static URL getBaseURL() {
- String clazz = JarURLConnectionTest.class.getName();
- int p = clazz.lastIndexOf(".");
- String pack = (p == -1 ? "" : clazz.substring(0, p)).replace('.', File.separatorChar);
-
- return JarURLConnectionTest.class.getClassLoader().getResource(pack);
- }
-
- private URL createContent(String jarFile, String inFile)
- throws MalformedURLException {
-
- File resources = Support_Resources.createTempFolder();
-
- Support_Resources.copyFile(resources, "net", jarFile);
- File file = new File(resources.toString() + "/net/" + jarFile);
- URL fUrl1 = new URL("jar:file:" + file.getPath() + "!/" + inFile);
-
- return fUrl1;
- }
-
- /**
- * @tests java.net.JarURLConnection#getAttributes()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAttributes",
- args = {}
- )
- public void test_getAttributes() throws Exception {
- //URL u = new URL("jar:"
- // + BASE.toString()+"/lf.jar!/swt.dll");
-
- URL u = createContent("lf.jar", "swt.dll");
- juc = (JarURLConnection) u.openConnection();
- java.util.jar.Attributes a = juc.getAttributes();
- assertEquals("Returned incorrect Attributes", "SHA MD5", a
- .get(new java.util.jar.Attributes.Name("Digest-Algorithms")));
-
- //URL invURL = new URL("jar:"
- // + BASE.toString()+"/InvalidJar.jar!/Test.class");
-
- URL invURL = createContent("InvalidJar.jar", "Test.class");
-
- JarURLConnection juConn = (JarURLConnection) invURL.openConnection();
- try {
- juConn.getAttributes();
- fail("IOException was not thrown.");
- } catch(java.io.IOException io) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCertificates",
- args = {}
- )
- public void test_getCertificates() throws Exception {
-
- //URL u = new URL("jar:"
- // + BASE.toString()+"/TestCodeSigners.jar!/Test.class");
-
- URL u = createContent("TestCodeSigners.jar", "Test.class");
-
- juc = (JarURLConnection) u.openConnection();
- assertNull(juc.getCertificates());
-
- JarEntry je = juc.getJarEntry();
- JarFile jf = juc.getJarFile();
- InputStream is = jf.getInputStream(je);
- is.skip(je.getSize());
-
- Certificate [] certs = juc.getCertificates();
- assertEquals(3, certs.length);
-
- //URL invURL = new URL("jar:"
- // + BASE.toString()+"/InvalidJar.jar!/Test.class");
-
- URL invURL = createContent("InvalidJar.jar", "Test.class");
-
- JarURLConnection juConn = (JarURLConnection) invURL.openConnection();
- try {
- juConn.getCertificates();
- fail("IOException was not thrown.");
- } catch(java.io.IOException io) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getManifest",
- args = {}
- )
- public void test_getManifest() throws Exception {
-
- String [] expected = {"plus.bmp", "swt.dll"};
- //URL u = new URL("jar:"
- // + BASE.toString()+"/lf.jar!/swt.dll");
-
- URL u = createContent("lf.jar", "swt.dll");
-
- juc = (JarURLConnection) u.openConnection();
- Manifest manifest = juc.getManifest();
- Map<String, Attributes> attr = manifest.getEntries();
- assertEquals(expected.length, attr.size());
- Set<String> keys = attr.keySet();
- String [] result = new String[expected.length];
- keys.toArray(result);
-
- for(int i = 0; i < result.length; i++) {
- assertEquals(expected[i], result[i]);
- }
-
- //URL invURL = new URL("jar:"
- // + BASE.toString()+"/InvalidJar.jar!/Test.class");
-
- URL invURL = createContent("InvalidJar.jar", "Test.class");
-
- JarURLConnection juConn = (JarURLConnection) invURL.openConnection();
- try {
- juConn.getManifest();
- fail("IOException was not thrown.");
- } catch(java.io.IOException io) {
- //expected
- }
- }
-
- /**
- * @throws Exception
- * @tests java.net.JarURLConnection#getEntryName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getEntryName",
- args = {}
- )
- public void test_getEntryName() throws Exception {
- //URL u = new URL("jar:"
- // + BASE.toString()+"/lf.jar!/plus.bmp");
-
- URL u = createContent("lf.jar", "plus.bmp");
-
- juc = (JarURLConnection) u.openConnection();
- assertEquals("Returned incorrect entryName", "plus.bmp", juc
- .getEntryName());
-
- //u = new URL("jar:" + BASE.toString()+"/lf.jar!/");
-
- u = createContent("lf.jar", "");
-
- juc = (JarURLConnection) u.openConnection();
- assertNull("Returned incorrect entryName", juc.getEntryName());
-// Regression test for harmony-3053
-
- URL url = new URL("jar:file:///bar.jar!/foo.jar!/Bugs/HelloWorld.class");
- assertEquals("foo.jar!/Bugs/HelloWorld.class",((JarURLConnection)url.openConnection()).getEntryName());
- }
-
- /**
- * @tests java.net.JarURLConnection#getJarEntry()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getJarEntry",
- args = {}
- )
- public void test_getJarEntry() throws Exception {
- //URL u = new URL("jar:"
- // + BASE.toString()+"/lf.jar!/plus.bmp");
-
- URL u = createContent("lf.jar", "plus.bmp");
-
- juc = (JarURLConnection) u.openConnection();
- assertEquals("Returned incorrect JarEntry", "plus.bmp", juc
- .getJarEntry().getName());
-
- //u = new URL("jar:" + BASE.toString()+"/lf.jar!/");
- u = createContent("lf.jar", "");
-
- juc = (JarURLConnection) u.openConnection();
- assertNull("Returned incorrect JarEntry", juc.getJarEntry());
-
- //URL invURL = new URL("jar:"
- // + BASE.toString()+"/InvalidJar.jar!/Test.class");
-
- URL invURL = createContent("InvalidJar.jar", "Test.class");
-
- JarURLConnection juConn = (JarURLConnection) invURL.openConnection();
- try {
- juConn.getJarEntry();
- fail("IOException was not thrown.");
- } catch(java.io.IOException io) {
- //expected
- }
- }
-
- /**
- * @tests java.net.JarURLConnection#getJarFile()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getJarFile",
- args = {}
- )
- public void test_getJarFile() throws MalformedURLException, IOException {
- URL url = null;
- //url = new URL("jar:"
- // + BASE.toString()+"/lf.jar!/missing");
-
- url = createContent("lf.jar", "missing");
-
- JarURLConnection connection = null;
- connection = (JarURLConnection) url.openConnection();
- try {
- connection.connect();
- fail("Did not throw exception on connect");
- } catch (IOException e) {
- // expected
- }
-
- try {
- connection.getJarFile();
- fail("Did not throw exception after connect");
- } catch (IOException e) {
- // expected
- }
-
- //URL invURL = new URL("jar:"
- // + BASE.toString()+"/InvalidJar.jar!/Test.class");
-
- URL invURL = createContent("InvalidJar.jar", "Test.class");
-
- JarURLConnection juConn = (JarURLConnection) invURL.openConnection();
- try {
- juConn.getJarFile();
- fail("IOException was not thrown.");
- } catch(java.io.IOException io) {
- //expected
- }
-
- File resources = Support_Resources.createTempFolder();
-
- Support_Resources.copyFile(resources, null, "hyts_att.jar");
- File file = new File(resources.toString() + "/hyts_att.jar");
- URL fUrl1 = new URL("jar:file:" + file.getPath() + "!/");
- JarURLConnection con1 = (JarURLConnection) fUrl1.openConnection();
- ZipFile jf1 = con1.getJarFile();
- JarURLConnection con2 = (JarURLConnection) fUrl1.openConnection();
- ZipFile jf2 = con2.getJarFile();
- assertTrue("file: JarFiles not the same", jf1 == jf2);
- jf1.close();
- assertTrue("File should exist", file.exists());
-
- fUrl1 = createContent("lf.jar", "");
- //new URL("jar:" + BASE.toString()+"/lf.jar!/");
-
- con1 = (JarURLConnection) fUrl1.openConnection();
- jf1 = con1.getJarFile();
- con2 = (JarURLConnection) fUrl1.openConnection();
- jf2 = con2.getJarFile();
- assertTrue("http: JarFiles not the same", jf1 == jf2);
- jf1.close();
- }
-
- /**
- * @tests java.net.JarURLConnection.getJarFile()
- *
- * Regression test for HARMONY-29
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test.",
- method = "getJarFile",
- args = {}
- )
- public void test_getJarFile29() throws Exception {
- File jarFile = File.createTempFile("1+2 3", "test.jar");
- jarFile.deleteOnExit();
- JarOutputStream out = new JarOutputStream(new FileOutputStream(jarFile));
- out.putNextEntry(new ZipEntry("test"));
- out.closeEntry();
- out.close();
-
- JarURLConnection conn = (JarURLConnection) new URL("jar:file:"
- + jarFile.getAbsolutePath().replaceAll(" ", "%20") + "!/")
- .openConnection();
- conn.getJarFile().entries();
- }
-
- //Regression for HARMONY-3436
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Exceptions checking missed.",
- method = "setUseCaches",
- args = {boolean.class}
- )
- public void test_setUseCaches() throws Exception {
- File resources = Support_Resources.createTempFolder();
- Support_Resources.copyFile(resources, null, "hyts_att.jar");
- File file = new File(resources.toString() + "/hyts_att.jar");
- URL url = new URL("jar:file:" + file.getPath() + "!/HasAttributes.txt");
-
- JarURLConnection connection = (JarURLConnection) url.openConnection();
- connection.setUseCaches(false);
- InputStream in = connection.getInputStream();
- in = connection.getInputStream();
- JarFile jarFile1 = connection.getJarFile();
- JarEntry jarEntry1 = connection.getJarEntry();
- in.read();
- in.close();
- JarFile jarFile2 = connection.getJarFile();
- JarEntry jarEntry2 = connection.getJarEntry();
- assertSame(jarFile1, jarFile2);
- assertSame(jarEntry1, jarEntry2);
-
- try {
- connection.getInputStream();
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- }
-
- /**
- * @tests java.net.JarURLConnection#getJarFileURL()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getJarFileURL",
- args = {}
- )
- public void test_getJarFileURL() throws Exception {
- //URL fileURL = new URL(BASE.toString()+"/lf.jar");
- //URL u = new URL("jar:"
- // + BASE.toString()+"/lf.jar!/plus.bmp");
-
- URL u = createContent("lf.jar", "plus.bmp");
-
- URL fileURL = new URL(u.getPath().substring(0, u.getPath().indexOf("!")));
-
- juc = (JarURLConnection) u.openConnection();
- assertTrue("Returned incorrect file URL", juc.getJarFileURL().equals(
- fileURL));
- // Regression test for harmony-3053
- URL url = new URL("jar:file:///bar.jar!/foo.jar!/Bugs/HelloWorld.class");
- assertEquals("file:/bar.jar",((JarURLConnection)url.openConnection()).getJarFileURL().toString());
- }
-
- /**
- * @tests java.net.JarURLConnection#getMainAttributes()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMainAttributes",
- args = {}
- )
- public void test_getMainAttributes() throws Exception {
- //URL u = new URL("jar:"
- // + BASE.toString()+"/lf.jar!/swt.dll");
- URL u = createContent("lf.jar", "swt.dll");
-
- juc = (JarURLConnection) u.openConnection();
- java.util.jar.Attributes a = juc.getMainAttributes();
- assertEquals("Returned incorrect Attributes", "1.0", a
- .get(java.util.jar.Attributes.Name.MANIFEST_VERSION));
-
- //URL invURL = new URL("jar:"
- // + BASE.toString()+"/InvalidJar.jar!/Test.class");
- URL invURL = createContent("InvalidJar.jar", "Test.class");
-
- JarURLConnection juConn = (JarURLConnection) invURL.openConnection();
- try {
- juConn.getMainAttributes();
- fail("IOException was not thrown.");
- } catch(java.io.IOException io) {
- //expected
- }
- }
-
- /**
- * @tests java.net.JarURLConnection#getInputStream()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Test fails: IOException expected but IllegalStateException is thrown: ticket 128",
- method = "getInputStream",
- args = {}
- )
- public void test_getInputStream_DeleteJarFileUsingURLConnection()
- throws Exception {
- String jarFileName = "";
- String entry = "text.txt";
- String cts = System.getProperty("java.io.tmpdir");
- File tmpDir = new File(cts);
- File jarFile = tmpDir.createTempFile("file", ".jar", tmpDir);
- jarFileName = jarFile.getPath();
- FileOutputStream jarFileOutputStream = new FileOutputStream(jarFileName);
- JarOutputStream out = new JarOutputStream(new BufferedOutputStream(
- jarFileOutputStream));
- JarEntry jarEntry = new JarEntry(entry);
- out.putNextEntry(jarEntry);
- out.write(new byte[] { 'a', 'b', 'c' });
- out.close();
-
- URL url = new URL("jar:file:" + jarFileName + "!/" + entry);
- URLConnection conn = url.openConnection();
- conn.setUseCaches(false);
- InputStream is = conn.getInputStream();
- is.close();
-
- assertTrue(jarFile.delete());
-
- /*
- try {
- conn.getInputStream();
- fail("Exception was not thrown.");
- } catch (IOException e) {
- //ok
- }
-
- */
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "JarURLConnection",
- args = {java.net.URL.class}
- )
- public void test_Constructor() {
- try {
- String jarFileName = "file.jar";
- String entry = "text.txt";
- URL url = new URL("jar:file:" + jarFileName + "!/" + entry);
- TestJarURLConnection jarConn = new TestJarURLConnection(url);
- assertEquals(new URL("file:file.jar"), jarConn.getJarFileURL());
- } catch(MalformedURLException me) {
- fail("MalformedURLException was thrown.");
- }
-
- try {
- URL [] urls = {new URL("file:file.jar"),
- new URL("http://foo.com/foo/foo.jar")};
-
- for(URL url:urls) {
- try {
- new TestJarURLConnection(url);
- fail("MalformedURLException was not thrown.");
- } catch(MalformedURLException me) {
- //expected
- }
- }
- } catch(MalformedURLException me) {
- fail("MalformedURLException was thrown.");
- }
- }
-
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-
- class TestJarURLConnection extends JarURLConnection {
-
- protected TestJarURLConnection(URL arg0) throws MalformedURLException {
- super(arg0);
- }
-
- @Override
- public JarFile getJarFile() throws IOException {
- return null;
- }
-
- @Override
- public void connect() throws IOException {
-
- }
-
- }
-}
-
diff --git a/luni/src/test/java/tests/api/java/net/MalformedURLExceptionTest.java b/luni/src/test/java/tests/api/java/net/MalformedURLExceptionTest.java
deleted file mode 100644
index aa3603b..0000000
--- a/luni/src/test/java/tests/api/java/net/MalformedURLExceptionTest.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.MalformedURLException;
-import java.net.URL;
-
-@TestTargetClass(MalformedURLException.class)
-public class MalformedURLExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.MalformedURLException#MalformedURLException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "MalformedURLException",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.net.MalformedURLException()
- boolean passed;
- passed = false;
- try {
- new URL("notAProtocol://www.ibm.com");
- } catch (MalformedURLException e) {
- // correct
- passed = true;
- } catch (Exception e) {
- fail("Wrong exception thrown : " + e.getMessage());
- }
- assertTrue("Failed to throw correct exception", passed);
- }
-
- /**
- * @tests java.net.MalformedURLException#MalformedURLException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "MalformedURLException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.net.MalformedURLException(java.lang.String)
- final String myString = "Gawsh!";
- try {
- if (true)
- throw new MalformedURLException(myString);
- } catch (MalformedURLException e) {
- assertTrue("Incorrect exception text", e.toString().indexOf(
- myString) >= 0);
- return;
- }
- fail("Exception not thrown");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/MulticastSocketTest.java b/luni/src/test/java/tests/api/java/net/MulticastSocketTest.java
deleted file mode 100644
index 46c7e98..0000000
--- a/luni/src/test/java/tests/api/java/net/MulticastSocketTest.java
+++ /dev/null
@@ -1,1612 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.IOException;
-import java.net.BindException;
-import java.net.DatagramPacket;
-import java.net.DatagramSocket;
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.MulticastSocket;
-import java.net.NetworkInterface;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.net.UnknownHostException;
-import java.security.Permission;
-import java.util.Enumeration;
-
-import tests.support.Support_NetworkInterface;
-import tests.support.Support_PortManager;
-
-@TestTargetClass(MulticastSocket.class)
-public class MulticastSocketTest extends SocketTestCase {
-
- Thread t;
-
- MulticastSocket mss;
-
- MulticastServer server;
-
- // private member variables used for tests
- boolean atLeastOneInterface = false;
-
- boolean atLeastTwoInterfaces = false;
-
- private NetworkInterface networkInterface1 = null;
-
- private NetworkInterface networkInterface2 = null;
-
- private NetworkInterface IPV6networkInterface1 = null;
-
- static class MulticastServer extends Thread {
-
- public MulticastSocket ms;
-
- boolean running = true;
-
- volatile public byte[] rbuf = new byte[512];
-
- volatile DatagramPacket rdp = null;
-
- public void run() {
- try {
- while (running) {
- try {
- ms.receive(rdp);
- } catch (java.io.InterruptedIOException e) {
- Thread.yield();
- }
- ;
- }
- ;
- } catch (java.io.IOException e) {
- System.out.println("Multicast server failed: " + e);
- } finally {
- ms.close();
- }
- }
-
- public synchronized void leaveGroup(InetAddress aGroup)
- throws java.io.IOException {
- ms.leaveGroup(aGroup);
- }
-
- public void stopServer() {
- running = false;
- }
-
- public MulticastServer(InetAddress anAddress, int aPort)
- throws java.io.IOException {
- rbuf = new byte[512];
- rbuf[0] = -1;
- rdp = new DatagramPacket(rbuf, rbuf.length);
- ms = new MulticastSocket(aPort);
- ms.setSoTimeout(2000);
- ms.joinGroup(anAddress);
- }
-
- public MulticastServer(SocketAddress anAddress, int aPort,
- NetworkInterface netInterface) throws java.io.IOException {
- rbuf = new byte[512];
- rbuf[0] = -1;
- rdp = new DatagramPacket(rbuf, rbuf.length);
- ms = new MulticastSocket(aPort);
- ms.setSoTimeout(2000);
- ms.joinGroup(anAddress, netInterface);
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#MulticastSocket()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException exception checking missed.",
- method = "MulticastSocket",
- args = {}
- )
- public void test_Constructor() throws IOException {
- // regression test for 497
- MulticastSocket s = new MulticastSocket();
- // regression test for Harmony-1162
- assertTrue(s.getReuseAddress());
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkListen(int port) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new MulticastSocket();
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } catch (IOException e) {
- fail("IOException was thrown.");
- e.printStackTrace();
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#MulticastSocket(int)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException exception checking missed.",
- method = "MulticastSocket",
- args = {int.class}
- )
- public void test_ConstructorI() {
- // Test for method java.net.MulticastSocket(int)
- // Used in tests
- MulticastSocket dup = null;
- try {
- mss = new MulticastSocket();
- int port = mss.getLocalPort();
- dup = new MulticastSocket(port);
- // regression test for Harmony-1162
- assertTrue(dup.getReuseAddress());
- } catch (IOException e) {
- fail("duplicate binding not allowed: " + e);
- }
-
-
-
- if (dup != null)
- dup.close();
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkListen(int port) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new MulticastSocket(1);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } catch (IOException e) {
- fail("IOException was thrown.");
- e.printStackTrace();
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#getInterface()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInterface",
- args = {}
- )
- @KnownFailure("No interfaces if there's no debugger connected")
- public void test_getInterface() {
- // Test for method java.net.InetAddress
- // java.net.MulticastSocket.getInterface()
- assertTrue("Used for testing.", true);
-
- int groupPort = Support_PortManager.getNextPortForUDP();
- try {
- if (atLeastOneInterface) {
- // validate that we get the expected response when one was not
- // set
- mss = new MulticastSocket(groupPort);
- String preferIPv4StackValue = System
- .getProperty("java.net.preferIPv4Stack");
- String preferIPv6AddressesValue = System
- .getProperty("java.net.preferIPv6Addresses");
- if (((preferIPv4StackValue == null) || preferIPv4StackValue
- .equalsIgnoreCase("false"))
- && (preferIPv6AddressesValue != null)
- && (preferIPv6AddressesValue.equals("true"))) {
- // we expect an IPv6 ANY in this case
- assertTrue("inet Address returned when not set:"
- + mss.getInterface().toString(), InetAddress
- .getByName("::0").equals(mss.getInterface()));
- } else {
- // we expect an IPv4 ANY in this case
- assertNotNull("inet Address returned when not set:",
- mss.getInterface());
- }
-
- // validate that we get the expected response when we set via
- // setInterface
- Enumeration addresses = networkInterface1.getInetAddresses();
- if (addresses != null) {
- InetAddress firstAddress = (InetAddress) addresses
- .nextElement();
- mss.setInterface(firstAddress);
- assertTrue(
- "getNetworkInterface did not return interface set " +
- "by setInterface. Expected:"
- + firstAddress + " Got:"
- + mss.getInterface(), firstAddress
- .equals(mss.getInterface()));
-
- groupPort = Support_PortManager.getNextPortForUDP();
- mss = new MulticastSocket(groupPort);
- mss.setNetworkInterface(networkInterface1);
- assertTrue(
- "getInterface did not return interface set by " +
- "setNeworkInterface Expected: "
- + firstAddress + "Got:"
- + mss.getInterface(), NetworkInterface
- .getByInetAddress(mss.getInterface())
- .equals(networkInterface1));
- }
- mss.close();
- try {
- mss.getInterface();
- fail("SocketException was not thrown.");
- } catch(SocketException ioe) {
- //expected
- }
- }
- } catch (Exception e) {
- fail("Exception during getInterface test: " + e.toString());
- }
- }
-
- /**
- * @throws IOException
- * @tests java.net.MulticastSocket#getNetworkInterface()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getNetworkInterface",
- args = {}
- )
- @KnownFailure("No interfaces if there's no debugger connected")
- public void test_getNetworkInterface() throws IOException {
- int groupPort = Support_PortManager.getNextPortForUDP();
- if (atLeastOneInterface) {
- // validate that we get the expected response when one was not
- // set
- mss = new MulticastSocket(groupPort);
- NetworkInterface theInterface = mss.getNetworkInterface();
- assertNotNull(
- "network interface returned wrong network interface when " +
- "not set:"
- + theInterface, theInterface.getInetAddresses());
- InetAddress firstAddress = (InetAddress) theInterface
- .getInetAddresses().nextElement();
- // validate we the first address in the network interface is the
- // ANY address
- String preferIPv4StackValue = System
- .getProperty("java.net.preferIPv4Stack");
- String preferIPv6AddressesValue = System
- .getProperty("java.net.preferIPv6Addresses");
- if (((preferIPv4StackValue == null) || preferIPv4StackValue
- .equalsIgnoreCase("false"))
- && (preferIPv6AddressesValue != null)
- && (preferIPv6AddressesValue.equals("true"))) {
- assertTrue(
- "network interface returned wrong network interface " +
- "when not set:"
- + theInterface, InetAddress.getByName("::0")
- .equals(firstAddress));
-
- } else {
- assertTrue(
- "network interface returned wrong network interface " +
- "when not set:"
- + theInterface, InetAddress
- .getByName("0.0.0.0").equals(firstAddress));
- }
-
- mss.setNetworkInterface(networkInterface1);
- assertTrue(
- "getNetworkInterface did not return interface set by " +
- "setNeworkInterface",
- networkInterface1.equals(mss.getNetworkInterface()));
-
- if (atLeastTwoInterfaces) {
- mss.setNetworkInterface(networkInterface2);
- assertTrue(
- "getNetworkInterface did not return network interface " +
- "set by second setNetworkInterface call",
- networkInterface2.equals(mss.getNetworkInterface()));
- }
-
- groupPort = Support_PortManager.getNextPortForUDP();
- mss = new MulticastSocket(groupPort);
- if (IPV6networkInterface1 != null) {
- mss.setNetworkInterface(IPV6networkInterface1);
- assertTrue(
- "getNetworkInterface did not return interface set " +
- "by setNeworkInterface",
- IPV6networkInterface1.equals(mss.getNetworkInterface()));
- }
-
- // validate that we get the expected response when we set via
- // setInterface
- groupPort = Support_PortManager.getNextPortForUDP();
- mss = new MulticastSocket(groupPort);
- Enumeration addresses = networkInterface1.getInetAddresses();
- if (addresses != null) {
- firstAddress = (InetAddress) addresses.nextElement();
- mss.setInterface(firstAddress);
- assertTrue(
- "getNetworkInterface did not return interface set " +
- "by setInterface",
- networkInterface1.equals(mss.getNetworkInterface()));
- }
-
- mss.close();
- try {
- mss.getNetworkInterface();
- fail("SocketException was not thrown.");
- } catch(SocketException ioe) {
- //expected
- }
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#getTimeToLive()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTimeToLive",
- args = {}
- )
- public void test_getTimeToLive() {
- try {
- mss = new MulticastSocket();
- mss.setTimeToLive(120);
- assertTrue("Returned incorrect 1st TTL: " + mss.getTimeToLive(),
- mss.getTimeToLive() == 120);
- mss.setTimeToLive(220);
- assertTrue("Returned incorrect 2nd TTL: " + mss.getTimeToLive(),
- mss.getTimeToLive() == 220);
- mss.close();
- try {
- mss.getTimeToLive();
- fail("IOException was not thrown.");
- } catch(IOException ioe) {
- //expected
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
- } catch (Exception e) {
- handleException(e, SO_MULTICAST);
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#getTTL()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTTL",
- args = {}
- )
- public void test_getTTL() {
- // Test for method byte java.net.MulticastSocket.getTTL()
-
- try {
- mss = new MulticastSocket();
- mss.setTTL((byte) 120);
- assertTrue("Returned incorrect TTL: " + mss.getTTL(),
- mss.getTTL() == 120);
- mss.close();
- try {
- mss.getTTL();
- fail("IOException was not thrown.");
- } catch(IOException ioe) {
- //expected
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
- } catch (Exception e) {
- handleException(e, SO_MULTICAST);
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#joinGroup(java.net.InetAddress)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "joinGroup",
- args = {java.net.InetAddress.class}
- )
- public void test_joinGroupLjava_net_InetAddress() {
- // Test for method void
- // java.net.MulticastSocket.joinGroup(java.net.InetAddress)
- String msg = null;
- InetAddress group = null;
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- int groupPort = ports[0];
- try {
- group = InetAddress.getByName("224.0.0.3");
- server = new MulticastServer(group, groupPort);
- server.start();
- Thread.sleep(1000);
- msg = "Hello World";
- mss = new MulticastSocket(ports[1]);
- DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg
- .length(), group, groupPort);
- mss.joinGroup(group);
- mss.send(sdp, (byte) 10);
- Thread.sleep(1000);
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkMulticast(InetAddress maddr) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- mss.joinGroup(group);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } catch (IOException e) {
- fail("IOException was thrown.");
- e.printStackTrace();
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- mss.close();
- try {
- mss.joinGroup(group);
- fail("SocketException was not thrown.");
- } catch(SocketException ioe) {
- //expected
- }
- } catch (Exception e) {
- fail("Exception during joinGroup test: " + e.toString());
- }
- assertTrue("Group member did not recv data: ", new String(server.rdp
- .getData(), 0, server.rdp.getLength()).equals(msg));
-
- }
-
- /**
- * @throws IOException
- * @throws InterruptedException
- * @tests java.net.MulticastSocket#joinGroup(java.net.SocketAddress,
- * java.net.NetworkInterface)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "joinGroup",
- args = {java.net.SocketAddress.class, java.net.NetworkInterface.class}
- )
- @KnownFailure("Needs investigation")
- public void test_joinGroupLjava_net_SocketAddressLjava_net_NetworkInterface()
- throws IOException, InterruptedException {
- // security manager that allows us to check that we only return the
- // addresses that we should
- class mySecurityManager extends SecurityManager {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkMulticast(InetAddress address) {
- throw new SecurityException("not allowed");
- }
- }
-
- String msg = null;
- InetAddress group = null;
- SocketAddress groupSockAddr = null;
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- int groupPort = ports[0];
- int serverPort = ports[1];
-
- Enumeration theInterfaces = NetworkInterface.getNetworkInterfaces();
-
- // first validate that we handle a null group ok
- mss = new MulticastSocket(groupPort);
- try {
- mss.joinGroup(null, null);
- fail("Did not get exception when group was null");
- } catch (IllegalArgumentException e) {
- }
-
- // now validate we get the expected error if the address specified
- // is not a multicast group
- try {
- groupSockAddr = new InetSocketAddress(InetAddress
- .getByName("255.255.255.255"), groupPort);
- mss.joinGroup(groupSockAddr, null);
- fail("Did not get exception when group is not a multicast address");
- } catch (IOException e) {
- }
-
- // now try to join a group if we are not authorized
- // set the security manager that will make the first address not
- // visible
- System.setSecurityManager(new mySecurityManager());
- try {
- group = InetAddress.getByName("224.0.0.3");
- groupSockAddr = new InetSocketAddress(group, groupPort);
- mss.joinGroup(groupSockAddr, null);
- fail("Did not get exception when joining group is not allowed");
- } catch (SecurityException e) {
- }
- System.setSecurityManager(null);
-
- if (atLeastOneInterface) {
- // now validate that we can properly join a group with a null
- // network interface
- ports = Support_PortManager.getNextPortsForUDP(2);
- groupPort = ports[0];
- serverPort = ports[1];
- mss = new MulticastSocket(groupPort);
- mss.joinGroup(groupSockAddr, null);
- mss.setTimeToLive(2);
- Thread.sleep(1000);
-
- // set up the server and join the group on networkInterface1
- group = InetAddress.getByName("224.0.0.3");
- groupSockAddr = new InetSocketAddress(group, groupPort);
- server = new MulticastServer(groupSockAddr, serverPort,
- networkInterface1);
- server.start();
- Thread.sleep(1000);
- msg = "Hello World";
- DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg
- .length(), group, serverPort);
- mss.setTimeToLive(2);
- mss.send(sdp);
- Thread.sleep(1000);
- // now vaildate that we received the data as expected
- assertTrue("Group member did not recv data: ", new String(
- server.rdp.getData(), 0, server.rdp.getLength())
- .equals(msg));
- server.stopServer();
-
- // now validate that we handled the case were we join a
- // different multicast address.
- // verify we do not receive the data
- ports = Support_PortManager.getNextPortsForUDP(2);
- serverPort = ports[0];
- server = new MulticastServer(groupSockAddr, serverPort,
- networkInterface1);
- server.start();
- Thread.sleep(1000);
-
- groupPort = ports[1];
- mss = new MulticastSocket(groupPort);
- InetAddress group2 = InetAddress.getByName("224.0.0.4");
- mss.setTimeToLive(10);
- msg = "Hello World - Different Group";
- sdp = new DatagramPacket(msg.getBytes(), msg.length(), group2,
- serverPort);
- mss.send(sdp);
- Thread.sleep(1000);
- assertFalse(
- "Group member received data when sent on different group: ",
- new String(server.rdp.getData(), 0, server.rdp.getLength())
- .equals(msg));
- server.stopServer();
-
- // if there is more than one network interface then check that
- // we can join on specific interfaces and that we only receive
- // if data is received on that interface
- if (atLeastTwoInterfaces) {
- // set up server on first interfaces
- NetworkInterface loopbackInterface = NetworkInterface
- .getByInetAddress(InetAddress.getByName("127.0.0.1"));
-
- theInterfaces = NetworkInterface.getNetworkInterfaces();
- while (theInterfaces.hasMoreElements()) {
-
- NetworkInterface thisInterface = (NetworkInterface)
- theInterfaces.nextElement();
- if ((thisInterface.getInetAddresses() != null && thisInterface
- .getInetAddresses().hasMoreElements())
- && (Support_NetworkInterface
- .useInterface(thisInterface) == true)) {
- // get the first address on the interface
-
- // start server which is joined to the group and has
- // only asked for packets on this interface
- Enumeration addresses = thisInterface
- .getInetAddresses();
-
- NetworkInterface sendingInterface = null;
- boolean isLoopback = false;
- if (addresses != null) {
- InetAddress firstAddress = (InetAddress) addresses
- .nextElement();
- if (firstAddress.isLoopbackAddress()) {
- isLoopback = true;
- }
- if (firstAddress instanceof Inet4Address) {
- group = InetAddress.getByName("224.0.0.4");
- if (networkInterface1.equals(NetworkInterface
- .getByInetAddress(InetAddress
- .getByName("127.0.0.1")))) {
- sendingInterface = networkInterface2;
- } else {
- sendingInterface = networkInterface1;
- }
- } else {
- // if this interface only seems to support
- // IPV6 addresses
- group = InetAddress
- .getByName("FF01:0:0:0:0:0:2:8001");
- sendingInterface = IPV6networkInterface1;
- }
- }
-
- InetAddress useAddress = null;
- addresses = sendingInterface.getInetAddresses();
- if ((addresses != null)
- && (addresses.hasMoreElements())) {
- useAddress = (InetAddress) addresses.nextElement();
- }
-
- ports = Support_PortManager.getNextPortsForUDP(2);
- serverPort = ports[0];
- groupPort = ports[1];
- groupSockAddr = new InetSocketAddress(group, serverPort);
- server = new MulticastServer(groupSockAddr, serverPort,
- thisInterface);
- server.start();
- Thread.sleep(1000);
-
- // Now send out a package on interface
- // networkInterface 1. We should
- // only see the packet if we send it on interface 1
- InetSocketAddress theAddress = new InetSocketAddress(
- useAddress, groupPort);
- mss = new MulticastSocket(groupPort);
- mss.setNetworkInterface(sendingInterface);
- msg = "Hello World - Again" + thisInterface.getName();
- sdp = new DatagramPacket(msg.getBytes(), msg.length(),
- group, serverPort);
- mss.send(sdp);
- Thread.sleep(1000);
- if (thisInterface.equals(sendingInterface)) {
- assertTrue(
- "Group member did not recv data when " +
- "bound on specific interface: ",
- new String(server.rdp.getData(), 0,
- server.rdp.getLength()).equals(msg));
- } else {
- assertFalse(
- "Group member received data on other " +
- "interface when only asked for it on one " +
- "interface: ",
- new String(server.rdp.getData(), 0,
- server.rdp.getLength()).equals(msg));
- }
-
- server.stopServer();
- }
- }
-
- // validate that we can join the same address on two
- // different interfaces but not on the same interface
- groupPort = Support_PortManager.getNextPortForUDP();
- mss = new MulticastSocket(groupPort);
- mss.joinGroup(groupSockAddr, networkInterface1);
- mss.joinGroup(groupSockAddr, networkInterface2);
- try {
- mss.joinGroup(groupSockAddr, networkInterface1);
- fail("Did not get expected exception when joining for " +
- "second time on same interface");
- } catch (IOException e) {
- }
- }
- }
- System.setSecurityManager(null);
- }
-
- /**
- * @tests java.net.MulticastSocket#leaveGroup(java.net.InetAddress)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "leaveGroup",
- args = {java.net.InetAddress.class}
- )
- public void test_leaveGroupLjava_net_InetAddress() {
- // Test for method void
- // java.net.MulticastSocket.leaveGroup(java.net.InetAddress)
- String msg = null;
- boolean except = false;
- InetAddress group = null;
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- int groupPort = ports[0];
-
- try {
- group = InetAddress.getByName("224.0.0.3");
- msg = "Hello World";
- mss = new MulticastSocket(ports[1]);
- DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg
- .length(), group, groupPort);
- mss.send(sdp, (byte) 10);
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
- } catch (Exception e) {
- handleException(e, SO_MULTICAST);
- }
- try {
- // Try to leave s group that mss is not a member of
- mss.leaveGroup(group);
- } catch (java.io.IOException e) {
- // Correct
- except = true;
- }
- assertTrue("Failed to throw exception leaving non-member group", except);
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkMulticast(InetAddress maddr) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- mss.leaveGroup(group);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } catch (IOException e) {
- fail("IOException was thrown.");
- e.printStackTrace();
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#leaveGroup(java.net.SocketAddress,
- * java.net.NetworkInterface)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "leaveGroup",
- args = {java.net.SocketAddress.class, java.net.NetworkInterface.class}
- )
- public void test_leaveGroupLjava_net_SocketAddressLjava_net_NetworkInterface() {
- // security manager that allows us to check that we only return the
- // addresses that we should
- class mySecurityManager extends SecurityManager {
-
- public void checkPermission(Permission p) {
- }
-
- public void checkMulticast(InetAddress address) {
- throw new SecurityException("not allowed");
- }
- }
-
- String msg = null;
- InetAddress group = null;
- int groupPort = Support_PortManager.getNextPortForUDP();
- SocketAddress groupSockAddr = null;
- SocketAddress groupSockAddr2 = null;
-
- try {
- Enumeration theInterfaces = NetworkInterface.getNetworkInterfaces();
-
- // first validate that we handle a null group ok
- mss = new MulticastSocket(groupPort);
- try {
- mss.leaveGroup(null, null);
- fail("Did not get exception when group was null");
- } catch (IllegalArgumentException e) {
- }
-
- // now validate we get the expected error if the address specified
- // is not a multicast group
- try {
- group = InetAddress.getByName("255.255.255.255");
- groupSockAddr = new InetSocketAddress(group, groupPort);
- mss.leaveGroup(groupSockAddr, null);
- fail("Did not get exception when group is not a " +
- "multicast address");
- } catch (IOException e) {
- }
-
- // now try to leave a group if we are not authorized
- // set the security manager that will make the first address not
- // visible
- System.setSecurityManager(new mySecurityManager());
- try {
- group = InetAddress.getByName("224.0.0.3");
- groupSockAddr = new InetSocketAddress(group, groupPort);
- mss.leaveGroup(groupSockAddr, null);
- fail("Did not get exception when joining group is " +
- "not allowed");
- } catch (SecurityException e) {
- }
- System.setSecurityManager(null);
-
- if (atLeastOneInterface) {
-
- // now test that we can join and leave a group successfully
- groupPort = Support_PortManager.getNextPortForUDP();
- mss = new MulticastSocket(groupPort);
- groupSockAddr = new InetSocketAddress(group, groupPort);
- mss.joinGroup(groupSockAddr, null);
- mss.leaveGroup(groupSockAddr, null);
- try {
- mss.leaveGroup(groupSockAddr, null);
- fail(
- "Did not get exception when trying to leave " +
- "group that was allready left");
- } catch (IOException e) {
- }
-
- InetAddress group2 = InetAddress.getByName("224.0.0.4");
- groupSockAddr2 = new InetSocketAddress(group2, groupPort);
- mss.joinGroup(groupSockAddr, networkInterface1);
- try {
- mss.leaveGroup(groupSockAddr2, networkInterface1);
- fail(
- "Did not get exception when trying to leave " +
- "group that was never joined");
- } catch (IOException e) {
- }
-
- mss.leaveGroup(groupSockAddr, networkInterface1);
- if (atLeastTwoInterfaces) {
- mss.joinGroup(groupSockAddr, networkInterface1);
- try {
- mss.leaveGroup(groupSockAddr, networkInterface2);
- fail(
- "Did not get exception when trying to leave " +
- "group on wrong interface joined on ["
- + networkInterface1
- + "] left on ["
- + networkInterface2 + "]");
- } catch (IOException e) {
- }
- }
- }
- } catch (Exception e) {
- fail("Exception during leaveGroup test: " + e.toString());
- } finally {
- System.setSecurityManager(null);
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#send(java.net.DatagramPacket, byte)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "send",
- args = {java.net.DatagramPacket.class, byte.class}
- )
- public void test_sendLjava_net_DatagramPacketB() {
- // Test for method void
- // java.net.MulticastSocket.send(java.net.DatagramPacket, byte)
-
- String msg = "Hello World";
- InetAddress group = null;
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- int groupPort = ports[0];
-
- try {
- group = InetAddress.getByName("224.0.0.3");
- mss = new MulticastSocket(ports[1]);
- server = new MulticastServer(group, groupPort);
- server.start();
- Thread.sleep(200);
- DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg
- .length(), group, groupPort);
- mss.send(sdp, (byte) 10);
- Thread.sleep(1000);
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
- } catch (Exception e) {
- handleException(e, SO_MULTICAST);
- try {
- mss.close();
- } catch (Exception ex) {
- }
-
- return;
- }
-
- DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg
- .length(), group, groupPort);
-
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkConnect(String host,
- int port) {
- throw new SecurityException();
- }
-
- public void checkMulticast(InetAddress maddr) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- mss.send(sdp);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } catch (IOException e) {
- fail("IOException was thrown.");
- e.printStackTrace();
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- mss.close();
-
- try {
- mss.send(sdp);
- fail("IOException should be thrown.");
- } catch(IOException ioe) {
- //expected
- }
-
- byte[] data = server.rdp.getData();
- int length = server.rdp.getLength();
- assertTrue("Failed to send data. Received " + length, new String(data,
- 0, length).equals(msg));
- }
-
- /**
- * @tests java.net.MulticastSocket#setInterface(java.net.InetAddress)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setInterface",
- args = {java.net.InetAddress.class}
- )
- public void test_setInterfaceLjava_net_InetAddress() {
- // Test for method void
- // java.net.MulticastSocket.setInterface(java.net.InetAddress)
- // Note that the machine is not multi-homed
-
- try {
- mss = new MulticastSocket();
- mss.setInterface(InetAddress.getLocalHost());
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST_INTERFACE);
- } catch (Exception e) {
- //handleException(e, SO_MULTICAST_INTERFACE);
- return;
- }
- try {
- InetAddress theInterface = mss.getInterface();
- // under IPV6 we are not guarrenteed to get the same address back as
- // the address, all we should be guaranteed is that we get an
- // address on the same interface
- if (theInterface instanceof Inet6Address) {
- assertTrue(
- "Failed to return correct interface IPV6",
- NetworkInterface
- .getByInetAddress(mss.getInterface())
- .equals(
- NetworkInterface
- .getByInetAddress(theInterface)));
- } else {
- assertTrue("Failed to return correct interface IPV4 got:"
- + mss.getInterface() + " excpeted: "
- + InetAddress.getLocalHost(), mss.getInterface()
- .equals(InetAddress.getLocalHost()));
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
- } catch (SocketException e) {
- handleException(e, SO_MULTICAST);
- } catch (UnknownHostException e) {
- fail("Exception during setInterface test: " + e.toString());
- }
-
- // Regression test for Harmony-2410
- try {
- mss = new MulticastSocket();
- mss.setInterface(InetAddress.getByName("224.0.0.5"));
- } catch (UnknownHostException uhe) {
- fail("Unable to get InetAddress by name from '224.0.0.5' addr: "
- + uhe.toString());
- } catch (SocketException se) {
- // expected
- } catch (IOException ioe) {
- handleException(ioe, SO_MULTICAST_INTERFACE);
- return;
- }
- }
-
- /**
- * @throws IOException
- * @throws InterruptedException
- * @tests java.net.MulticastSocket#setNetworkInterface(
- * java.net.NetworkInterface)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setNetworkInterface",
- args = {java.net.NetworkInterface.class}
- )
- @KnownFailure("No interfaces if there's no debugger connected")
- public void test_setNetworkInterfaceLjava_net_NetworkInterface()
- throws IOException, InterruptedException {
- String msg = null;
- InetAddress group = null;
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- int groupPort = ports[0];
- int serverPort = ports[1];
- if (atLeastOneInterface) {
- // validate that null interface is handled ok
- mss = new MulticastSocket(groupPort);
-
- // this should through a socket exception to be compatible
- try {
- mss.setNetworkInterface(null);
- fail("No socket exception when we set then network " +
- "interface with NULL");
- } catch (SocketException ex) {
- }
-
- // validate that we can get and set the interface
- groupPort = Support_PortManager.getNextPortForUDP();
- mss = new MulticastSocket(groupPort);
- mss.setNetworkInterface(networkInterface1);
- assertTrue(
- "Interface did not seem to be set by setNeworkInterface",
- networkInterface1.equals(mss.getNetworkInterface()));
-
- // set up the server and join the group
- group = InetAddress.getByName("224.0.0.3");
-
- Enumeration theInterfaces = NetworkInterface.getNetworkInterfaces();
- while (theInterfaces.hasMoreElements()) {
- NetworkInterface thisInterface = (NetworkInterface) theInterfaces
- .nextElement();
- if (thisInterface.getInetAddresses() != null
- && thisInterface.getInetAddresses().hasMoreElements()) {
- if ((!((InetAddress) thisInterface.getInetAddresses()
- .nextElement()).isLoopbackAddress())
- &&
- // for windows we cannot use these pseudo
- // interfaces for the test as the packets still
- // come from the actual interface, not the
- // Pseudo interface that was set
- (Support_NetworkInterface
- .useInterface(thisInterface) == true)) {
- ports = Support_PortManager.getNextPortsForUDP(2);
- serverPort = ports[0];
- server = new MulticastServer(group, serverPort);
- server.start();
- // give the server some time to start up
- Thread.sleep(1000);
-
- // Send the packets on a particular interface. The
- // source address in the received packet
- // should be one of the addresses for the interface
- // set
- groupPort = ports[1];
- mss = new MulticastSocket(groupPort);
- mss.setNetworkInterface(thisInterface);
- msg = thisInterface.getName();
- byte theBytes[] = msg.getBytes();
- DatagramPacket sdp = new DatagramPacket(theBytes,
- theBytes.length, group, serverPort);
- mss.send(sdp);
- Thread.sleep(1000);
- String receivedMessage = new String(server.rdp
- .getData(), 0, server.rdp.getLength());
- assertTrue(
- "Group member did not recv data when send on " +
- "a specific interface: ",
- receivedMessage.equals(msg));
- assertTrue(
- "Datagram was not received from expected " +
- "interface expected["
- + thisInterface
- + "] got ["
- + NetworkInterface
- .getByInetAddress(server.rdp
- .getAddress()) + "]",
- NetworkInterface.getByInetAddress(
- server.rdp.getAddress()).equals(
- thisInterface));
-
- // stop the server
- server.stopServer();
- }
- }
- }
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#setTimeToLive(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setTimeToLive",
- args = {int.class}
- )
- public void test_setTimeToLiveI() {
- try {
- mss = new MulticastSocket();
- mss.setTimeToLive(120);
- assertTrue("Returned incorrect 1st TTL: " + mss.getTimeToLive(),
- mss.getTimeToLive() == 120);
- mss.setTimeToLive(220);
- assertTrue("Returned incorrect 2nd TTL: " + mss.getTimeToLive(),
- mss.getTimeToLive() == 220);
- mss.close();
- try {
- mss.setTimeToLive(1);
- fail("IOException was not thrown.");
- }catch(IOException ioe) {
- //expected
- }
-
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
- } catch (Exception e) {
- handleException(e, SO_MULTICAST);
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#setTTL(byte)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setTTL",
- args = {byte.class}
- )
- public void test_setTTLB() {
- // Test for method void java.net.MulticastSocket.setTTL(byte)
- try {
- mss = new MulticastSocket();
- mss.setTTL((byte) 120);
- assertTrue("Failed to set TTL: " + mss.getTTL(),
- mss.getTTL() == 120);
-
- mss.close();
- try {
- mss.setTTL((byte) 1);
- fail("IOException was not thrown.");
- } catch(IOException ioe) {
- //expected
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
- } catch (Exception e) {
- handleException(e, SO_MULTICAST);
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#MulticastSocket(java.net.SocketAddress)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "MulticastSocket",
- args = {java.net.SocketAddress.class}
- )
- public void test_ConstructorLjava_net_SocketAddress() throws Exception {
- MulticastSocket ms = new MulticastSocket((SocketAddress) null);
- assertTrue("should not be bound", !ms.isBound() && !ms.isClosed()
- && !ms.isConnected());
- ms.bind(new InetSocketAddress(InetAddress.getLocalHost(),
- Support_PortManager.getNextPortForUDP()));
- assertTrue("should be bound", ms.isBound() && !ms.isClosed()
- && !ms.isConnected());
- ms.close();
- assertTrue("should be closed", ms.isClosed());
- ms = new MulticastSocket(new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPortForUDP()));
- assertTrue("should be bound", ms.isBound() && !ms.isClosed()
- && !ms.isConnected());
- ms.close();
- assertTrue("should be closed", ms.isClosed());
- ms = new MulticastSocket(new InetSocketAddress("localhost",
- Support_PortManager.getNextPortForUDP()));
- assertTrue("should be bound", ms.isBound() && !ms.isClosed()
- && !ms.isConnected());
- ms.close();
- assertTrue("should be closed", ms.isClosed());
- boolean exception = false;
- try {
- ms = new MulticastSocket(new InetSocketAddress("unresolvedname",
- Support_PortManager.getNextPortForUDP()));
- } catch (IOException e) {
- exception = true;
- }
- assertTrue("Expected IOException", exception);
-
- // regression test for Harmony-1162
- InetSocketAddress addr = new InetSocketAddress("0.0.0.0", 0);
- MulticastSocket s = new MulticastSocket(addr);
- assertTrue(s.getReuseAddress());
-
- InetSocketAddress isa = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPortForUDP());
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkListen(int port) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new MulticastSocket(isa);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } catch (IOException e) {
- fail("IOException was thrown.");
- e.printStackTrace();
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#getLoopbackMode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLoopbackMode",
- args = {}
- )
- public void test_getLoopbackMode() {
- try {
- MulticastSocket ms = new MulticastSocket((SocketAddress) null);
- assertTrue("should not be bound", !ms.isBound() && !ms.isClosed()
- && !ms.isConnected());
- ms.getLoopbackMode();
- assertTrue("should not be bound", !ms.isBound() && !ms.isClosed()
- && !ms.isConnected());
- ms.close();
- assertTrue("should be closed", ms.isClosed());
- try {
- ms.getLoopbackMode();
- fail("SocketException was not thrown.");
- } catch(SocketException ioe) {
- //expected
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_USELOOPBACK);
- } catch (IOException e) {
- handleException(e, SO_USELOOPBACK);
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#setLoopbackMode(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setLoopbackMode",
- args = {boolean.class}
- )
- public void test_setLoopbackModeZ() {
- try {
- MulticastSocket ms = new MulticastSocket();
- ms.setLoopbackMode(true);
- assertTrue("loopback should be true", ms.getLoopbackMode());
- ms.setLoopbackMode(false);
- assertTrue("loopback should be false", !ms.getLoopbackMode());
- ms.close();
- assertTrue("should be closed", ms.isClosed());
-
- try {
- ms.setLoopbackMode(true);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
-
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_USELOOPBACK);
- } catch (IOException e) {
- handleException(e, SO_USELOOPBACK);
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#setLoopbackMode(boolean)
- */
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- notes = "SocketException checking missed",
- method = "setLoopbackMode",
- args = {boolean.class}
- )
- public void test_setLoopbackModeSendReceive() throws IOException{
- final String ADDRESS = "224.1.2.3";
- final int PORT = Support_PortManager.getNextPortForUDP();
- final String message = "Hello, world!";
-
- // test send receive
- MulticastSocket socket = null;
- try {
- // open a multicast socket
- socket = new MulticastSocket(PORT);
- socket.setLoopbackMode(false); // false indecates doing loop back
- socket.joinGroup(InetAddress.getByName(ADDRESS));
-
- // send the datagram
- byte[] sendData = message.getBytes();
- DatagramPacket sendDatagram = new DatagramPacket(sendData, 0,
- sendData.length, new InetSocketAddress(InetAddress
- .getByName(ADDRESS), PORT));
- socket.send(sendDatagram);
-
- // receive the datagram
- byte[] recvData = new byte[100];
- DatagramPacket recvDatagram = new DatagramPacket(recvData,
- recvData.length);
- socket.setSoTimeout(5000); // prevent eternal block in
- // socket.receive()
- socket.receive(recvDatagram);
- String recvMessage = new String(recvData, 0, recvDatagram
- .getLength());
- assertEquals(message, recvMessage);
- } finally {
- if (socket != null)
- socket.close();
- }
- }
-
-
- /**
- * @tests java.net.MulticastSocket#setReuseAddress(boolean)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "SocketException checking missesd. Method inherited from " +
- "class java.net.DatagramSocket",
- method = "setReuseAddress",
- args = {boolean.class}
- )
- public void test_setReuseAddressZ() {
- try {
- // test case were we set it to false
- MulticastSocket theSocket1 = null;
- MulticastSocket theSocket2 = null;
- try {
- InetSocketAddress theAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), Support_PortManager
- .getNextPortForUDP());
- theSocket1 = new MulticastSocket(null);
- theSocket2 = new MulticastSocket(null);
- theSocket1.setReuseAddress(false);
- theSocket2.setReuseAddress(false);
- theSocket1.bind(theAddress);
- theSocket2.bind(theAddress);
- fail(
- "No exception when trying to connect to do " +
- "duplicate socket bind with re-useaddr set to false");
- } catch (BindException e) {
-
- }
- if (theSocket1 != null)
- theSocket1.close();
- if (theSocket2 != null)
- theSocket2.close();
-
- // test case were we set it to true
- try {
- InetSocketAddress theAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), Support_PortManager
- .getNextPortForUDP());
- theSocket1 = new MulticastSocket(null);
- theSocket2 = new MulticastSocket(null);
- theSocket1.setReuseAddress(true);
- theSocket2.setReuseAddress(true);
- theSocket1.bind(theAddress);
- theSocket2.bind(theAddress);
- } catch (Exception e) {
- fail(
- "unexpected exception when trying to connect " +
- "to do duplicate socket bind with re-useaddr set " +
- "to true");
- }
- if (theSocket1 != null)
- theSocket1.close();
- if (theSocket2 != null)
- theSocket2.close();
-
- // test the default case which we expect to be the same on all
- // platforms
- try {
- InetSocketAddress theAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), Support_PortManager
- .getNextPortForUDP());
- theSocket1 = new MulticastSocket(null);
- theSocket2 = new MulticastSocket(null);
- theSocket1.bind(theAddress);
- theSocket2.bind(theAddress);
- } catch (BindException e) {
- fail(
- "unexpected exception when trying to connect to do " +
- "duplicate socket bind with re-useaddr left as default");
- }
- if (theSocket1 != null)
- theSocket1.close();
- if (theSocket2 != null)
- theSocket2.close();
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
- } catch (Exception e) {
- handleException(e, SO_REUSEADDR);
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
-
- Enumeration theInterfaces = null;
- try {
- theInterfaces = NetworkInterface.getNetworkInterfaces();
- } catch (Exception e) {
- }
-
- // only consider interfaces that have addresses associated with them.
- // Otherwise tests don't work so well
- if (theInterfaces != null) {
-
- atLeastOneInterface = false;
- while (theInterfaces.hasMoreElements()
- && (atLeastOneInterface == false)) {
- networkInterface1 = (NetworkInterface) theInterfaces
- .nextElement();
- if ((networkInterface1.getInetAddresses() != null)
- && networkInterface1.getInetAddresses()
- .hasMoreElements() &&
- // we only want real interfaces
- (Support_NetworkInterface
- .useInterface(networkInterface1) == true)) {
- atLeastOneInterface = true;
- }
- }
-
- atLeastTwoInterfaces = false;
- if (theInterfaces.hasMoreElements()) {
- while (theInterfaces.hasMoreElements()
- && (atLeastTwoInterfaces == false)) {
- networkInterface2 = (NetworkInterface) theInterfaces
- .nextElement();
- if ((networkInterface2.getInetAddresses() != null)
- && networkInterface2.getInetAddresses()
- .hasMoreElements() &&
- // we only want real interfaces
- (Support_NetworkInterface
- .useInterface(networkInterface2) == true)) {
- atLeastTwoInterfaces = true;
- }
- }
- }
-
- Enumeration addresses;
-
- // first the first interface that supports IPV6 if one exists
- try {
- theInterfaces = NetworkInterface.getNetworkInterfaces();
- } catch (Exception e) {
- }
- boolean found = false;
- while (theInterfaces.hasMoreElements() && !found) {
- NetworkInterface nextInterface = (NetworkInterface) theInterfaces
- .nextElement();
- addresses = nextInterface.getInetAddresses();
- if (addresses != null) {
- while (addresses.hasMoreElements()) {
- InetAddress nextAddress = (InetAddress) addresses
- .nextElement();
- if (nextAddress instanceof Inet6Address) {
- IPV6networkInterface1 = nextInterface;
- found = true;
- break;
- }
- }
- }
- }
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
-
- if (t != null)
- t.interrupt();
- if (mss != null)
- mss.close();
- if (server != null)
- server.stopServer();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/NetPermissionTest.java b/luni/src/test/java/tests/api/java/net/NetPermissionTest.java
deleted file mode 100644
index fdc197a..0000000
--- a/luni/src/test/java/tests/api/java/net/NetPermissionTest.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.NetPermission;
-
-@TestTargetClass(NetPermission.class)
-public class NetPermissionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.NetPermission#NetPermission(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NetPermission",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.net.NetPermission(java.lang.String)
- NetPermission n = new NetPermission("requestPasswordAuthentication");
- assertEquals("Returned incorrect name",
- "requestPasswordAuthentication", n.getName());
- }
-
- /**
- * @tests java.net.NetPermission#NetPermission(java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NetPermission",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_String() {
- // Test for method java.net.NetPermission(java.lang.String,
- // java.lang.String)
- NetPermission n = new NetPermission("requestPasswordAuthentication",
- null);
- assertEquals("Returned incorrect name",
- "requestPasswordAuthentication", n.getName());
- NetPermission n1 = new NetPermission("requestPasswordAuthentication",
- "");
- assertEquals("", n1.getActions());
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/NetworkInterfaceTest.java b/luni/src/test/java/tests/api/java/net/NetworkInterfaceTest.java
deleted file mode 100644
index fc9e57d..0000000
--- a/luni/src/test/java/tests/api/java/net/NetworkInterfaceTest.java
+++ /dev/null
@@ -1,609 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.InetAddress;
-import java.net.NetworkInterface;
-import java.net.SocketException;
-import java.util.ArrayList;
-import java.util.Enumeration;
-
-@TestTargetClass(NetworkInterface.class)
-public class NetworkInterfaceTest extends junit.framework.TestCase {
-
- // private member variables used for tests
- boolean atLeastOneInterface = false;
-
- boolean atLeastTwoInterfaces = false;
-
- private NetworkInterface networkInterface1 = null;
-
- private NetworkInterface sameAsNetworkInterface1 = null;
-
- private NetworkInterface networkInterface2 = null;
-
- /**
- * @tests java.net.NetworkInterface#getName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getName",
- args = {}
- )
- public void test_getName() {
- if (atLeastOneInterface) {
- assertNotNull("validate that non null name is returned",
- networkInterface1.getName());
- assertFalse("validate that non-zero length name is generated",
- networkInterface1.getName().equals(""));
- }
- if (atLeastTwoInterfaces) {
- assertFalse(
- "Validate strings are different for different interfaces",
- networkInterface1.getName().equals(
- networkInterface2.getName()));
- }
- }
-
- /**
- * @tests java.net.NetworkInterface#getInetAddresses()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInetAddresses",
- args = {}
- )
- public void test_getInetAddresses() {
-
- // security manager that allows us to check that we only return the
- // addresses that we should
- class mySecurityManager extends SecurityManager {
-
- ArrayList disallowedNames = null;
-
- public mySecurityManager(ArrayList addresses) {
- disallowedNames = new ArrayList();
- for (int i = 0; i < addresses.size(); i++) {
- disallowedNames.add(((InetAddress) addresses.get(i))
- .getHostName());
- disallowedNames.add(((InetAddress) addresses.get(i))
- .getHostAddress());
- }
- }
-
- public void checkConnect(String host, int port) {
-
- if (host == null) {
- throw new NullPointerException("host was null)");
- }
-
- for (int i = 0; i < disallowedNames.size(); i++) {
- if (((String) disallowedNames.get(i)).equals(host)) {
- throw new SecurityException("not allowed");
- }
- }
- }
-
- }
-
- if (atLeastOneInterface) {
- Enumeration theAddresses = networkInterface1.getInetAddresses();
- if (theAddresses != null) {
- while (theAddresses.hasMoreElements()) {
- InetAddress theAddress = (InetAddress) theAddresses
- .nextElement();
- assertTrue("validate that address is not null",
- null != theAddress);
- }
- }
- }
-
- if (atLeastTwoInterfaces) {
- Enumeration theAddresses = networkInterface2.getInetAddresses();
- if (theAddresses != null) {
- while (theAddresses.hasMoreElements()) {
- InetAddress theAddress = (InetAddress) theAddresses
- .nextElement();
- assertTrue("validate that address is not null",
- null != theAddress);
- }
- }
- }
-
- // create the list of ok and not ok addresses to return
- if (atLeastOneInterface) {
- ArrayList okAddresses = new ArrayList();
- Enumeration addresses = networkInterface1.getInetAddresses();
- int index = 0;
- ArrayList notOkAddresses = new ArrayList();
- if (addresses != null) {
- while (addresses.hasMoreElements()) {
- InetAddress theAddress = (InetAddress) addresses
- .nextElement();
- if (index != 0) {
- okAddresses.add(theAddress);
- } else {
- notOkAddresses.add(theAddress);
- }
- index++;
- }
- }
-
- // do the same for network interface 2 it it exists
- if (atLeastTwoInterfaces) {
- addresses = networkInterface2.getInetAddresses();
- index = 0;
- if (addresses != null) {
- while (addresses.hasMoreElements()) {
- InetAddress theAddress = (InetAddress) addresses
- .nextElement();
- if (index != 0) {
- okAddresses.add(theAddress);
- } else {
- notOkAddresses.add(theAddress);
- }
- index++;
- }
- }
- }
-
- // set the security manager that will make the first address not
- // visible
- System.setSecurityManager(new mySecurityManager(notOkAddresses));
-
- // validate not ok addresses are not returned
- for (int i = 0; i < notOkAddresses.size(); i++) {
- Enumeration reducedAddresses = networkInterface1
- .getInetAddresses();
- if (reducedAddresses != null) {
- while (reducedAddresses.hasMoreElements()) {
- InetAddress nextAddress = (InetAddress) reducedAddresses
- .nextElement();
- assertTrue(
- "validate that address without permission is not returned",
- !nextAddress.equals(notOkAddresses.get(i)));
- }
- }
- if (atLeastTwoInterfaces) {
- reducedAddresses = networkInterface2.getInetAddresses();
- if (reducedAddresses != null) {
- while (reducedAddresses.hasMoreElements()) {
- InetAddress nextAddress = (InetAddress) reducedAddresses
- .nextElement();
- assertTrue(
- "validate that address without permission is not returned",
- !nextAddress.equals(notOkAddresses.get(i)));
- }
- }
- }
- }
-
- // validate that ok addresses are returned
- for (int i = 0; i < okAddresses.size(); i++) {
- boolean addressReturned = false;
- Enumeration reducedAddresses = networkInterface1
- .getInetAddresses();
- if (reducedAddresses != null) {
- while (reducedAddresses.hasMoreElements()) {
- InetAddress nextAddress = (InetAddress) reducedAddresses
- .nextElement();
- if (nextAddress.equals(okAddresses.get(i))) {
- addressReturned = true;
- }
- }
- }
- if (atLeastTwoInterfaces) {
- reducedAddresses = networkInterface2.getInetAddresses();
- if (reducedAddresses != null) {
- while (reducedAddresses.hasMoreElements()) {
- InetAddress nextAddress = (InetAddress) reducedAddresses
- .nextElement();
- if (nextAddress.equals(okAddresses.get(i))) {
- addressReturned = true;
- }
- }
- }
- }
- assertTrue("validate that address with permission is returned",
- addressReturned);
- }
-
- // validate that we can get the interface by specifying the address.
- // This is to be compatible
- for (int i = 0; i < notOkAddresses.size(); i++) {
- try {
- assertNotNull(
- "validate we cannot get the NetworkInterface with an address for which we have no privs",
- NetworkInterface
- .getByInetAddress((InetAddress) notOkAddresses
- .get(i)));
- } catch (Exception e) {
- fail("get NetworkInterface for address with no perm - exception");
- }
- }
-
- // validate that we can get the network interface for the good
- // addresses
- try {
- for (int i = 0; i < okAddresses.size(); i++) {
- assertNotNull(
- "validate we cannot get the NetworkInterface with an address fro which we have no privs",
- NetworkInterface
- .getByInetAddress((InetAddress) okAddresses
- .get(i)));
- }
- } catch (Exception e) {
- fail("get NetworkInterface for address with perm - exception");
- }
-
- System.setSecurityManager(null);
- }
- }
-
- /**
- * @tests java.net.NetworkInterface#getDisplayName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDisplayName",
- args = {}
- )
- public void test_getDisplayName() {
- if (atLeastOneInterface) {
- assertNotNull("validate that non null display name is returned",
- networkInterface1.getDisplayName());
- assertFalse(
- "validate that non-zero lengtj display name is generated",
- networkInterface1.getDisplayName().equals(""));
- }
- if (atLeastTwoInterfaces) {
- assertFalse(
- "Validate strings are different for different interfaces",
- networkInterface1.getDisplayName().equals(
- networkInterface2.getDisplayName()));
- }
- }
-
- /**
- * @tests java.net.NetworkInterface#getByName(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "SocketException checking missed.",
- method = "getByName",
- args = {java.lang.String.class}
- )
- public void test_getByNameLjava_lang_String() {
- try {
- assertNull("validate null handled ok",
- NetworkInterface.getByName(null));
- fail("getByName did not throw NullPointerException for null argument");
- } catch (NullPointerException e) {
- } catch (Exception e) {
- fail("getByName, null inetAddress - raised exception : "
- + e.getMessage());
- }
-
- try {
- assertNull("validate handled ok if we ask for name not associated with any interface",
- NetworkInterface.getByName("8not a name4"));
- } catch (Exception e) {
- fail("getByName, unknown inetAddress - raised exception : "
- + e.getMessage());
- }
-
- // for each address in an interface validate that we get the right
- // interface for that name
- if (atLeastOneInterface) {
- String theName = networkInterface1.getName();
- if (theName != null) {
- try {
- assertTrue(
- "validate that Interface can be obtained with its name",
- NetworkInterface.getByName(theName).equals(
- networkInterface1));
- } catch (Exception e) {
- fail("validate to get network interface using name - socket exception");
- }
- }
- try {
- NetworkInterface.getByName(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- }
- }
-
- // validate that we get the right interface with the second interface as
- // well (ie we just don't always get the first interface
- if (atLeastTwoInterfaces) {
- String theName = networkInterface2.getName();
- if (theName != null) {
- try {
- assertTrue(
- "validate that Interface can be obtained with its name",
- NetworkInterface.getByName(theName).equals(
- networkInterface2));
- } catch (Exception e) {
- fail("validate to get network interface using name - socket exception");
- }
- }
- }
- }
-
- /**
- * @tests java.net.NetworkInterface#getByInetAddress(java.net.InetAddress)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "SocketException checking missed.",
- method = "getByInetAddress",
- args = {java.net.InetAddress.class}
- )
- public void test_getByInetAddressLjava_net_InetAddress() {
-
- byte addressBytes[] = new byte[4];
- addressBytes[0] = 0;
- addressBytes[1] = 0;
- addressBytes[2] = 0;
- addressBytes[3] = 0;
-
- try {
- assertNull("validate null handled ok",
- NetworkInterface.getByInetAddress(null));
- fail("should not get here if getByInetAddress throws "
- + "NullPointerException if null passed in");
- } catch (NullPointerException e) {
- } catch (Exception e) {
- fail("getByInetAddress, null inetAddress should have raised NPE"
- + " but instead threw a : " + e.getMessage());
- }
-
- try {
- assertNull("validate handled ok if we ask for address not associated with any interface",
- NetworkInterface.getByInetAddress(InetAddress
- .getByAddress(addressBytes)));
- } catch (Exception e) {
- fail("getByInetAddress, unknown inetAddress threw exception : " + e);
- }
-
- // for each address in an interface validate that we get the right
- // interface for that address
- if (atLeastOneInterface) {
- Enumeration addresses = networkInterface1.getInetAddresses();
- if (addresses != null) {
- while (addresses.hasMoreElements()) {
- InetAddress theAddress = (InetAddress) addresses
- .nextElement();
- try {
- assertTrue(
- "validate that Interface can be obtained with any one of its addresses",
- NetworkInterface.getByInetAddress(theAddress)
- .equals(networkInterface1));
- } catch (Exception e) {
- fail("validate to get address using inetAddress " +
- "threw exception : " + e);
- }
- }
- }
-
- try {
- NetworkInterface.getByInetAddress(null);
- fail("NullPointerException should be thrown.");
- } catch(NullPointerException npe) {
- //expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- }
- }
-
- // validate that we get the right interface with the second interface as
- // well (ie we just don't always get the first interface
- if (atLeastTwoInterfaces) {
- Enumeration addresses = networkInterface2.getInetAddresses();
- if (addresses != null) {
- while (addresses.hasMoreElements()) {
- InetAddress theAddress = (InetAddress) addresses
- .nextElement();
- try {
- assertTrue(
- "validate that Interface can be obtained with any one of its addresses",
- NetworkInterface.getByInetAddress(theAddress)
- .equals(networkInterface2));
- } catch (Exception e) {
- fail("validate to get address using inetAddress "
- + "threw exception : " + e);
- }
- }
- }
- }
- }
-
- /**
- * @tests java.net.NetworkInterface#getNetworkInterfaces()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "SocketException checking missed.",
- method = "getNetworkInterfaces",
- args = {}
- )
- public void test_getNetworkInterfaces() {
-
- // really this is tested by all of the other calls but just make sure we
- // can call it and get a list of interfaces if they exist
- try {
- Enumeration theInterfaces = NetworkInterface.getNetworkInterfaces();
- } catch (Exception e) {
- fail("get Network Interfaces - raised exception : "
- + e.getMessage());
- }
- }
-
- /**
- * @tests java.net.NetworkInterface#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean
- // java.net.SocketPermission.equals(java.lang.Object)
- if (atLeastOneInterface) {
- assertTrue("If objects are the same true is returned",
- networkInterface1.equals(sameAsNetworkInterface1));
- assertFalse("Validate Null handled ok", networkInterface1
- .equals(null));
- }
- if (atLeastTwoInterfaces) {
- assertFalse("If objects are different false is returned",
- networkInterface1.equals(networkInterface2));
- }
- }
-
- /**
- * @tests java.net.NetworkInterface#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
-
- if (atLeastOneInterface) {
- assertTrue(
- "validate that hash codes are the same for two calls on the same object",
- networkInterface1.hashCode() == networkInterface1
- .hashCode());
- assertTrue(
- "validate that hash codes are the same for two objects for which equals is true",
- networkInterface1.hashCode() == sameAsNetworkInterface1
- .hashCode());
- }
- }
-
- /**
- * @tests java.net.NetworkInterface#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- if (atLeastOneInterface) {
- assertNotNull("validate that non null string is generated",
- networkInterface1.toString());
- assertFalse("validate that non-zero length string is generated",
- networkInterface1.toString().equals(""));
- }
- if (atLeastTwoInterfaces) {
- assertFalse(
- "Validate strings are different for different interfaces",
- networkInterface1.toString().equals(
- networkInterface2.toString()));
- }
- }
-
- protected void setUp() {
-
- Enumeration theInterfaces = null;
- try {
- theInterfaces = NetworkInterface.getNetworkInterfaces();
- } catch (Exception e) {
- fail("Exception occurred getting network interfaces : " + e);
- }
-
- // Set up NetworkInterface instance members. Note that because the call
- // to NetworkInterface.getNetworkInterfaces() returns *all* of the
- // interfaces on the test machine it is possible that one or more of
- // them will not currently be bound to an InetAddress. e.g. a laptop
- // running connected by a wire to the local network may also have a
- // wireless interface that is not active and so has no InetAddress
- // bound to it. For these tests only work with NetworkInterface objects
- // that are bound to an InetAddress.
- if ((theInterfaces != null) && (theInterfaces.hasMoreElements())) {
- while ((theInterfaces.hasMoreElements())
- && (atLeastOneInterface == false)) {
- NetworkInterface theInterface = (NetworkInterface) theInterfaces
- .nextElement();
- if (theInterface.getInetAddresses() != null) {
- // Ensure that the current NetworkInterface has at least
- // one InetAddress bound to it.
- Enumeration addrs = theInterface.getInetAddresses();
- if ((addrs != null) && (addrs.hasMoreElements())) {
- atLeastOneInterface = true;
- networkInterface1 = theInterface;
- }// end if
- }
- }
-
- while ((theInterfaces.hasMoreElements())
- && (atLeastTwoInterfaces == false)) {
- NetworkInterface theInterface = (NetworkInterface) theInterfaces
- .nextElement();
- if (theInterface.getInetAddresses() != null) {
- // Ensure that the current NetworkInterface has at least
- // one InetAddress bound to it.
- Enumeration addrs = theInterface.getInetAddresses();
- if ((addrs != null) && (addrs.hasMoreElements())) {
- atLeastTwoInterfaces = true;
- networkInterface2 = theInterface;
- }// end if
- }
- }
-
- // Only set sameAsNetworkInterface1 if we succeeded in finding
- // at least one good NetworkInterface
- if (atLeastOneInterface) {
- Enumeration addresses = networkInterface1.getInetAddresses();
- if (addresses != null) {
- try {
- if (addresses.hasMoreElements()) {
- sameAsNetworkInterface1 = NetworkInterface
- .getByInetAddress((InetAddress) addresses
- .nextElement());
- }
- } catch (SocketException e) {
- fail("SocketException occurred : " + e);
- }
- }
- }// end if atLeastOneInterface
- }
- }
-
- protected void tearDown() {
- System.setSecurityManager(null);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/NoRouteToHostExceptionTest.java b/luni/src/test/java/tests/api/java/net/NoRouteToHostExceptionTest.java
deleted file mode 100644
index 3cf1e44..0000000
--- a/luni/src/test/java/tests/api/java/net/NoRouteToHostExceptionTest.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.NoRouteToHostException;
-
-@TestTargetClass(NoRouteToHostException.class)
-public class NoRouteToHostExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.NoRouteToHostException#NoRouteToHostException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NoRouteToHostException",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.net.NoRouteToHostException()
-
- try {
- if (true)
- throw new NoRouteToHostException();
- } catch (NoRouteToHostException e) {
- return;
- }
- fail("Failed to generate expected exception");
- }
-
- /**
- * @tests java.net.NoRouteToHostException#NoRouteToHostException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NoRouteToHostException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.net.NoRouteToHostException(java.lang.String)
- // Cannot test correctly without changing some routing tables !!
-
- try {
- if (true)
- throw new NoRouteToHostException("test");
- } catch (NoRouteToHostException e) {
- assertEquals("Threw exception with incorrect message", "test", e.getMessage()
- );
- return;
- }
- fail("Failed to generate expected exception");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/PasswordAuthenticationTest.java b/luni/src/test/java/tests/api/java/net/PasswordAuthenticationTest.java
deleted file mode 100644
index b9c2da7..0000000
--- a/luni/src/test/java/tests/api/java/net/PasswordAuthenticationTest.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.PasswordAuthentication;
-
-@TestTargetClass(PasswordAuthentication.class)
-public class PasswordAuthenticationTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.PasswordAuthentication#PasswordAuthentication(java.lang.String,
- * char[])
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PasswordAuthentication",
- args = {java.lang.String.class, char[].class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPassword",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getUserName",
- args = {}
- )
- })
- public void test_ConstructorLjava_lang_String$C() {
- // Test for method java.net.PasswordAuthentication(java.lang.String,
- // char [])
- char[] password = new char[] { 'd', 'r', 'o', 'w', 's', 's', 'a', 'p' };
- final String name = "Joe Blow";
- PasswordAuthentication pa = new PasswordAuthentication(name, password);
- char[] returnedPassword = pa.getPassword();
- assertTrue("Incorrect name", pa.getUserName().equals(name));
- assertTrue("Password was not cloned", returnedPassword != password);
- assertTrue("Passwords not equal length",
- returnedPassword.length == password.length);
- for (int counter = password.length - 1; counter >= 0; counter--)
- assertTrue("Passwords not equal",
- returnedPassword[counter] == password[counter]);
-
- try {
- new PasswordAuthentication(name, null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- pa = new PasswordAuthentication(null, password);
- assertNull(pa.getUserName());
- assertEquals(password.length, pa.getPassword().length);
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/PortUnreachableExceptionTest.java b/luni/src/test/java/tests/api/java/net/PortUnreachableExceptionTest.java
deleted file mode 100644
index 8131220..0000000
--- a/luni/src/test/java/tests/api/java/net/PortUnreachableExceptionTest.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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 tests.api.java.net;
-
-import junit.framework.TestCase;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.net.PasswordAuthentication;
-import java.net.PortUnreachableException;
-
-@TestTargetClass(PortUnreachableException.class)
-public class PortUnreachableExceptionTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PortUnreachableException",
- args = {}
- )
- public void test_Constructor() {
- PortUnreachableException pue = new PortUnreachableException();
- assertNull(pue.getMessage());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PortUnreachableException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLString() {
- String [] messages = {"", null, "Test Message"};
- for(String str:messages) {
- PortUnreachableException pue = new PortUnreachableException(str);
- assertEquals(str, pue.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/ProtocolExceptionTest.java b/luni/src/test/java/tests/api/java/net/ProtocolExceptionTest.java
deleted file mode 100644
index 9bcd738..0000000
--- a/luni/src/test/java/tests/api/java/net/ProtocolExceptionTest.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.ProtocolException;
-
-@TestTargetClass(ProtocolException.class)
-public class ProtocolExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.ProtocolException#ProtocolException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ProtocolException",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.net.ProtocolException()
- try {
- throw new ProtocolException();
- } catch (ProtocolException e) {
- return;
- } catch (Exception e) {
- fail("Exception during ProtocolException test : " + e.getMessage());
- }
- fail("Failed to generate expected exception");
- }
-
- /**
- * @tests java.net.ProtocolException#ProtocolException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ProtocolException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.net.ProtocolException(java.lang.String)
- try {
- throw new ProtocolException("Some error message");
- } catch (ProtocolException e) {
- return;
- } catch (Exception e) {
- fail("Exception during ProtocolException test : " + e.getMessage());
- }
- fail("Failed to generate expected exception");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/ProxySelectorTest.java b/luni/src/test/java/tests/api/java/net/ProxySelectorTest.java
deleted file mode 100644
index f208954..0000000
--- a/luni/src/test/java/tests/api/java/net/ProxySelectorTest.java
+++ /dev/null
@@ -1,737 +0,0 @@
-/* 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.NetPermission;
-import java.net.Proxy;
-import java.net.ProxySelector;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.security.Permission;
-import java.util.List;
-import java.util.Properties;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(ProxySelector.class)
-public class ProxySelectorTest extends TestCase {
-
- private static final String HTTP_PROXY_HOST = "127.0.0.1";
-
- private static final int HTTP_PROXY_PORT = 80;
-
- private static final String HTTPS_PROXY_HOST = "127.0.0.2";
-
- private static final int HTTPS_PROXY_PORT = 443;
-
- private static final String FTP_PROXY_HOST = "127.0.0.3";
-
- private static final int FTP_PROXY_PORT = 80;
-
- private static final String SOCKS_PROXY_HOST = "127.0.0.4";
-
- private static final int SOCKS_PROXY_PORT = 1080;
-
- private static URI httpUri;
-
- private static URI ftpUri;
-
- private static URI httpsUri;
-
- private static URI tcpUri;
-
- private List proxyList;
-
- private ProxySelector selector = ProxySelector.getDefault();
-
- static {
- try {
- httpUri = new URI("http://test.com");
- ftpUri = new URI("ftp://test.com");
- httpsUri = new URI("https://test.com");
- tcpUri = new URI("socket://host.com");
- } catch (URISyntaxException e) {
-
- }
- }
-
- /*
- * Original system properties must be restored after running each test case.
- */
- private Properties orignalSystemProperties;
-
- /**
- * @tests java.net.ProxySelector#getDefault()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for getDefault method.",
- method = "getDefault",
- args = {}
- )
- public void test_getDefault() {
- ProxySelector selector1 = ProxySelector.getDefault();
- assertNotNull(selector1);
-
- ProxySelector selector2 = ProxySelector.getDefault();
- assertSame(selector1, selector2);
- }
-
- /**
- * @tests java.net.ProxySelector#getDefault()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for getDefault method.",
- method = "getDefault",
- args = {}
- )
- public void test_getDefault_Security() {
- SecurityManager orignalSecurityManager = System.getSecurityManager();
- try {
- System.setSecurityManager(new MockSecurityManager());
- } catch (SecurityException e) {
- System.err.println("No setSecurityManager permission.");
- System.err.println("test_getDefault_Security is not tested");
- return;
- }
- try {
- ProxySelector.getDefault();
- fail("should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(orignalSecurityManager);
- }
- }
-
- /**
- * @tests java.net.ProxySelector#setDefault(ProxySelector)}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for setDefault method.",
- method = "setDefault",
- args = {java.net.ProxySelector.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ProxySelector",
- args = {}
- )
- })
- public void test_setDefaultLjava_net_ProxySelector() {
- ProxySelector originalSelector = ProxySelector.getDefault();
- try {
- ProxySelector newSelector = new MockProxySelector();
- ProxySelector.setDefault(newSelector);
- assertSame(newSelector, ProxySelector.getDefault());
- // use null to unset
- ProxySelector.setDefault(null);
- assertSame(null, ProxySelector.getDefault());
- } finally {
- ProxySelector.setDefault(originalSelector);
- }
- }
-
- /**
- * @tests java.net.ProxySelector#setDefault(ProxySelector)}
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for setDefault method.",
- method = "setDefault",
- args = {java.net.ProxySelector.class}
- )
- public void test_setDefaultLjava_net_ProxySelector_Security() {
- ProxySelector originalSelector = ProxySelector.getDefault();
- SecurityManager orignalSecurityManager = System.getSecurityManager();
- try {
- System.setSecurityManager(new MockSecurityManager());
- } catch (SecurityException e) {
- System.err.println("No setSecurityManager permission.");
- System.err
- .println("test_setDefaultLjava_net_ProxySelector_Security is not tested");
- return;
- }
- try {
- ProxySelector.setDefault(new MockProxySelector());
- fail("should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(orignalSecurityManager);
- ProxySelector.setDefault(originalSelector);
- }
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectExact()
- throws URISyntaxException {
- // no proxy, return a proxyList only contains NO_PROXY
- proxyList = selector.select(httpUri);
- assertProxyEquals(proxyList,Proxy.NO_PROXY);
-
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
- // set socks proxy
- System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
- System.setProperty("socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
-
- proxyList = selector.select(httpUri);
- assertProxyEquals(proxyList,Proxy.Type.HTTP,HTTP_PROXY_HOST,HTTP_PROXY_PORT);
-
- proxyList = selector.select(httpsUri);
- assertProxyEquals(proxyList,Proxy.Type.HTTP,HTTPS_PROXY_HOST,HTTPS_PROXY_PORT);
-
- proxyList = selector.select(ftpUri);
- assertProxyEquals(proxyList,Proxy.Type.HTTP,FTP_PROXY_HOST,FTP_PROXY_PORT);
-
- proxyList = selector.select(tcpUri);
- assertProxyEquals(proxyList,Proxy.Type.SOCKS,SOCKS_PROXY_HOST,SOCKS_PROXY_PORT);
-
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectExact_NullHost()
- throws URISyntaxException {
- // regression test for Harmony-1063
- httpUri = new URI("http://a@");
- ftpUri = new URI("ftp://a@");
- httpsUri = new URI("https://a@");
- tcpUri = new URI("socket://a@");
- // no proxy, return a proxyList only contains NO_PROXY
- proxyList = selector.select(httpUri);
- assertProxyEquals(proxyList, Proxy.NO_PROXY);
-
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
- // set socks proxy
- System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
- System.setProperty("socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
-
- proxyList = selector.select(httpUri);
- assertProxyEquals(proxyList, Proxy.Type.HTTP, HTTP_PROXY_HOST,
- HTTP_PROXY_PORT);
-
- proxyList = selector.select(httpsUri);
- assertProxyEquals(proxyList, Proxy.Type.HTTP, HTTPS_PROXY_HOST,
- HTTPS_PROXY_PORT);
-
- proxyList = selector.select(ftpUri);
- assertProxyEquals(proxyList, Proxy.Type.HTTP, FTP_PROXY_HOST,
- FTP_PROXY_PORT);
-
- proxyList = selector.select(tcpUri);
- assertProxyEquals(proxyList, Proxy.Type.SOCKS, SOCKS_PROXY_HOST,
- SOCKS_PROXY_PORT);
-
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectExact_DefaultPort()
- throws URISyntaxException {
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
-
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- // set socks proxy
- System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
-
- proxyList = selector.select(httpUri);
- assertProxyEquals(proxyList,Proxy.Type.HTTP,HTTP_PROXY_HOST,HTTP_PROXY_PORT);
-
- proxyList = selector.select(httpsUri);
- assertProxyEquals(proxyList,Proxy.Type.HTTP,HTTPS_PROXY_HOST,HTTPS_PROXY_PORT);
-
- proxyList = selector.select(ftpUri);
- assertProxyEquals(proxyList,Proxy.Type.HTTP,FTP_PROXY_HOST,FTP_PROXY_PORT);
-
- proxyList = selector.select(tcpUri);
- assertProxyEquals(proxyList,Proxy.Type.SOCKS,SOCKS_PROXY_HOST,SOCKS_PROXY_PORT);
-
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectExact_InvalidPort()
- throws URISyntaxException {
- final String INVALID_PORT = "abc";
-
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.proxyPort", INVALID_PORT);
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- System.setProperty("https.proxyPort", INVALID_PORT);
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.proxyPort", INVALID_PORT);
- // set socks proxy
- System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
- System.setProperty("socksproxyPort", INVALID_PORT);
-
- proxyList = selector.select(httpUri);
- assertProxyEquals(proxyList,Proxy.Type.HTTP,HTTP_PROXY_HOST,HTTP_PROXY_PORT);
-
- proxyList = selector.select(httpsUri);
- assertProxyEquals(proxyList,Proxy.Type.HTTP,HTTPS_PROXY_HOST,HTTPS_PROXY_PORT);
-
- proxyList = selector.select(ftpUri);
- assertProxyEquals(proxyList,Proxy.Type.HTTP,FTP_PROXY_HOST,FTP_PROXY_PORT);
-
- proxyList = selector.select(tcpUri);
- assertProxyEquals(proxyList,Proxy.Type.SOCKS,SOCKS_PROXY_HOST,SOCKS_PROXY_PORT);
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- // RI may fail this test case.
- // Uncomment this test case when regex.jar is ready.
- /*
- public void test_selectLjava_net_URI_Select_NonProxyHosts()
- throws URISyntaxException {
- // RI's bug. Some RIs may fail this test case.
- URI[] httpUris = { new URI("http://test.com"),
- new URI("http://10.10.1.2"), new URI("http://a"),
- new URI("http://def.abc.com") };
- URI[] ftpUris = { new URI("ftp://test.com"),
- new URI("ftp://10.10.1.2"), new URI("ftp://a"),
- new URI("ftp://def.abc.com") };
-
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.nonProxyHosts", "a|b|tes*|10.10.*|*.abc.com");
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.nonProxyHosts", "a|b|tes*|10.10.*|*.abc.com");
-
- for (int i = 0; i < httpUris.length; i++) {
- proxyList = selector.select(httpUris[i]);
- assertProxyEquals(proxyList,Proxy.NO_PROXY);
- }
-
- for (int i = 0; i < ftpUris.length; i++) {
- proxyList = selector.select(ftpUris[i]);
- assertProxyEquals(proxyList,Proxy.NO_PROXY);
- }
- }*/
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectLikeHTTP()
- throws URISyntaxException {
- System.setProperty("http.proxyHost", "");
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
- // set socks proxy
- System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
- System.setProperty("socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
-
- proxyList = selector.select(httpUri);
- assertProxyEquals(proxyList,Proxy.Type.SOCKS,SOCKS_PROXY_HOST,SOCKS_PROXY_PORT);
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectNoHTTP()
- throws URISyntaxException {
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
-
- proxyList = selector.select(httpUri);
- assertProxyEquals(proxyList,Proxy.NO_PROXY);
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectLikeHTTPS()
- throws URISyntaxException {
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
- // set https proxy host empty
- System.setProperty("http.proxyHost", "");
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
- // set socks proxy
- System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
- System.setProperty("socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
-
- proxyList = selector.select(httpsUri);
- assertProxyEquals(proxyList,Proxy.Type.SOCKS,SOCKS_PROXY_HOST,SOCKS_PROXY_PORT);
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectNoHTTPS()
- throws URISyntaxException {
- // set https proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
-
- proxyList = selector.select(httpsUri);
- assertProxyEquals(proxyList,Proxy.NO_PROXY);
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectLikeFTP()
- throws URISyntaxException {
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
- // set ftp host empty
- System.setProperty("ftp.proxyHost", "");
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
- // set socks proxy
- System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
- System.setProperty("socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
-
- proxyList = selector.select(ftpUri);
- assertProxyEquals(proxyList,Proxy.Type.SOCKS,SOCKS_PROXY_HOST,SOCKS_PROXY_PORT);
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectNoFTP()
- throws URISyntaxException {
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
-
- proxyList = selector.select(ftpUri);
- assertProxyEquals(proxyList,Proxy.NO_PROXY);
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectNoSOCKS()
- throws URISyntaxException {
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
- // set socks proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
-
- proxyList = selector.select(tcpUri);
- assertProxyEquals(proxyList,Proxy.NO_PROXY);
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for connectFailed method.",
- method = "connectFailed",
- args = {java.net.URI.class, java.net.SocketAddress.class, java.io.IOException.class}
- )
- public void test_connectionFailedLjava_net_URILjava_net_SocketAddressLjava_io_IOException()
- throws URISyntaxException {
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
- // set socks proxy
- System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
- System.setProperty("socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
-
- List proxyList1 = selector.select(httpUri);
- assertNotNull(proxyList1);
- assertEquals(1, proxyList1.size());
- Proxy proxy1 = (Proxy) proxyList1.get(0);
- selector
- .connectFailed(httpUri, proxy1.address(), new SocketException());
-
- List proxyList2 = selector.select(httpUri);
- assertNotNull(proxyList2);
- assertEquals(1, proxyList2.size());
- Proxy proxy2 = (Proxy) proxyList2.get(0);
- // Default implemention doesn't change the proxy list
- assertEquals(proxy1, proxy2);
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for connectFailed method.",
- method = "connectFailed",
- args = {java.net.URI.class, java.net.SocketAddress.class, java.io.IOException.class}
- )
- public void test_connectionFailedLjava_net_URILjava_net_SocketAddressLjava_io_IOException_IllegalArguement()
- throws URISyntaxException {
- SocketAddress sa = InetSocketAddress.createUnresolved("127.0.0.1", 0);
- try {
- selector.connectFailed(null, sa, new SocketException());
- fail("should throw IllegalArgumentException if any argument is null.");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- selector.connectFailed(httpUri, null, new SocketException());
- fail("should throw IllegalArgumentException if any argument is null.");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- selector.connectFailed(httpUri, sa, null);
- fail("should throw IllegalArgumentException if any argument is null.");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_IllegalArgument()
- throws URISyntaxException {
- URI[] illegalUris = { new URI("abc"), new URI("http"), null };
- for (int i = 0; i < illegalUris.length; i++) {
- try {
- selector.select(illegalUris[i]);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
- }
-
- /*
- * asserts whether selectedProxyList contains one and only one element,
- * and the element equals proxy.
- */
- private void assertProxyEquals(List selectedProxyList, Proxy proxy) {
- assertNotNull(selectedProxyList);
- assertEquals(1, selectedProxyList.size());
- assertEquals((Proxy) selectedProxyList.get(0), proxy);
- }
-
- /*
- * asserts whether selectedProxyList contains one and only one element,
- * and the element equals proxy which is represented by arguments "type",
- * "host","port".
- */
- private void assertProxyEquals(List selectedProxyList, Proxy.Type type,
- String host, int port) {
- SocketAddress sa = InetSocketAddress.createUnresolved(host, port);
- Proxy proxy = new Proxy(type, sa);
- assertProxyEquals(selectedProxyList, proxy);
- }
-
- /*
- * Mock selector for setDefault test
- */
- static class MockProxySelector extends ProxySelector {
-
- public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
-
- }
-
- public List <Proxy> select(URI uri) {
- return null;
- }
- }
-
- /*
- * MockSecurityMaanger. It denies NetPermission("getProxySelector") and
- * NetPermission("setProxySelector").
- */
- class MockSecurityManager extends SecurityManager {
- public void checkPermission(Permission permission) {
- if (permission instanceof NetPermission) {
- if ("getProxySelector".equals(permission.getName())) {
- throw new SecurityException();
- }
- }
-
- if (permission instanceof NetPermission) {
- if ("setProxySelector".equals(permission.getName())) {
- throw new SecurityException();
- }
- }
-
- if (permission instanceof RuntimePermission) {
- if ("setSecurityManager".equals(permission.getName())) {
- return;
- }
- }
- }
- }
-
- /*
- * @see junit.framework.TestCase#setUp()
- */
- protected void setUp() throws Exception {
- super.setUp();
- // save original system properties
- orignalSystemProperties = (Properties) System.getProperties().clone();
- }
-
- /*
- * @see junit.framework.TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- // restore orignal system properties
- System.setProperties(orignalSystemProperties);
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/ProxyTest.java b/luni/src/test/java/tests/api/java/net/ProxyTest.java
deleted file mode 100644
index eac9505..0000000
--- a/luni/src/test/java/tests/api/java/net/ProxyTest.java
+++ /dev/null
@@ -1,343 +0,0 @@
-/* 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.InetSocketAddress;
-import java.net.Proxy;
-import java.net.SocketAddress;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(Proxy.class)
-public class ProxyTest extends TestCase {
-
- private SocketAddress address = new InetSocketAddress("127.0.0.1", 1234);
-
- /**
- * @tests java.net.Proxy#Proxy(java.net.Proxy.Type, SocketAddress)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for Proxy constructor.",
- method = "Proxy",
- args = {java.net.Proxy.Type.class, java.net.SocketAddress.class}
- )
- public void test_ConstructorLjava_net_ProxyLjava_net_SocketAddress_Normal() {
- // test HTTP type proxy
- Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
- assertEquals(Proxy.Type.HTTP, proxy.type());
- assertEquals(address, proxy.address());
-
- // test SOCKS type proxy
- proxy = new Proxy(Proxy.Type.SOCKS, address);
- assertEquals(Proxy.Type.SOCKS, proxy.type());
- assertEquals(address, proxy.address());
-
- // test DIRECT type proxy
- proxy = Proxy.NO_PROXY;
- assertEquals(Proxy.Type.DIRECT, proxy.type());
- assertNull(proxy.address());
- }
-
- /**
- * @tests java.net.Proxy#Proxy(java.net.Proxy.Type, SocketAddress)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for Proxy constructor.",
- method = "Proxy",
- args = {java.net.Proxy.Type.class, java.net.SocketAddress.class}
- )
- public void test_ConstructorLjava_net_ProxyLjava_net_SocketAddress_IllegalAddress() {
- Proxy proxy = null;
- // test HTTP type proxy
- try {
- proxy = new Proxy(Proxy.Type.HTTP, null);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- // test SOCKS type proxy
- try {
- proxy = new Proxy(Proxy.Type.SOCKS, null);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- // test DIRECT type proxy
- try {
- proxy = new Proxy(Proxy.Type.DIRECT, null);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- // test DIRECT type proxy, any address is illegal
- try {
- proxy = new Proxy(Proxy.Type.DIRECT, address);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- }
-
- /**
- * @tests java.net.Proxy#hashCode()
- * @see test_equalsLjava_lang_Object_Equals
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- SocketAddress address1 = new InetSocketAddress("127.0.0.1", 1234);
-
- Proxy proxy1 = new Proxy(Proxy.Type.HTTP, address1);
- Proxy proxy2 = new Proxy(Proxy.Type.HTTP, address1);
- assertTrue(proxy1.hashCode() == proxy2.hashCode());
-
- Proxy proxy3 = new Proxy(Proxy.Type.SOCKS, address1);
- Proxy proxy4 = new Proxy(Proxy.Type.SOCKS, address1);
- assertTrue(proxy1.hashCode() == proxy2.hashCode());
-
- assertTrue(proxy1.hashCode() != proxy4.hashCode());
-
- SocketAddress address2 = new InetSocketAddress("127.0.0.1", 1235);
-
- Proxy proxy5 = new Proxy(Proxy.Type.SOCKS, address1);
- Proxy proxy6 = new Proxy(Proxy.Type.SOCKS, address2);
- assertTrue(proxy5.hashCode() != proxy6.hashCode());
- }
-
- /**
- * @tests java.net.Proxy#type()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "type",
- args = {}
- )
- public void test_type() {
-
- Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
- assertEquals(Proxy.Type.HTTP, proxy.type());
-
- proxy = new Proxy(Proxy.Type.SOCKS, address);
- assertEquals(Proxy.Type.SOCKS, proxy.type());
-
- proxy = Proxy.NO_PROXY;
- assertEquals(Proxy.Type.DIRECT, proxy.type());
- }
-
- /**
- * @tests java.net.Proxy#address() This method has been tested in
- * Constructor test case.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "address",
- args = {}
- )
- public void test_address() {
- Proxy proxy = new Proxy(Proxy.Type.SOCKS, address);
- assertEquals(address, proxy.address());
-
- try {
- new Proxy(Proxy.Type.SOCKS, null);
- fail("IllegalArgumentException was thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @tests java.net.Proxy#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
- // include type String
- assertTrue(proxy.toString().indexOf(proxy.type().toString()) != -1);
- // include address String
- assertTrue(proxy.toString().indexOf(proxy.address().toString()) != -1);
-
- proxy = new Proxy(Proxy.Type.SOCKS, address);
- // include type String
- assertTrue(proxy.toString().indexOf(proxy.type().toString()) != -1);
- // include address String
- assertTrue(proxy.toString().indexOf(proxy.address().toString()) != -1);
-
- proxy = Proxy.NO_PROXY;
- // include type String
- assertTrue(proxy.toString().indexOf(proxy.type().toString()) != -1);
-
- proxy = new Proxy(null, address);
- // ensure no NPE is thrown
- proxy.toString();
-
- }
-
- /**
- * @tests java.net.Proxy#equals(Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for equals method.",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object_Equals() {
- SocketAddress address1 = new InetSocketAddress("127.0.0.1", 1234);
- SocketAddress address2 = new InetSocketAddress("127.0.0.1", 1234);
- // HTTP type
- Proxy proxy1 = new Proxy(Proxy.Type.HTTP, address1);
- Proxy proxy2 = new Proxy(Proxy.Type.HTTP, address2);
- assertTrue(proxy1.equals(proxy2));
- // assert hashCode
- assertTrue(proxy1.hashCode() == proxy2.hashCode());
-
- // SOCKS type
- Proxy proxy3 = new Proxy(Proxy.Type.SOCKS, address1);
- Proxy proxy4 = new Proxy(Proxy.Type.SOCKS, address2);
- assertTrue(proxy3.equals(proxy4));
- // assert hashCode
- assertTrue(proxy3.hashCode() == proxy4.hashCode());
-
- // null type
- Proxy proxy5 = new Proxy(null, address1);
- Proxy proxy6 = new Proxy(null, address2);
- assertTrue(proxy5.equals(proxy6));
- }
-
- /**
- * @tests java.net.Proxy#equals(Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for equals method.",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object_NotEquals() {
- SocketAddress address1 = new InetSocketAddress("127.0.0.1", 1234);
- SocketAddress address2 = new InetSocketAddress("127.0.0.1", 1235);
- Proxy proxy[] = { new Proxy(Proxy.Type.HTTP, address1),
- new Proxy(Proxy.Type.HTTP, address2),
- new Proxy(Proxy.Type.SOCKS, address1),
- new Proxy(Proxy.Type.SOCKS, address2), Proxy.NO_PROXY,
- new Proxy(null, address1), new Proxy(null, address2) };
- // All of them are not equals
- for (int i = 0; i < proxy.length; i++) {
- for (int j = i + 1; j < proxy.length; j++) {
- assertFalse(proxy[i].equals(proxy[j]));
- }
- }
- // Not equals to an Object type instance. Ensure no exception is thrown.
- assertFalse(proxy[0].equals(new Object()));
- }
-
- /**
- * @tests java.net.Proxy.Type#valueOf(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Proxy.Type.DIRECT, Proxy.Type.HTTP, Proxy.Type.SOCKS",
- method = "!Constants",
- args = {}
- )
- public void test_Type_valueOfLjava_lang_String_Normal() {
- assertEquals(Proxy.Type.DIRECT, Proxy.Type.valueOf("DIRECT"));
- assertEquals(Proxy.Type.HTTP, Proxy.Type.valueOf("HTTP"));
- assertEquals(Proxy.Type.SOCKS, Proxy.Type.valueOf("SOCKS"));
- }
-
- /**
- * @tests java.net.Proxy.Type#valueOf(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!Constants",
- args = {}
- )
- public void test_Type_valueOfLjava_lang_String_IllegalName() {
- String[] illegalName = { "Direct", "direct", "http", "socks",
- "illegalName", "" };
- for (int i = 0; i < illegalName.length; i++) {
- try {
- Proxy.Type.valueOf(illegalName[i]);
- fail("should throw IllegalArgumentException, illegalName:"
- + illegalName);
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
- }
-
- /**
- * @tests java.net.Proxy.Type#valueOf(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!Constants",
- args = {}
- )
- public void test_Type_valueOfLjava_lang_String_NullPointerException() {
- // Some old RIs,which throw IllegalArgumentException.
- // Latest RIs throw NullPointerException.
- try {
- Proxy.Type.valueOf(null);
- fail("should throw an exception.");
- } catch (NullPointerException e) {
- // May be caused by some compilers' code
- } catch (IllegalArgumentException e) {
- // other compilers will throw this
- }
- }
-
- /**
- * @tests java.net.Proxy.Type#values()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!Constants",
- args = {}
- )
- public void test_Type_values() {
- Proxy.Type types[] = Proxy.Type.values();
- assertEquals(3, types.length);
- assertEquals(Proxy.Type.DIRECT, types[0]);
- assertEquals(Proxy.Type.HTTP, types[1]);
- assertEquals(Proxy.Type.SOCKS, types[2]);
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/net/ProxyTypeTest.java b/luni/src/test/java/tests/api/java/net/ProxyTypeTest.java
deleted file mode 100644
index 4ce7b89..0000000
--- a/luni/src/test/java/tests/api/java/net/ProxyTypeTest.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.net.Proxy;
-
-@TestTargetClass(Proxy.Type.class)
-public class ProxyTypeTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {java.lang.String.class}
- )
- public void test_valueOf() {
- Proxy.Type [] types = {Proxy.Type.DIRECT, Proxy.Type.HTTP,
- Proxy.Type.SOCKS};
-
- String [] strTypes = {"DIRECT", "HTTP", "SOCKS"};
-
- for(int i = 0; i < strTypes.length; i++) {
- assertEquals(types[i], Proxy.Type.valueOf(strTypes[i]));
- }
-
- String [] incTypes = {"", "direct", "http", "socks", " HTTP"};
-
- for(String str:incTypes) {
- try {
- Proxy.Type.valueOf(str);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- try {
- Proxy.Type.valueOf(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
- public void test_values() {
- Proxy.Type [] types = { Proxy.Type.DIRECT, Proxy.Type.HTTP,
- Proxy.Type.SOCKS };
-
- Proxy.Type [] result = Proxy.Type.values();
-
- assertEquals(types.length, result.length);
-
- for(int i = 0; i < result.length; i++) {
- assertEquals(types[i], result[i]);
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/ResponseCacheTest.java b/luni/src/test/java/tests/api/java/net/ResponseCacheTest.java
deleted file mode 100644
index 449fbba..0000000
--- a/luni/src/test/java/tests/api/java/net/ResponseCacheTest.java
+++ /dev/null
@@ -1,300 +0,0 @@
-/* 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 tests.api.java.net;
-
-import dalvik.annotation.BrokenTest;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.OutputStream;
-import java.net.CacheRequest;
-import java.net.CacheResponse;
-import java.net.HttpURLConnection;
-import java.net.NetPermission;
-import java.net.ResponseCache;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.net.URLConnection;
-import java.security.Permission;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import junit.framework.TestCase;
-
-import tests.support.Support_Configuration;
-
-@TestTargetClass(
- value = ResponseCache.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "put method is not tested completely",
- method = "put",
- args = {java.net.URI.class, java.net.URLConnection.class}
- )
- }
-)
-public class ResponseCacheTest extends TestCase {
-
-
-
- /**
- * @tests java.net.ResponseCache#getDefault()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for getDefault method.",
- method = "getDefault",
- args = {}
- )
- public void test_GetDefault() throws Exception {
- assertNull(ResponseCache.getDefault());
- }
-
- /**
- * @tests java.net.ResponseCache#setDefault(ResponseCache)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "This is a complete subset of tests for setDefault method.",
- method = "setDefault",
- args = {java.net.ResponseCache.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "This is a complete subset of tests for setDefault method.",
- method = "ResponseCache",
- args = {}
- )
- })
- public void test_SetDefaultLjava_net_ResponseCache_Normal()
- throws Exception {
- ResponseCache rc1 = new MockResponseCache();
- ResponseCache rc2 = new MockResponseCache();
- ResponseCache.setDefault(rc1);
- assertSame(ResponseCache.getDefault(), rc1);
- ResponseCache.setDefault(rc2);
- assertSame(ResponseCache.getDefault(), rc2);
- ResponseCache.setDefault(null);
- assertNull(ResponseCache.getDefault());
- }
-
- /**
- * @tests java.net.ResponseCache#getDefault()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for getDefault method.",
- method = "getDefault",
- args = {}
- )
- public void test_GetDefault_Security() {
- SecurityManager old = System.getSecurityManager();
- try {
- System.setSecurityManager(new MockSM());
- } catch (SecurityException e) {
- System.err.println("No setSecurityManager permission.");
- System.err.println("test_setDefaultLjava_net_ResponseCache_NoPermission is not tested");
- return;
- }
- try {
- ResponseCache.getDefault();
- fail("should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(old);
- }
- }
-
- /**
- * @tests java.net.ResponseCache#setDefault(ResponseCache)
- */
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- notes = "This is a complete subset of tests for setDefault method.",
- method = "setDefault",
- args = {java.net.ResponseCache.class}
- )
- public void test_setDefaultLjava_net_ResponseCache_NoPermission() {
- ResponseCache rc = new MockResponseCache();
- SecurityManager old = System.getSecurityManager();
- try {
- System.setSecurityManager(new MockSM());
- } catch (SecurityException e) {
- System.err.println("No setSecurityManager permission.");
- System.err.println("test_setDefaultLjava_net_ResponseCache_NoPermission is not tested");
- return;
- }
- try {
- ResponseCache.setDefault(rc);
- fail("should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(old);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {java.net.URI.class, java.lang.String.class, java.util.Map.class}
- )
- @BrokenTest("cache seems not to be used")
- public void test_get_put() throws Exception {
-
- URL url = new URL("http://" +
- Support_Configuration.SpecialInetTestAddress);
- ResponseCache.setDefault(new TestResponseCache());
- HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
- httpCon.setUseCaches(true);
- httpCon.connect();
- try {
- Thread.sleep(5000);
- } catch(Exception e) {}
-
- InputStream is = httpCon.getInputStream();
- byte [] array = new byte [10];
- is.read(array);
- assertEquals("Cache test", new String(array));
-
- try {
- Thread.sleep(5000);
- } catch(Exception e) {}
- is.close();
- httpCon.disconnect();
- }
-
- /*
- * MockResponseCache for testSetDefault(ResponseCache)
- */
- class MockResponseCache extends ResponseCache {
-
- public CacheResponse get(URI arg0, String arg1, Map arg2)
- throws IOException {
- return null;
- }
-
- public CacheRequest put(URI arg0, URLConnection arg1)
- throws IOException {
- return null;
- }
- }
-
- /*
- * MockSecurityMaanger. It denies NetPermission("getResponseCache") and
- * NetPermission("setResponseCache").
- */
- class MockSM extends SecurityManager {
- public void checkPermission(Permission permission) {
- if (permission instanceof NetPermission) {
- if ("setResponseCache".equals(permission.getName())) {
- throw new SecurityException();
- }
- }
-
- if (permission instanceof NetPermission) {
- if ("getResponseCache".equals(permission.getName())) {
-
- throw new SecurityException();
- }
- }
-
- if (permission instanceof RuntimePermission) {
- if ("setSecurityManager".equals(permission.getName())) {
- return;
- }
- }
- }
- }
-
- class TestCacheResponse extends CacheResponse {
- InputStream is = null;
- Map<String, List<String>> headers = null;
-
- public TestCacheResponse(String filename) {
- String path = getClass().getPackage().getName().replace(".", "/");
- is = getClass().getResourceAsStream("/" + path + "/" + filename);
- }
-
- public InputStream getBody() throws IOException {
- return is;
- }
-
- public Map getHeaders() throws IOException {
- return null;
- }
- }
-
- class TestCacheRequest extends CacheRequest {
-
- public TestCacheRequest(String filename,
- Map<String, List<String>> rspHeaders) {
- }
- public OutputStream getBody() throws IOException {
- return null;
- }
-
- public void abort() {
- }
- }
-
- class TestResponseCache extends ResponseCache {
-
- URI uri1 = null;
-
- public CacheResponse get(URI uri, String rqstMethod, Map rqstHeaders)
- throws IOException {
- try {
- uri1 = new URI("http://" +
- Support_Configuration.SpecialInetTestAddress);
- } catch (URISyntaxException e) {
- }
- if (uri.equals(uri1)) {
- return new TestCacheResponse("file1.cache");
- }
- return null;
- }
-
- public CacheRequest put(URI uri, URLConnection conn)
- throws IOException {
- try {
- uri1 = new URI("http://www.google.com");
- } catch (URISyntaxException e) {
- }
- if (uri.equals(uri1)) {
- return new TestCacheRequest("file2.cache",
- conn.getHeaderFields());
- }
- return null;
- }
- }
-} \ No newline at end of file
diff --git a/luni/src/test/java/tests/api/java/net/SecureCacheResponseTest.java b/luni/src/test/java/tests/api/java/net/SecureCacheResponseTest.java
deleted file mode 100644
index 2fcad76..0000000
--- a/luni/src/test/java/tests/api/java/net/SecureCacheResponseTest.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import tests.api.java.net.ResponseCacheTest.TestCacheRequest;
-import tests.api.java.net.ResponseCacheTest.TestCacheResponse;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.CacheRequest;
-import java.net.CacheResponse;
-import java.net.HttpURLConnection;
-import java.net.ResponseCache;
-import java.net.SecureCacheResponse;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.net.URLConnection;
-import java.security.Principal;
-import java.security.cert.Certificate;
-import java.util.List;
-import java.util.Map;
-
-import javax.net.ssl.SSLPeerUnverifiedException;
-
-@TestTargetClass(SecureCacheResponse.class)
-public class SecureCacheResponseTest extends TestCase {
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SecureCacheResponse",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCipherSuite",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalCertificateChain",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalPrincipal",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPeerPrincipal",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getServerCertificateChain",
- args = {}
- )
- })
- public void test_Constructor() throws Exception {
- TestSecureCacheResponse scr = new TestSecureCacheResponse();
- assertNull(scr.getCipherSuite());
- assertNull(scr.getLocalCertificateChain());
- assertNull(scr.getLocalPrincipal());
- assertNull(scr.getPeerPrincipal());
- assertNull(scr.getServerCertificateChain());
- assertNull(scr.getBody());
- assertNull(scr.getHeaders());
- }
-
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- notes = "",
- method = "SecureCacheResponse",
- args = {}
- )
- public void test_additional() throws Exception {
-
- URL url = new URL("http://google.com");
- ResponseCache.setDefault(new TestResponseCache());
- HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
- httpCon.setUseCaches(true);
- httpCon.connect();
- try {
- Thread.sleep(5000);
- } catch(Exception e) {}
- httpCon.disconnect();
-
- }
-
- class TestSecureCacheResponse extends SecureCacheResponse {
-
- @Override
- public String getCipherSuite() {
- return null;
- }
-
- @Override
- public List<Certificate> getLocalCertificateChain() {
- return null;
- }
-
- @Override
- public Principal getLocalPrincipal() {
- return null;
- }
-
- @Override
- public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
- return null;
- }
-
- @Override
- public List<Certificate> getServerCertificateChain() throws SSLPeerUnverifiedException {
- return null;
- }
-
- @Override
- public InputStream getBody() throws IOException {
- return null;
- }
-
- @Override
- public Map<String, List<String>> getHeaders() throws IOException {
- return null;
- }
-
- }
-
- class TestResponseCache extends ResponseCache {
-
- URI uri1 = null;
-
- public TestSecureCacheResponse get(URI uri, String rqstMethod, Map rqstHeaders)
- throws IOException {
-
-
- try {
- uri1 = new URI("http://google.com");
- } catch (URISyntaxException e) {
- }
- if (uri.equals(uri)) {
- return new TestSecureCacheResponse();
- }
- return null;
- }
-
- public CacheRequest put(URI uri, URLConnection conn)
- throws IOException {
- return null;
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/ServerSocketTest.java b/luni/src/test/java/tests/api/java/net/ServerSocketTest.java
deleted file mode 100644
index 36e092d..0000000
--- a/luni/src/test/java/tests/api/java/net/ServerSocketTest.java
+++ /dev/null
@@ -1,1504 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InterruptedIOException;
-import java.io.OutputStream;
-import java.net.BindException;
-import java.net.ConnectException;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.net.SocketImpl;
-import java.net.SocketImplFactory;
-import java.net.SocketTimeoutException;
-import java.net.UnknownHostException;
-import java.nio.channels.IllegalBlockingModeException;
-import java.nio.channels.ServerSocketChannel;
-import java.security.Permission;
-import java.util.Date;
-import java.util.Properties;
-
-import tests.support.Support_Configuration;
-import tests.support.Support_PortManager;
-
-@TestTargetClass(value = ServerSocket.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_NECESSARY,
- notes = "Protected constructor.",
- method = "ServerSocket",
- args = {SocketImpl.class}
- )}
- )
-public class ServerSocketTest extends SocketTestCase {
-
- boolean interrupted;
- boolean isCreateCalled = false;
-
- ServerSocket s;
-
- Socket sconn;
-
- Thread t;
-
- static class SSClient implements Runnable {
- Socket cs;
-
- int port;
-
- public SSClient(int prt) {
- port = prt;
- }
-
- public void run() {
- try {
- // Go to sleep so the server can setup and wait for connection
- Thread.sleep(1000);
- cs = new Socket(InetAddress.getLocalHost().getHostName(), port);
- // Sleep again to allow server side processing. Thread is
- // stopped by server.
- Thread.sleep(10000);
- } catch (InterruptedException e) {
- return;
- } catch (Throwable e) {
- System.out
- .println("Error establishing client: " + e.toString());
- } finally {
- try {
- if (cs != null)
- cs.close();
- } catch (Exception e) {
- }
- }
- }
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkListen(int port) {
- throw new SecurityException();
- }
- };
-
- /**
- * @tests java.net.ServerSocket#ServerSocket()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ServerSocket",
- args = {}
- )
- public void test_Constructor() {
- ServerSocket ss = null;
- try {
- ss = new ServerSocket();
- assertEquals(-1, ss.getLocalPort());
- } catch (IOException e) {
- fail("IOException was thrown.");
- } finally {
- try {
- ss.close();
- } catch(IOException ioe) {}
- }
- }
-
- /**
- * @tests java.net.ServerSocket#ServerSocket(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ServerSocket",
- args = {int.class}
- )
- public void test_ConstructorI() throws Exception {
- int portNumber = Support_PortManager.getNextPort();
- s = new ServerSocket(portNumber);
- try {
- new ServerSocket(portNumber);
- fail("IOException was not thrown.");
- } catch(IOException ioe) {
- //expected
- }
- try {
- startClient(s.getLocalPort());
- sconn = s.accept();
- assertNotNull("Was unable to accept connection", sconn);
- sconn.close();
- } finally {
- s.close();
- }
-
- s = new ServerSocket(0);
- try {
- startClient(s.getLocalPort());
- sconn = s.accept();
- assertNotNull("Was unable to accept connection", sconn);
- sconn.close();
- } finally {
- s.close();
- }
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new ServerSocket(0);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.net.ServerSocket#ServerSocket(int)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Regression test.",
- method = "ServerSocket",
- args = {int.class}
- )
- public void test_ConstructorI_SocksSet() throws IOException {
- // Harmony-623 regression test
- ServerSocket ss = null;
- Properties props = (Properties) System.getProperties().clone();
- try {
- System.setProperty("socksProxyHost", "127.0.0.1");
- System.setProperty("socksProxyPort", "12345");
- ss = new ServerSocket(0);
- } finally {
- System.setProperties(props);
- if (null != ss) {
- ss.close();
- }
- }
- }
-
- /**
- * @tests java.net.ServerSocket#ServerSocket(int, int)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Doesn't check backlog.",
- method = "ServerSocket",
- args = {int.class, int.class}
- )
- public void test_ConstructorII() throws IOException {
- int freePortNumber = Support_PortManager.getNextPort();
- try {
- s = new ServerSocket(freePortNumber, 1);
- s.setSoTimeout(2000);
- startClient(freePortNumber);
- sconn = s.accept();
-
- } catch (InterruptedIOException e) {
- fail("InterruptedIOException was thrown.");
- } finally {
- try {
- sconn.close();
- s.close();
- } catch(IOException ioe) {}
- }
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new ServerSocket(0, 0);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- int portNumber = Support_PortManager.getNextPort();
- new ServerSocket(portNumber, 0);
- try {
- new ServerSocket(portNumber, 0);
- fail("IOExcepion was not thrown.");
- } catch(IOException ioe) {
- //expected
- }
- }
-
- /**
- * @tests java.net.ServerSocket#ServerSocket(int, int, java.net.InetAddress)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Doesn't check backlog value.",
- method = "ServerSocket",
- args = {int.class, int.class, java.net.InetAddress.class}
- )
- public void test_ConstructorIILjava_net_InetAddress()
- throws UnknownHostException, IOException {
- s = new ServerSocket(0, 10, InetAddress.getLocalHost());
- try {
- s.setSoTimeout(5000);
- startClient(s.getLocalPort());
- sconn = s.accept();
- assertNotNull("Was unable to accept connection", sconn);
- sconn.close();
- } finally {
- s.close();
- }
-
- int freePortNumber = Support_PortManager.getNextPort();
- ServerSocket ss = new ServerSocket(freePortNumber, 10,
- InetAddress.getLocalHost());
-
- try {
- new ServerSocket(freePortNumber, 10,
- InetAddress.getLocalHost());
- fail("IOException was not thrown.");
- } catch(IOException ioe) {
- //expected
- }
-
- try {
- new ServerSocket(65536, 10,
- InetAddress.getLocalHost());
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new ServerSocket(0, 10, InetAddress.getLocalHost());
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- int portNumber = Support_PortManager.getNextPort();
- new ServerSocket(portNumber, 0);
- try {
- new ServerSocket(portNumber, 0);
- fail("IOExcepion was not thrown.");
- } catch(IOException ioe) {
- //expected
- }
- }
-
- /**
- * @tests java.net.ServerSocket#accept()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException is not checked.",
- method = "accept",
- args = {}
- )
- public void test_accept() throws IOException {
- s = new ServerSocket(0);
- try {
- s.setSoTimeout(5000);
- startClient(s.getLocalPort());
- sconn = s.accept();
- int localPort1 = s.getLocalPort();
- int localPort2 = sconn.getLocalPort();
- sconn.close();
- assertEquals("Bad local port value", localPort1, localPort2);
- } finally {
- s.close();
- }
-
- try {
- interrupted = false;
- final ServerSocket ss = new ServerSocket(0);
- ss.setSoTimeout(12000);
- Runnable runnable = new Runnable() {
- public void run() {
- try {
- ss.accept();
- } catch (InterruptedIOException e) {
- interrupted = true;
- } catch (IOException e) {
- }
- }
- };
- Thread thread = new Thread(runnable, "ServerSocket.accept");
- thread.start();
- try {
- do {
- Thread.sleep(500);
- } while (!thread.isAlive());
- } catch (InterruptedException e) {
- }
- ss.close();
- int c = 0;
- do {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- }
- if (interrupted) {
- fail("accept interrupted");
- }
- if (++c > 4) {
- fail("accept call did not exit");
- }
- } while (thread.isAlive());
-
- interrupted = false;
- ServerSocket ss2 = new ServerSocket(0);
- ss2.setSoTimeout(500);
- Date start = new Date();
- try {
- ss2.accept();
- } catch (InterruptedIOException e) {
- interrupted = true;
- }
- assertTrue("accept not interrupted", interrupted);
- Date finish = new Date();
- int delay = (int) (finish.getTime() - start.getTime());
- assertTrue("timeout too soon: " + delay + " " + start.getTime()
- + " " + finish.getTime(), delay >= 490);
- ss2.close();
- } catch (IOException e) {
- fail("Unexpected IOException : " + e.getMessage());
- }
-
- int portNumber = Support_PortManager.getNextPort();
- ServerSocket serSocket = new ServerSocket(portNumber);
- startClient(portNumber);
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkAccept(String host,
- int port) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- serSocket.accept();
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- serSocket.close();
- }
-
- ServerSocket newSocket = new ServerSocket(portNumber);
- newSocket.setSoTimeout(500);
-
- try {
- newSocket.accept();
- fail("SocketTimeoutException was not thrown.");
- } catch(SocketTimeoutException ste) {
- //expected
- } finally {
- newSocket.close();
- }
-
- ServerSocketChannel ssc = ServerSocketChannel.open();
- ServerSocket ss = ssc.socket();
-
- try {
- ss.accept();
- fail("IllegalBlockingModeException was not thrown.");
- } catch(IllegalBlockingModeException ibme) {
- //expected
- } finally {
- ss.close();
- ssc.close();
- }
- }
-
- /**
- * @tests java.net.ServerSocket#close()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException checking missed.",
- method = "close",
- args = {}
- )
- public void test_close() throws IOException {
- try {
- s = new ServerSocket(0);
- try {
- s.close();
- s.accept();
- fail("Close test failed");
- } catch (SocketException e) {
- // expected;
- }
- } finally {
- s.close();
- }
- }
-
- /**
- * @tests java.net.ServerSocket#getInetAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInetAddress",
- args = {}
- )
- public void test_getInetAddress() throws IOException {
- InetAddress addr = InetAddress.getLocalHost();
- s = new ServerSocket(0, 10, addr);
- try {
- assertEquals("Returned incorrect InetAdrees", addr, s
- .getInetAddress());
- } finally {
- s.close();
- }
- }
-
- /**
- * @tests java.net.ServerSocket#getLocalPort()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getLocalPort",
- args = {}
- )
- public void test_getLocalPort() throws IOException {
- // Try a specific port number, but don't complain if we don't get it
- int portNumber = 63024; // I made this up
- try {
- try {
- s = new ServerSocket(portNumber);
- } catch (BindException e) {
- // we could not get the port, give up
- return;
- }
- assertEquals("Returned incorrect port", portNumber, s
- .getLocalPort());
- } finally {
- s.close();
- }
- }
-
- /**
- * @tests java.net.ServerSocket#getSoTimeout()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSoTimeout",
- args = {}
- )
- public void test_getSoTimeout() throws IOException {
- s = new ServerSocket(0);
- try {
- s.setSoTimeout(100);
- assertEquals("Returned incorrect sotimeout", 100, s.getSoTimeout());
- } finally {
- s.close();
- }
- try {
- ServerSocket newSocket = new ServerSocket();
- newSocket.close();
- try {
- newSocket.setSoTimeout(100);
- fail("SocketException was not thrown.");
- } catch(SocketException e) {
- //expected
- }
- } catch(Exception e) {
- fail("Unexpected exception.");
- }
- }
-
- /**
- * @tests java.net.ServerSocket#setSoTimeout(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setSoTimeout",
- args = {int.class}
- )
- public void test_setSoTimeoutI() throws IOException {
- // Timeout should trigger and throw InterruptedIOException
- try {
- s = new ServerSocket(0);
- s.setSoTimeout(100);
- s.accept();
- } catch (InterruptedIOException e) {
- try {
- assertEquals("Set incorrect sotimeout", 100, s.getSoTimeout());
- return;
- } catch (Exception x) {
- fail("Exception during setSOTimeout: " + e.toString());
- }
- } catch (IOException iox) {
- fail("IOException during setSotimeout: " + iox.toString());
- }
-
- // Timeout should not trigger in this case
- s = new ServerSocket(0);
- startClient(s.getLocalPort());
- s.setSoTimeout(10000);
- sconn = s.accept();
-
- ServerSocket newSocket = new ServerSocket();
- newSocket.close();
- try {
- newSocket.setSoTimeout(100);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- /**
- * @tests java.net.ServerSocket#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() throws Exception {
- s = new ServerSocket(0);
- try {
- int portNumber = s.getLocalPort();
- assertTrue(s.toString().contains("" + portNumber));
- } finally {
- try {
- s.close();
- } catch(Exception e) {
-
- }
- }
- }
-
- /**
- * @tests java.net.ServerSocket#bind(java.net.SocketAddress)
- */
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "bind",
- args = {java.net.SocketAddress.class}
- )
- public void test_bindLjava_net_SocketAddress() throws IOException {
- class mySocketAddress extends SocketAddress {
- public mySocketAddress() {
- }
- }
- // create servers socket, bind it and then validate basic state
- ServerSocket theSocket = new ServerSocket();
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), 0);
- theSocket.bind(theAddress);
- int portNumber = theSocket.getLocalPort();
- assertTrue(
- "Returned incorrect InetSocketAddress(2):"
- + theSocket.getLocalSocketAddress().toString()
- + "Expected: "
- + (new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)).toString(), theSocket
- .getLocalSocketAddress().equals(
- new InetSocketAddress(InetAddress
- .getLocalHost(), portNumber)));
- assertTrue("Server socket not bound when it should be:", theSocket
- .isBound());
-
- // now make sure that it is actually bound and listening on the
- // address we provided
- Socket clientSocket = new Socket();
- InetSocketAddress clAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), portNumber);
- clientSocket.connect(clAddress);
- Socket servSock = theSocket.accept();
-
- assertEquals(clAddress, clientSocket.getRemoteSocketAddress());
- theSocket.close();
- servSock.close();
- clientSocket.close();
-
- // validate we can specify null for the address in the bind and all
- // goes ok
- theSocket = new ServerSocket();
- theSocket.bind(null);
- theSocket.close();
-
- // Address that we have already bound to
- theSocket = new ServerSocket();
- ServerSocket theSocket2 = new ServerSocket();
- try {
- theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
- theSocket.bind(theAddress);
- SocketAddress localAddress = theSocket.getLocalSocketAddress();
- theSocket2.bind(localAddress);
- fail("No exception binding to address that is not available");
- } catch (IOException ex) {
- }
- theSocket.close();
- theSocket2.close();
-
- // validate we get io address when we try to bind to address we
- // cannot bind to
- theSocket = new ServerSocket();
- try {
- theSocket.bind(new InetSocketAddress(InetAddress
- .getByAddress(Support_Configuration.nonLocalAddressBytes),
- 0));
- fail("No exception was thrown when binding to bad address");
- } catch (IOException ex) {
- }
- theSocket.close();
-
- // now validate case where we pass in an unsupported subclass of
- // SocketAddress
- theSocket = new ServerSocket();
- try {
- theSocket.bind(new mySocketAddress());
- fail("No exception when binding using unsupported SocketAddress subclass");
- } catch (IllegalArgumentException ex) {
- }
- theSocket.close();
-
-
- ServerSocket serSocket = new ServerSocket();
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- serSocket.bind(theAddress);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- serSocket.close();
- }
- }
-
- /**
- * @tests java.net.ServerSocket#bind(java.net.SocketAddress,int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "bind",
- args = {java.net.SocketAddress.class, int.class}
- )
- public void test_bindLjava_net_SocketAddressI() throws IOException {
- class mySocketAddress extends SocketAddress {
-
- public mySocketAddress() {
- }
- }
-
- // create servers socket, bind it and then validate basic state
- ServerSocket theSocket = new ServerSocket();
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), 0);
- theSocket.bind(theAddress, 5);
- int portNumber = theSocket.getLocalPort();
- assertTrue(
- "Returned incorrect InetSocketAddress(2):"
- + theSocket.getLocalSocketAddress().toString()
- + "Expected: "
- + (new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)).toString(), theSocket
- .getLocalSocketAddress().equals(
- new InetSocketAddress(InetAddress
- .getLocalHost(), portNumber)));
- assertTrue("Server socket not bound when it should be:", theSocket
- .isBound());
-
- // now make sure that it is actually bound and listening on the
- // address we provided
- SocketAddress localAddress = theSocket.getLocalSocketAddress();
- Socket clientSocket = new Socket();
- clientSocket.connect(localAddress);
- Socket servSock = theSocket.accept();
-
- assertTrue(clientSocket.getRemoteSocketAddress().equals(localAddress));
- theSocket.close();
- servSock.close();
- clientSocket.close();
-
- // validate we can specify null for the address in the bind and all
- // goes ok
- theSocket = new ServerSocket();
- theSocket.bind(null, 5);
- theSocket.close();
-
- // Address that we have already bound to
- theSocket = new ServerSocket();
- ServerSocket theSocket2 = new ServerSocket();
- try {
- theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
- theSocket.bind(theAddress, 5);
- SocketAddress inuseAddress = theSocket.getLocalSocketAddress();
- theSocket2.bind(inuseAddress, 5);
- fail("No exception binding to address that is not available");
- } catch (IOException ex) {
- // expected
- }
- theSocket.close();
- theSocket2.close();
-
- // validate we get ioException when we try to bind to address we
- // cannot bind to
- theSocket = new ServerSocket();
- try {
- theSocket.bind(new InetSocketAddress(InetAddress
- .getByAddress(Support_Configuration.nonLocalAddressBytes),
- 0), 5);
- fail("No exception was thrown when binding to bad address");
- } catch (IOException ex) {
- }
- theSocket.close();
-
- // now validate case where we pass in an unsupported subclass of
- // SocketAddress
- theSocket = new ServerSocket();
- try {
- theSocket.bind(new mySocketAddress(), 5);
- fail("Binding using unsupported SocketAddress subclass should have thrown exception");
- } catch (IllegalArgumentException ex) {
- }
- theSocket.close();
-
- // now validate that backlog is respected. We have to do a test that
- // checks if it is a least a certain number as some platforms make
- // it higher than we request. Unfortunately non-server versions of
- // windows artificially limit the backlog to 5 and 5 is the
- // historical default so it it not a great test.
- theSocket = new ServerSocket();
- theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
- theSocket.bind(theAddress, 4);
- localAddress = theSocket.getLocalSocketAddress();
- Socket theSockets[] = new Socket[4];
- int i = 0;
- try {
- for (i = 0; i < 4; i++) {
- theSockets[i] = new Socket();
- theSockets[i].connect(localAddress);
- }
- } catch (ConnectException ex) {
- fail("Backlog does not seem to be respected in bind:" + i + ":"
- + ex.toString());
- }
-
- for (i = 0; i < 4; i++) {
- theSockets[i].close();
- }
-
- theSocket.close();
- servSock.close();
-
- ServerSocket serSocket = new ServerSocket();
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- serSocket.bind(theAddress, 5);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- serSocket.close();
- }
- }
-
- /**
- * @tests java.net.ServerSocket#getLocalSocketAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalSocketAddress",
- args = {}
- )
- public void test_getLocalSocketAddress() {
- // set up server connect and then validate that we get the right
- // response for the local address
- try {
- ServerSocket theSocket = new ServerSocket(0, 5, InetAddress
- .getLocalHost());
- int portNumber = theSocket.getLocalPort();
- assertTrue("Returned incorrect InetSocketAddress(1):"
- + theSocket.getLocalSocketAddress().toString()
- + "Expected: "
- + (new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)).toString(), theSocket
- .getLocalSocketAddress().equals(
- new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)));
- theSocket.close();
-
- // now create a socket that is not bound and validate we get the
- // right answer
- theSocket = new ServerSocket();
- assertNull(
- "Returned incorrect InetSocketAddress -unbound socket- Expected null",
- theSocket.getLocalSocketAddress());
-
- // now bind the socket and make sure we get the right answer
- theSocket
- .bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
- int localPort = theSocket.getLocalPort();
- assertEquals("Returned incorrect InetSocketAddress(2):", theSocket
- .getLocalSocketAddress(), new InetSocketAddress(InetAddress
- .getLocalHost(), localPort));
- theSocket.close();
- } catch (Exception e) {
- fail("Exception during getLocalSocketAddress test: " + e);
- }
- }
-
- /**
- * @tests java.net.ServerSocket#isBound()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isBound",
- args = {}
- )
- public void test_isBound() throws IOException {
- InetAddress addr = InetAddress.getLocalHost();
- ServerSocket serverSocket = new ServerSocket();
- assertFalse("Socket indicated bound when it should be (1)",
- serverSocket.isBound());
-
- // now bind and validate bound ok
- serverSocket.bind(new InetSocketAddress(addr, 0));
- assertTrue("Socket indicated not bound when it should be (1)",
- serverSocket.isBound());
- serverSocket.close();
-
- // now do with some of the other constructors
- serverSocket = new ServerSocket(0);
- assertTrue("Socket indicated not bound when it should be (2)",
- serverSocket.isBound());
- serverSocket.close();
-
- serverSocket = new ServerSocket(0, 5, addr);
- assertTrue("Socket indicated not bound when it should be (3)",
- serverSocket.isBound());
- serverSocket.close();
-
- serverSocket = new ServerSocket(0, 5);
- assertTrue("Socket indicated not bound when it should be (4)",
- serverSocket.isBound());
- serverSocket.close();
- }
-
- /**
- * @tests java.net.ServerSocket#isClosed()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isClosed",
- args = {}
- )
- public void test_isClosed() throws IOException {
- InetAddress addr = InetAddress.getLocalHost();
- ServerSocket serverSocket = new ServerSocket(0, 5, addr);
-
- // validate isClosed returns expected values
- assertFalse("Socket should indicate it is not closed(1):", serverSocket
- .isClosed());
- serverSocket.close();
- assertTrue("Socket should indicate it is closed(1):", serverSocket
- .isClosed());
-
- // now do with some of the other constructors
- serverSocket = new ServerSocket(0);
- assertFalse("Socket should indicate it is not closed(1):", serverSocket
- .isClosed());
- serverSocket.close();
- assertTrue("Socket should indicate it is closed(1):", serverSocket
- .isClosed());
-
- serverSocket = new ServerSocket(0, 5, addr);
- assertFalse("Socket should indicate it is not closed(1):", serverSocket
- .isClosed());
- serverSocket.close();
- assertTrue("Socket should indicate it is closed(1):", serverSocket
- .isClosed());
-
- serverSocket = new ServerSocket(0, 5);
- assertFalse("Socket should indicate it is not closed(1):", serverSocket
- .isClosed());
- serverSocket.close();
- assertTrue("Socket should indicate it is closed(1):", serverSocket
- .isClosed());
- }
-
- /**
- * @tests java.net.ServerSocket#setReuseAddress(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setReuseAddress",
- args = {boolean.class}
- )
- public void test_setReuseAddressZ() {
- try {
- // set up server and connect
- InetSocketAddress anyAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), 0);
- ServerSocket serverSocket = new ServerSocket();
- serverSocket.setReuseAddress(false);
- serverSocket.bind(anyAddress);
- SocketAddress theAddress = serverSocket.getLocalSocketAddress();
-
- // make a connection to the server, then close the server
- Socket theSocket = new Socket();
- theSocket.connect(theAddress);
- Socket stillActiveSocket = serverSocket.accept();
- serverSocket.close();
-
- // now try to rebind the server which should fail with
- // setReuseAddress to false. On windows platforms the bind is
- // allowed even then reUseAddress is false so our test uses
- // the platform to determine what the expected result is.
- String platform = System.getProperty("os.name");
- try {
- serverSocket = new ServerSocket();
- serverSocket.setReuseAddress(false);
- serverSocket.bind(theAddress);
- if ((!platform.startsWith("Windows"))) {
- fail("No exception when setReuseAddress is false and we bind:"
- + theAddress.toString());
- }
- } catch (IOException ex) {
- if (platform.startsWith("Windows")) {
- fail("Got unexpected exception when binding with setReuseAddress false on windows platform:"
- + theAddress.toString() + ":" + ex.toString());
- }
- }
- stillActiveSocket.close();
- theSocket.close();
-
- // now test case were we set it to true
- anyAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
- serverSocket = new ServerSocket();
- serverSocket.setReuseAddress(true);
- serverSocket.bind(anyAddress);
- theAddress = serverSocket.getLocalSocketAddress();
-
- // make a connection to the server, then close the server
- theSocket = new Socket();
- theSocket.connect(theAddress);
- stillActiveSocket = serverSocket.accept();
- serverSocket.close();
-
- // now try to rebind the server which should pass with
- // setReuseAddress to true
- try {
- serverSocket = new ServerSocket();
- serverSocket.setReuseAddress(true);
- serverSocket.bind(theAddress);
- } catch (IOException ex) {
- fail("Unexpected exception when setReuseAddress is true and we bind:"
- + theAddress.toString() + ":" + ex.toString());
- }
- stillActiveSocket.close();
- theSocket.close();
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
-
- // now test default case were we expect this to work regardless of
- // the value set
- anyAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
- serverSocket = new ServerSocket();
- serverSocket.bind(anyAddress);
- theAddress = serverSocket.getLocalSocketAddress();
-
- // make a connection to the server, then close the server
- theSocket = new Socket();
- theSocket.connect(theAddress);
- stillActiveSocket = serverSocket.accept();
- serverSocket.close();
-
- // now try to rebind the server which should pass
- try {
- serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- } catch (IOException ex) {
- fail("Unexpected exception when setReuseAddress is the default case and we bind:"
- + theAddress.toString() + ":" + ex.toString());
- }
- stillActiveSocket.close();
- theSocket.close();
- try {
- theSocket.setReuseAddress(true);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
- } catch (Exception e) {
- handleException(e, SO_REUSEADDR);
- }
- }
-
- /**
- * @tests java.net.ServerSocket#getReuseAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getReuseAddress",
- args = {}
- )
- public void test_getReuseAddress() {
- try {
- ServerSocket theSocket = new ServerSocket();
- theSocket.setReuseAddress(true);
- assertTrue("getReuseAddress false when it should be true",
- theSocket.getReuseAddress());
- theSocket.setReuseAddress(false);
- assertFalse("getReuseAddress true when it should be False",
- theSocket.getReuseAddress());
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
- } catch (Exception e) {
- handleException(e, SO_REUSEADDR);
- }
-
- try {
- ServerSocket newSocket = new ServerSocket();
- newSocket.close();
- try {
- newSocket.getReuseAddress();
- fail("SocketException was not thrown.");
- } catch(SocketException e) {
- //expected
- }
- } catch(Exception e) {
- fail("Unexpected exception.");
- }
- }
-
- /**
- * @tests java.net.ServerSocket#setReceiveBufferSize(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setReceiveBufferSize",
- args = {int.class}
- )
- public void test_setReceiveBufferSizeI() {
- try {
- // now validate case where we try to set to 0
- ServerSocket theSocket = new ServerSocket();
- try {
- theSocket.setReceiveBufferSize(0);
- fail("No exception when receive buffer size set to 0");
- } catch (IllegalArgumentException ex) {
- }
- theSocket.close();
-
- // now validate case where we try to set to a negative value
- theSocket = new ServerSocket();
- try {
- theSocket.setReceiveBufferSize(-1000);
- fail("No exception when receive buffer size set to -1000");
- } catch (IllegalArgumentException ex) {
- }
- theSocket.close();
-
- // now just try to set a good value to make sure it is set and there
- // are not exceptions
- theSocket = new ServerSocket();
- theSocket.setReceiveBufferSize(1000);
- theSocket.close();
- try {
- theSocket.setReceiveBufferSize(10);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
- } catch (Exception e) {
- handleException(e, SO_RCVBUF);
- }
-
- }
-
- /*
- * @tests java.net.ServerSocket#getReceiveBufferSize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getReceiveBufferSize",
- args = {}
- )
- public void test_getReceiveBufferSize() {
- try {
- ServerSocket theSocket = new ServerSocket();
-
- // since the value returned is not necessary what we set we are
- // limited in what we can test
- // just validate that it is not 0 or negative
- assertFalse("get Buffer size returns 0:", 0 == theSocket
- .getReceiveBufferSize());
- assertFalse("get Buffer size returns a negative value:",
- 0 > theSocket.getReceiveBufferSize());
-
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
- } catch (Exception e) {
- handleException(e, SO_RCVBUF);
- }
- try {
- ServerSocket newSocket = new ServerSocket();
- newSocket.close();
- try {
- newSocket.getReceiveBufferSize();
- fail("SocketException was not thrown.");
- } catch(SocketException e) {
- //expected
- }
- } catch(Exception e) {
- fail("Unexpected exception.");
- }
- }
-
- /**
- * @tests java.net.ServerSocket#getChannel()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getChannel",
- args = {}
- )
- public void test_getChannel() throws Exception {
- assertNull(new ServerSocket().getChannel());
- }
-
- /*
- * @tests java.net.ServerSocket#setPerformancePreference()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setPerformancePreferences",
- args = {int.class, int.class, int.class}
- )
- public void test_setPerformancePreference_Int_Int_Int() throws Exception {
- performancePreferenceTest(1, 0, 0);
- performancePreferenceTest(1, 1, 1);
- performancePreferenceTest(0, 1, 2);
- performancePreferenceTest(Integer.MAX_VALUE, Integer.MAX_VALUE,
- Integer.MAX_VALUE);
- }
-
- void performancePreferenceTest(int connectionTime, int latency,
- int bandwidth) throws Exception {
- ServerSocket theSocket = new ServerSocket();
- theSocket.setPerformancePreferences(connectionTime, latency, bandwidth);
-
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), 0);
- theSocket.bind(theAddress);
- int portNumber = theSocket.getLocalPort();
- assertTrue(
- "Returned incorrect InetSocketAddress(2):"
- + theSocket.getLocalSocketAddress().toString()
- + "Expected: "
- + (new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)).toString(), theSocket
- .getLocalSocketAddress().equals(
- new InetSocketAddress(InetAddress
- .getLocalHost(), portNumber)));
- assertTrue("Server socket not bound when it should be:", theSocket
- .isBound());
-
- // now make sure that it is actually bound and listening on the
- // address we provided
- Socket clientSocket = new Socket();
- InetSocketAddress clAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), portNumber);
- clientSocket.connect(clAddress);
- Socket servSock = theSocket.accept();
-
- assertEquals(clAddress, clientSocket.getRemoteSocketAddress());
- theSocket.close();
- servSock.close();
- clientSocket.close();
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
-
- try {
- if (s != null)
- s.close();
- if (sconn != null)
- sconn.close();
- if (t != null)
- t.interrupt();
- } catch (Exception e) {
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void startClient(int port) {
- t = new Thread(new SSClient(port), "SSClient");
- t.start();
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- System.out.println("Exception during startClinet()" + e.toString());
- }
- }
-
- /**
- * @tests java.net.ServerSocket#implAccept
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Regression test.",
- method = "implAccept",
- args = {java.net.Socket.class}
- )
- public void test_implAcceptLjava_net_Socket() throws Exception {
- // regression test for Harmony-1235
- try {
- new MockServerSocket().mockImplAccept(new MockSocket(
- new MockSocketImpl()));
- } catch (SocketException e) {
- // expected
- }
- }
-
- class MockSocketImpl extends SocketImpl {
- public MockSocketImpl() {
- isCreateCalled = true;
- }
-
- protected void create(boolean arg0) throws IOException {
- //empty
- }
-
- protected void connect(String arg0, int arg1) throws IOException {
- // empty
- }
-
- protected void connect(InetAddress arg0, int arg1) throws IOException {
- // empty
- }
-
- protected void connect(SocketAddress arg0, int arg1) throws IOException {
- // empty
- }
-
- protected void bind(InetAddress arg0, int arg1) throws IOException {
- // empty
- }
-
- protected void listen(int arg0) throws IOException {
- // empty
- }
-
- protected void accept(SocketImpl arg0) throws IOException {
- // empty
- }
-
- protected InputStream getInputStream() throws IOException {
- return null;
- }
-
- protected OutputStream getOutputStream() throws IOException {
- return null;
- }
-
- protected int available() throws IOException {
- return 0;
- }
-
- protected void close() throws IOException {
- // empty
- }
-
- protected void sendUrgentData(int arg0) throws IOException {
- // empty
- }
-
- public void setOption(int arg0, Object arg1) throws SocketException {
- // empty
- }
-
- public Object getOption(int arg0) throws SocketException {
- return null;
- }
- }
-
- static class MockSocket extends Socket {
- public MockSocket(SocketImpl impl) throws SocketException {
- super(impl);
- }
- }
-
- static class MockServerSocket extends ServerSocket {
- public MockServerSocket() throws Exception {
- super();
- }
-
- public void mockImplAccept(Socket s) throws Exception {
- super.implAccept(s);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getLocalPort",
- args = {}
- )
- public void test_LocalPort() throws IOException {
- ServerSocket ss1 = new ServerSocket(4242);
- assertEquals(ss1.getLocalPort(), 4242);
- ss1.close();
-
- ServerSocket ss2 = new ServerSocket();
- ss2.bind(new InetSocketAddress("127.0.0.1", 4343));
- assertEquals(ss2.getLocalPort(), 4343);
- ss2.close();
-
- ServerSocket ss3 = new ServerSocket(0);
- assertTrue(ss3.getLocalPort() != 0);
- ss3.close();
- }
-
- /**
- * @tests java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "",
- method = "setSocketFactory",
- args = {java.net.SocketImplFactory.class}
- )
- public void test_setSocketFactoryLjava_net_SocketImplFactory() {
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkSetFactory() {
- throw new SecurityException();
- }
- };
-
- MockSocketFactory sf = new MockSocketFactory();
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- ServerSocket.setSocketFactory(sf);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (IOException e) {
- fail("IOException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
-/*
-* try {
-* ServerSocket.setSocketFactory(sf);
-* ServerSocket ss1 = new ServerSocket();
-* assertTrue(isCreateCalled);
-* isCreateCalled = false;
-* ServerSocket ss2 = new ServerSocket(0);
-* assertTrue(isCreateCalled);
-* } catch(IOException ioe) {
-* fail("IOException was thrown: " + ioe.toString());
-* }
-
-* try {
-* ServerSocket.setSocketFactory(null);
-* fail("IOException was not thrown.");
-* } catch(IOException ioe) {
-* //expected
-* }
-*/
- }
-
- class MockSocketFactory implements SocketImplFactory {
- public SocketImpl createSocketImpl() {
- return new MockSocketImpl();
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/SocketExceptionTest.java b/luni/src/test/java/tests/api/java/net/SocketExceptionTest.java
deleted file mode 100644
index c86c4b2..0000000
--- a/luni/src/test/java/tests/api/java/net/SocketExceptionTest.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.SocketException;
-
-@TestTargetClass(SocketException.class)
-public class SocketExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.SocketException#SocketException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SocketException",
- args = {}
- )
- public void test_Constructor() {
- try {
- throw new SocketException();
- } catch (SocketException e) {
- return;
- } catch (Exception e) {
- fail("Exception during SocketException test : " + e.getMessage());
- }
- fail("Failed to generate expected exception");
- }
-
- /**
- * @tests java.net.SocketException#SocketException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SocketException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- try {
- throw new SocketException("Some error message");
- } catch (SocketException e) {
- return;
- } catch (Exception e) {
- fail("Exception during SocketException test" + e.toString());
- }
- fail("Failed to generate expected exception");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/SocketImplFactoryTest.java b/luni/src/test/java/tests/api/java/net/SocketImplFactoryTest.java
deleted file mode 100644
index 3a4a2bc..0000000
--- a/luni/src/test/java/tests/api/java/net/SocketImplFactoryTest.java
+++ /dev/null
@@ -1,211 +0,0 @@
-package tests.api.java.net;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-import junit.framework.TestCase;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.lang.reflect.Field;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.net.SocketImpl;
-import java.net.SocketImplFactory;
-
-
-@TestTargetClass(SocketImplFactory.class)
-public class SocketImplFactoryTest extends TestCase {
-
- SocketImplFactory oldFactory = null;
- Field factoryField = null;
-
- boolean isTestable = false;
-
- boolean iSocketImplCalled = false;
- boolean isCreateSocketImpl = false;
-
- @TestTargets ({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "createSocketImpl",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies positive case, and SocketException.",
- clazz = Socket.class,
- method = "setSocketImplFactory",
- args = {java.net.SocketImplFactory.class}
- )
- })
- public void test_createSocketImpl() throws IOException {
- MockSocketImplFactory factory = new MockSocketImplFactory();
- if(isTestable) {
-
- assertFalse(isCreateSocketImpl);
- Socket.setSocketImplFactory(factory);
-
- try {
- Socket ds = new Socket();
- assertTrue(isCreateSocketImpl);
- assertTrue(iSocketImplCalled);
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
-
- }
-
- try {
- Socket.setSocketImplFactory(factory);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
-
- try {
- Socket.setSocketImplFactory(null);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
-
- } else {
- SocketImpl si = factory.createSocketImpl();
- try {
- assertNull(si.getOption(0));
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- }
- }
- }
-
- public void setUp() {
- Field [] fields = Socket.class.getDeclaredFields();
- int counter = 0;
- for (Field field : fields) {
- if (SocketImplFactory.class.equals(field.getType())) {
- counter++;
- factoryField = field;
- }
- }
-
- if(counter == 1) {
-
- isTestable = true;
-
- factoryField.setAccessible(true);
- try {
- oldFactory = (SocketImplFactory) factoryField.get(null);
- } catch (IllegalArgumentException e) {
- fail("IllegalArgumentException was thrown during setUp: "
- + e.getMessage());
- } catch (IllegalAccessException e) {
- fail("IllegalAccessException was thrown during setUp: "
- + e.getMessage());
- }
- }
- }
-
- public void tearDown() {
- if(isTestable) {
- try {
- factoryField.set(null, oldFactory);
- } catch (IllegalArgumentException e) {
- fail("IllegalArgumentException was thrown during tearDown: "
- + e.getMessage());
- } catch (IllegalAccessException e) {
- fail("IllegalAccessException was thrown during tearDown: "
- + e.getMessage());
- }
- }
- }
-
- class MockSocketImplFactory implements SocketImplFactory {
-
- public SocketImpl createSocketImpl() {
- isCreateSocketImpl = true;
- return new MockSocketImpl();
- }
- }
-
- class MockSocketImpl extends SocketImpl {
-
- public MockSocketImpl() {
- super();
- iSocketImplCalled = true;
- }
- @Override
- protected void accept(SocketImpl arg0) throws IOException {
-
- }
-
- @Override
- protected int available() throws IOException {
- return 0;
- }
-
- @Override
- protected void bind(InetAddress arg0, int arg1) throws IOException {
-
- }
-
- @Override
- protected void close() throws IOException {
-
- }
-
- @Override
- protected void connect(String arg0, int arg1) throws IOException {
-
- }
-
- @Override
- protected void connect(InetAddress arg0, int arg1) throws IOException {
-
- }
-
- @Override
- protected void connect(SocketAddress arg0, int arg1) throws IOException {
-
- }
-
- @Override
- protected void create(boolean arg0) throws IOException {
-
- }
-
- @Override
- protected InputStream getInputStream() throws IOException {
- return null;
- }
-
- @Override
- protected OutputStream getOutputStream() throws IOException {
- return null;
- }
-
- @Override
- protected void listen(int arg0) throws IOException {
-
- }
-
- @Override
- protected void sendUrgentData(int arg0) throws IOException {
-
- }
-
- public Object getOption(int arg0) throws SocketException {
- return null;
- }
-
- public void setOption(int arg0, Object arg1) throws SocketException {
-
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/SocketImplTest.java b/luni/src/test/java/tests/api/java/net/SocketImplTest.java
deleted file mode 100644
index 7e9b601..0000000
--- a/luni/src/test/java/tests/api/java/net/SocketImplTest.java
+++ /dev/null
@@ -1,265 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.FileDescriptor;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.InetAddress;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.net.SocketImpl;
-/*
-* SocketImpl functionality is untestable because of
-* Socket.setSocketImplFactory method can be specified only once.
-*/
-
-@TestTargetClass(value = SocketImpl.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "accept",
- args = {SocketImpl.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "available",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "bind",
- args = {InetAddress.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "close",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "connect",
- args = {String.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "connect",
- args = {InetAddress.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "connect",
- args = {SocketAddress.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "create",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getFileDescriptor",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getInetAddress",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getInputStream",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getLocalPort",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getOption",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getOutputStream",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getPort",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "listen",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "sendUrgentData",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setOption",
- args = {int.class, Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setPerformancePreferences",
- args = {int.class, int.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "shutdownInput",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "shutdownOutput",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "supportsUrgentData",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "toString",
- args = {}
- )
- })
-public class SocketImplTest extends junit.framework.TestCase {
-
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Regression test.",
- method = "SocketImpl",
- args = {}
- )
- public void test_Constructor_fd() throws Exception {
- // regression test for Harmony-1117
- MockSocketImpl mockSocketImpl = new MockSocketImpl();
- assertNull(mockSocketImpl.getFileDescriptor());
- }
-
- // the mock class for test, leave all method empty
- class MockSocketImpl extends SocketImpl{
-
- protected void accept(SocketImpl newSocket) throws IOException {
- }
-
- protected int available() throws IOException {
- return 0;
- }
-
- protected void bind(InetAddress address, int port) throws IOException {
- }
-
- protected void close() throws IOException {
- }
-
- protected void connect(String host, int port) throws IOException {
- }
-
- protected void connect(InetAddress address, int port) throws IOException {
- }
-
- protected void create(boolean isStreaming) throws IOException {
- }
-
- protected InputStream getInputStream() throws IOException {
- return null;
- }
-
- public Object getOption(int optID) throws SocketException {
- return null;
- }
-
- protected OutputStream getOutputStream() throws IOException {
- return null;
- }
-
- protected void listen(int backlog) throws IOException {
- }
-
- public void setOption(int optID, Object val) throws SocketException {
- }
-
- protected void connect(SocketAddress remoteAddr, int timeout) throws IOException {
- }
-
- protected void sendUrgentData(int value) throws IOException {
- }
-
- public void setPerformancePreference(int connectionTime,
- int latency,
- int bandwidth){
- super.setPerformancePreferences(connectionTime, latency, bandwidth);
- }
-
- public FileDescriptor getFileDescriptor() {
- return super.getFileDescriptor();
- }
-
- public void shutdownOutput() throws IOException {
- super.shutdownOutput();
- }
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-
- protected void doneSuite() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/SocketPermissionTest.java b/luni/src/test/java/tests/api/java/net/SocketPermissionTest.java
deleted file mode 100644
index fecf50c..0000000
--- a/luni/src/test/java/tests/api/java/net/SocketPermissionTest.java
+++ /dev/null
@@ -1,288 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.InetAddress;
-import java.net.SocketPermission;
-import java.net.UnknownHostException;
-import java.security.PermissionCollection;
-
-import tests.support.Support_Configuration;
-
-@TestTargetClass(SocketPermission.class)
-public class SocketPermissionTest extends junit.framework.TestCase {
-
- String starName = "*." + Support_Configuration.DomainAddress;
-
- String wwwName = Support_Configuration.HomeAddress;
-
- SocketPermission star_Resolve = new SocketPermission(starName, "resolve");
-
- SocketPermission star_All = new SocketPermission(starName,
- "listen,accept,connect");
-
- SocketPermission www_All = new SocketPermission(wwwName,
- "connect,listen,accept");
-
- SocketPermission copyOfWww_All = new SocketPermission(wwwName,
- "connect,listen,accept");
-
- /**
- * @tests java.net.SocketPermission#SocketPermission(java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SocketPermission",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_String() {
- // Test for method java.net.SocketPermission(java.lang.String,
- // java.lang.String)
- assertTrue("Incorrect name", star_Resolve.getName().equals(starName));
- assertEquals("Incorrect actions",
- "resolve", star_Resolve.getActions());
-
- SocketPermission sp1 = new SocketPermission("", "connect");
- assertEquals("Wrong name1", "localhost", sp1.getName());
- SocketPermission sp2 = new SocketPermission(":80", "connect");
- assertEquals("Wrong name2", ":80", sp2.getName());
-
- // regression for HARMONY-1462
- SocketPermission sp3 = new SocketPermission("localhost:*", "listen");
- assertEquals("Wrong name3", "localhost:*", sp3.getName());
- // for all ports
- SocketPermission spAllPorts = new SocketPermission("localhost:0-65535",
- "listen");
- assertTrue("Port range error", sp3.implies(spAllPorts));
- assertTrue("Port range error", spAllPorts.implies(sp3));
- }
-
- /**
- * @tests java.net.SocketPermission#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean
- // java.net.SocketPermission.equals(java.lang.Object)
- assertTrue("Different names but returned equal", !star_All
- .equals(www_All));
- assertTrue("Different actions but returned equal", !star_Resolve
- .equals(star_All));
- assertTrue("Same but returned unequal", www_All.equals(copyOfWww_All));
- assertTrue("Returned true when compared to a String", !www_All
- .equals(www_All.toString()));
-
- SocketPermission sp1 = new SocketPermission("TEST1.com",
- "resolve,connect");
- SocketPermission sp2 = new SocketPermission("test1.com",
- "resolve,connect");
- assertTrue("Different cases should be equal", sp1.equals(sp2));
-
- // Regression for HARMONY-1524
- assertFalse(sp1.equals(null));
-
- // Regression for HARMONY-3333
- sp1 = new SocketPermission("TEST1.com:333", "resolve");
- sp2 = new SocketPermission("test1.com:444", "resolve");
- assertTrue("Different cases should be equal", sp1.equals(sp2));
- }
-
- /**
- * @tests java.net.SocketPermission#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object_subtest0() {
- SocketPermission sp1 = new SocketPermission(
- Support_Configuration.InetTestAddress, "resolve,connect");
- SocketPermission sp2 = new SocketPermission(
- Support_Configuration.InetTestIP, "resolve,connect");
- assertTrue("Same IP address should be equal", sp1.equals(sp2));
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- SocketPermission sp1 = new SocketPermission(
- Support_Configuration.InetTestIP, "resolve,connect");
- SocketPermission sp2 = new SocketPermission(
- Support_Configuration.InetTestIP, "resolve,connect");
- assertTrue("Same IP address should have equal hash codes",
- sp1.hashCode() == sp2.hashCode());
-
- assertTrue("Different names but returned equal hash codes",
- star_All.hashCode() != www_All.hashCode());
- }
-
- /**
- * @tests java.net.SocketPermission#getActions()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getActions",
- args = {}
- )
- public void test_getActions() {
- // Test for method java.lang.String
- // java.net.SocketPermission.getActions()
- assertEquals("Incorrect actions",
- "resolve", star_Resolve.getActions());
- assertEquals("Incorrect actions/not in canonical form", "connect,listen,accept,resolve", star_All
- .getActions());
- }
-
- /**
- * @tests java.net.SocketPermission#implies(java.security.Permission)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "implies",
- args = {java.security.Permission.class}
- )
- public void test_impliesLjava_security_Permission() {
- // Test for method boolean
- // java.net.SocketPermission.implies(java.security.Permission)
- assertTrue("All should imply resolve", star_All.implies(star_Resolve));
-
- // regression for HARMONY-1200
- assertFalse("Null should not be implied", star_All.implies((SocketPermission)null));
-
- assertTrue("Equals should imply eachother", www_All
- .implies(copyOfWww_All));
- assertTrue("Wild should imply normal", star_All.implies(www_All));
- assertTrue("Normal shouldn't imply wildcard", !www_All
- .implies(star_Resolve));
- assertTrue("Resolve shouldn't imply all", !star_Resolve
- .implies(star_All));
- SocketPermission p1 = new SocketPermission(wwwName + ":80-81",
- "connect");
- SocketPermission p2 = new SocketPermission(wwwName + ":80", "connect");
- assertTrue("Port 80 is implied by 80-81", p1.implies(p2));
- p1 = new SocketPermission(wwwName + ":79-80", "connect");
- assertTrue("Port 80 is implied by 79-80", p1.implies(p2));
- p1 = new SocketPermission(wwwName + ":79-81", "connect");
- assertTrue("Port 80 is implied by 79-81", p1.implies(p2));
- p2 = new SocketPermission(wwwName + ":79-80", "connect");
- assertTrue("Port 79-80 is implied by 79-81", p1.implies(p2));
- p2 = new SocketPermission(wwwName, "resolve");
- assertTrue(
- "Any identical host should imply resolve regardless of the ports",
- p1.implies(p2));
-
- SocketPermission sp1 = new SocketPermission("www.Ibm.com", "resolve");
- SocketPermission sp2 = new SocketPermission("www.IBM.com", "resolve");
- assertTrue("SocketPermission is case sensitive", sp1.implies(sp2));
-
- SocketPermission sp3 = new SocketPermission("*.ibm.com", "resolve");
- assertTrue("SocketPermission wildcard is case sensitive", sp3
- .implies(sp2));
-
- InetAddress host = null;
- try {
- host = InetAddress.getByName(Support_Configuration.UnresolvedIP);
- } catch (UnknownHostException e) {
- }
-
- SocketPermission perm1 = new SocketPermission(
- Support_Configuration.UnresolvedIP, "connect");
- SocketPermission perm2 = new SocketPermission(
- Support_Configuration.UnresolvedIP + ":80", "connect");
- assertTrue("should imply port 80", perm1.implies(perm2));
- PermissionCollection col = perm1.newPermissionCollection();
- col.add(perm1);
- assertTrue("collection should imply port 80", col.implies(perm2));
-
- }
-
- /**
- * @tests java.net.SocketPermission#newPermissionCollection()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "newPermissionCollection",
- args = {}
- )
- public void test_newPermissionCollection() {
- // Test for method java.security.PermissionCollection
- // java.net.SocketPermission.newPermissionCollection()
- java.security.PermissionCollection pc = star_Resolve
- .newPermissionCollection();
- pc.add(star_Resolve);
- pc.add(www_All);
- assertTrue("Should imply all on " + wwwName, pc.implies(www_All));
- assertTrue("Should imply resolve on " + starName, pc
- .implies(star_Resolve));
- assertTrue("Should not imply all on " + starName, !pc.implies(star_All));
-
- // wipe out pc
- pc = star_Resolve.newPermissionCollection();
- pc.add(star_All);
- assertTrue("Should imply resolve on " + starName, pc
- .implies(star_Resolve));
- assertTrue("Should imply all on " + wwwName, pc.implies(www_All));
-
- pc = star_Resolve.newPermissionCollection();
- SocketPermission p1 = new SocketPermission(wwwName + ":79-80",
- "connect");
- pc.add(p1);
- SocketPermission p2 = new SocketPermission(wwwName, "resolve");
- assertTrue(
- "Any identical host should imply resolve regardless of the ports",
- pc.implies(p2));
- assertTrue("A different host should not imply resolve", !pc
- .implies(star_Resolve));
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/SocketTest.java b/luni/src/test/java/tests/api/java/net/SocketTest.java
deleted file mode 100644
index 94e7d09..0000000
--- a/luni/src/test/java/tests/api/java/net/SocketTest.java
+++ /dev/null
@@ -1,3395 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.AndroidOnly;
-//import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InterruptedIOException;
-import java.io.OutputStream;
-import java.net.ConnectException;
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.Proxy;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.net.SocketImpl;
-import java.net.SocketTimeoutException;
-import java.net.UnknownHostException;
-import java.nio.channels.IllegalBlockingModeException;
-import java.nio.channels.SocketChannel;
-import java.security.Permission;
-
-import tests.support.Support_Configuration;
-import tests.support.Support_PortManager;
-
-@TestTargetClass(Socket.class)
-public class SocketTest extends SocketTestCase {
-
- ServerSocket ss;
-
- Socket s;
-
- Thread t;
-
- boolean interrupted = false;
-
- class SServer extends Thread implements Runnable {
- Socket s1 = null;
-
- public void run() {
- try {
- ss.setSoTimeout(5000);
- s1 = ss.accept();
- ss.close();
- Thread.sleep(4000);
- } catch (java.io.InterruptedIOException x) {
- System.out.println(Thread.currentThread()
- + ", accept() timeout fired: " + x);
- } catch (InterruptedException x) {
- } catch (Exception e) {
- System.out.println("Unable to accept: " + e.toString());
- } finally {
- try {
- if (s1 != null)
- s1.close();
- } catch (java.io.IOException e) {
- }
- }
- }
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {}
-
- public void checkConnect(String host, int port) {
- throw new SecurityException();
- }
- };
-
- /**
- * @tests java.net.Socket#Socket()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Socket",
- args = {}
- )
- public void test_Constructor() {
- // create the socket and then validate some basic state
- s = new Socket();
- assertFalse("new socket should not be connected", s.isConnected());
- assertFalse("new socket should not be bound", s.isBound());
- assertFalse("new socket should not be closed", s.isClosed());
- assertFalse("new socket should not be in InputShutdown", s
- .isInputShutdown());
- assertFalse("new socket should not be in OutputShutdown", s
- .isOutputShutdown());
-
- }
-
- /**
- * @tests java.net.Socket#Socket(java.lang.String, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Socket",
- args = {java.lang.String.class, int.class}
- )
- public void test_ConstructorLjava_lang_StringI() throws IOException {
- // Test for method java.net.Socket(java.lang.String, int)
- int sport = startServer("Cons String,I");
- s = new Socket(InetAddress.getLocalHost().getHostName(), sport);
- assertTrue("Failed to create socket", s.getPort() == sport);
-
- //regression for HARMONY-946
- ServerSocket ss = null;
- Socket s = null;
- try {
- ss = new ServerSocket(0);
- s = new Socket("0.0.0.0", ss.getLocalPort());
- } finally {
- try {
- ss.close();
- } catch(Exception e) {
- //ignore
- }
- try {
- s.close();
- } catch(Exception e) {
- //ignore
- }
- }
-
- try {
- new Socket("unknown.host", 0);
- fail("UnknownHostException was not thrown.");
- } catch(UnknownHostException uhe) {
- //expected
- }
- Socket socket = null;
- try {
- socket = new Socket(InetAddress.getByName(null), sport);
- assertEquals(InetAddress.getByName("127.0.0.1"), socket.getLocalAddress());
- } finally {
- try {
- socket.close();
- } catch(Exception e) {}
- }
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new Socket(InetAddress.getLocalHost().getHostName(), sport);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.net.Socket#Socket(java.lang.String, int,
- * java.net.InetAddress, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Socket",
- args = {java.lang.String.class, int.class, java.net.InetAddress.class, int.class}
- )
- public void test_ConstructorLjava_lang_StringILjava_net_InetAddressI()
- throws IOException {
- // Test for method java.net.Socket(java.lang.String, int,
- // java.net.InetAddress, int)
- int sport = startServer("Cons String,I,InetAddress,I");
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost().getHostName(), sport,
- InetAddress.getLocalHost(), portNumber);
- assertTrue("Failed to create socket", s.getPort() == sport);
-
- if (("true".equals(System.getProperty("java.net.preferIPv6Addresses")))
- && !("true".equals(System
- .getProperty("java.net.preferIPv4Stack")))) {
-
- // ALTERNATE IPv6 TEST
- if ("true".equals(System.getProperty("run.ipv6tests"))) {
- System.out
- .println("Running testConstructorLjava_lang_StringILjava_net_InetAddressI(SocketTest) with IPv6GlobalAddressJcl4: "
- + Support_Configuration.IPv6GlobalAddressJcl4);
- int testPort = Support_PortManager.getNextPort();
- Socket s1 = null, s2 = null;
- try {
- s1 = new Socket(
- Support_Configuration.IPv6GlobalAddressJcl4, 80,
- InetAddress.getLocalHost(), testPort);
- } catch (IOException e) {
- // check here if InetAddress.getLocalHost() is returning the
- // loopback address.
- // if so that is likely the cause of the failure
- String warning = "";
- try {
- InetAddress returnedLocalHost = InetAddress
- .getLocalHost();
- // don't use isLoopbackAddress for some configurations
- // as they do not have it
- if (returnedLocalHost.isLoopbackAddress()) {
- warning = " - WARNING RETURNED LOCAL HOST IS THE LOOPBACK ADDRESS - MACHINE IS LIKELY NOT CONFIGURED CORRECTLY - THIS LIKELY CAUSED THE FAILURE";
-
- }
- } catch (Exception ex) {
- warning = " - WARNING COULD NOT GET LOCAL HOST - " + ex;
- }
-
- fail("Exception creating 1st socket" + warning + ": " + e);
- }
- boolean exception = false;
- try {
- s2 = new Socket(
- Support_Configuration.IPv6GlobalAddressJcl4, 80,
- InetAddress.getLocalHost(), testPort);
- } catch (IOException e) {
- exception = true;
- }
- try {
- s1.close();
- if (!exception)
- s2.close();
- } catch (IOException e) {
- }
- assertTrue("Was able to create two sockets on same port",
- exception);
- }
-
- } else {
- int testPort = Support_PortManager.getNextPort();
- Socket s1 = null, s2 = null;
- int serverPort = ss.getLocalPort();
- try {
- s1 = new Socket("127.0.0.1", serverPort, InetAddress
- .getLocalHost(), testPort);
- } catch (IOException e) {
- e.printStackTrace();
-
- // check here if InetAddress.getLocalHost() is returning the
- // loopback address.
- // if so that is likely the cause of the failure
- String warning = "";
- try {
- InetAddress returnedLocalHost = InetAddress.getLocalHost();
- // don't use isLoopbackAddress for some configurations as
- // they do not have it
- if (returnedLocalHost.isLoopbackAddress()) {
- warning = " - WARNING RETURNED LOCAL HOST IS THE LOOPBACK ADDRESS - MACHINE IS LIKELY NOT CONFIGURED CORRECTLY - THIS LIKELY CAUSED THE FAILURE";
-
- }
- } catch (Exception ex) {
- warning = " - WARNING COULD NOT GET LOCAL HOST - " + ex;
- }
-
- fail("Exception creating 1st socket" + warning + ": " + e);
- }
- boolean exception = false;
- try {
- s2 = new Socket("127.0.0.1", serverPort, InetAddress
- .getLocalHost(), testPort);
- } catch (IOException e) {
- exception = true;
- }
- try {
- s1.close();
- if (!exception)
- s2.close();
- } catch (IOException e) {
- }
- assertTrue("Was able to create two sockets on same port", exception);
- }
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new Socket("127.0.0.1", 0, InetAddress
- .getLocalHost(), 0);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.net.Socket#Socket(java.lang.String, int, boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Socket",
- args = {java.lang.String.class, int.class, boolean.class}
- )
- public void test_ConstructorLjava_lang_StringIZ() throws IOException {
- // Test for method java.net.Socket(java.lang.String, int, boolean)
- int sport = startServer("Cons String,I,Z");
- s = new Socket(InetAddress.getLocalHost().getHostName(), sport, true);
- assertTrue("Failed to create socket", s.getPort() == sport);
-
- s = new Socket(InetAddress.getLocalHost().getHostName(), sport, false);
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new Socket(InetAddress.getLocalHost().getHostName(), sport, true);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.net.Socket#Socket(java.net.InetAddress, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Socket",
- args = {java.net.InetAddress.class, int.class}
- )
- public void test_ConstructorLjava_net_InetAddressI() throws IOException {
- // Test for method java.net.Socket(java.net.InetAddress, int)
- int sport = startServer("Cons InetAddress,I");
- s = new Socket(InetAddress.getLocalHost(), sport);
- assertTrue("Failed to create socket", s.getPort() == sport);
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new Socket(InetAddress.getLocalHost(), sport);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.net.Socket#Socket(java.net.InetAddress, int,
- * java.net.InetAddress, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Socket",
- args = {java.net.InetAddress.class, int.class, java.net.InetAddress.class, int.class}
- )
- public void test_ConstructorLjava_net_InetAddressILjava_net_InetAddressI()
- throws IOException {
- // Test for method java.net.Socket(java.net.InetAddress, int,
- // java.net.InetAddress, int)
- int sport = startServer("Cons InetAddress,I,InetAddress,I");
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost().getHostName(), sport,
- InetAddress.getLocalHost(), portNumber);
- assertTrue("Failed to create socket", s.getLocalPort() == portNumber);
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new Socket(InetAddress.getLocalHost().getHostName(), sport,
- InetAddress.getLocalHost(), portNumber);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.net.Socket#Socket(java.net.InetAddress, int, boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Socket",
- args = {java.net.InetAddress.class, int.class, boolean.class}
- )
- public void test_ConstructorLjava_net_InetAddressIZ() throws IOException {
- // Test for method java.net.Socket(java.net.InetAddress, int, boolean)
- int sport = startServer("Cons InetAddress,I,Z");
- s = new Socket(InetAddress.getLocalHost(), sport, true);
- assertTrue("Failed to create socket", s.getPort() == sport);
-
- s = new Socket(InetAddress.getLocalHost(), sport, false);
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new Socket(InetAddress.getLocalHost(), sport, true);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.net.Socket#close()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException checking missing.",
- method = "close",
- args = {}
- )
- public void test_close() throws IOException {
- // Test for method void java.net.Socket.close()
- int sport = startServer("SServer close");
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- try {
- s.setSoLinger(false, 100);
- } catch (IOException e) {
- handleException(e, SO_LINGER);
- }
- s.close();
- try {
- s.getOutputStream();
- fail("IOException was not thrown.");
- } catch (java.io.IOException e) {
- //expected
- }
- }
-
- /**
- * @tests java.net.Socket#getInetAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInetAddress",
- args = {}
- )
- public void test_getInetAddress() throws IOException {
- // Test for method java.net.InetAddress java.net.Socket.getInetAddress()
- int sport = startServer("SServer getInetAddress");
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- assertTrue("Returned incorrect InetAdrees", s.getInetAddress().equals(
- InetAddress.getLocalHost()));
-
- }
-
- /**
- * @tests java.net.Socket#getInputStream()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInputStream",
- args = {}
- )
- public void test_getInputStream() throws IOException {
- // Test for method java.io.InputStream java.net.Socket.getInputStream()
- int sport = startServer("SServer getInputStream");
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- (t = new SServer()).start();
- java.io.InputStream is = s.getInputStream();
- assertNotNull("Failed to get stream", is);
- s.setSoTimeout(6000);
- is.read();
- s.close();
- assertEquals("Invalid after close", -1, is.read());
-
- interrupted = false;
- int portNum = Support_PortManager.getNextPort();
- final ServerSocket ss = new ServerSocket(portNum);
- Socket sock = new Socket(InetAddress.getLocalHost(), portNum);
- Runnable runnable = new Runnable() {
- public void run() {
- try {
- Socket as = ss.accept();
- ss.close();
- as.setSoTimeout(12000);
- InputStream in = as.getInputStream();
- in.read();
- in.close();
- } catch (InterruptedIOException e) {
- interrupted = true;
- } catch (IOException e) {
- }
- }
- };
- Thread thread = new Thread(runnable, "Socket.getInputStream");
- thread.start();
- try {
- do {
- Thread.sleep(200);
- } while (!thread.isAlive());
- } catch (InterruptedException e) {
- }
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- }
- sock.close();
- try {
- sock.getInputStream();
- fail("IOException was not thrown.");
- } catch(IOException ioe) {
- //expected
- }
- int c = 0;
- do {
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- }
- if (interrupted) {
- fail("read interrupted");
- }
- if (++c > 4) {
- fail("read call did not exit");
- }
- } while (thread.isAlive());
-
- }
-
- /**
- * @tests java.net.Socket#getKeepAlive()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getKeepAlive",
- args = {}
- )
- public void test_getKeepAlive() {
- try {
- int sport = startServer("SServer getKeepAlive");
- int portNumber = Support_PortManager.getNextPort();
- Socket theSocket = new Socket(InetAddress.getLocalHost(), sport,
- null, portNumber);
- theSocket.setKeepAlive(true);
- assertTrue("getKeepAlive false when it should be true", theSocket
- .getKeepAlive());
- theSocket.setKeepAlive(false);
- assertFalse("getKeepAlive true when it should be False", theSocket
- .getKeepAlive());
- theSocket.close();
- try {
- theSocket.setKeepAlive(false);
- fail("IOException was not thrown after calling setKeepAlive " +
- "method.");
- } catch(IOException ioe) {
- //expected
- }
- try {
- theSocket.getKeepAlive();
- fail("IOException was not thrown after calling getKeepAlive +" +
- "method.");
- } catch(IOException ioe) {
- //expected
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_KEEPALIVE);
- } catch (Exception e) {
- handleException(e, SO_KEEPALIVE);
- }
- }
-
- /**
- * @tests java.net.Socket#getLocalAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalAddress",
- args = {}
- )
- public void test_getLocalAddress() throws IOException {
- // Test for method java.net.InetAddress
- // java.net.Socket.getLocalAddress()
- int sport = startServer("SServer getLocAddress");
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- assertEquals("Returned incorrect InetAddress",
- InetAddress.getLocalHost(), s.getLocalAddress());
-
- // now validate thet behaviour when the any address is returned
- String preferIPv4StackValue = System
- .getProperty("java.net.preferIPv4Stack");
- String preferIPv6AddressesValue = System
- .getProperty("java.net.preferIPv6Addresses");
-
- s = new Socket();
- s.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
-
- if (((preferIPv4StackValue == null) || preferIPv4StackValue
- .equalsIgnoreCase("false"))
- && (preferIPv6AddressesValue != null)
- && (preferIPv6AddressesValue.equals("true"))) {
- assertTrue(
- "ANY address not returned correctly (getLocalAddress) with preferIPv6Addresses=true, preferIPv4Stack=false "
- + s.getLocalSocketAddress(),
- s.getLocalAddress() instanceof Inet6Address);
- } else {
- assertTrue(
- "ANY address not returned correctly (getLocalAddress) with preferIPv6Addresses=true, preferIPv4Stack=true "
- + s.getLocalSocketAddress(),
- s.getLocalAddress() instanceof Inet4Address);
- }
- s.close();
-
- }
-
- /**
- * @tests java.net.Socket#getLocalPort()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalPort",
- args = {}
- )
- public void test_getLocalPort() throws IOException {
- // Test for method int java.net.Socket.getLocalPort()
- int sport = startServer("SServer getLocalPort");
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost().getHostName(), sport,
- InetAddress.getLocalHost(), portNumber);
- assertTrue("Returned incorrect port", s.getLocalPort() == portNumber);
- }
-
- /**
- * @tests java.net.Socket#getOutputStream()
- */
- @SuppressWarnings("deprecation")
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException checking missing.",
- method = "getOutputStream",
- args = {}
- )
- public void test_getOutputStream() throws IOException {
- // Test for method java.io.OutputStream
- // java.net.Socket.getOutputStream()
- int sport = startServer("SServer getOutputStream");
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- java.io.OutputStream os = s.getOutputStream();
- assertNotNull("Failed to get stream", os);
- os.write(1);
- s.close();
- // Regression test for harmony-2934
- s = new Socket("127.0.0.1", Support_PortManager.getNextPort(),
- false);
- OutputStream o = s.getOutputStream();
- o.write(1);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- }
- o.close();
- s.close();
-
- // Regression test for harmony-2942
- s = new Socket("0.0.0.0", Support_PortManager.getNextPort(),
- false);
- o = s.getOutputStream();
- o.write(1);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- }
- o.close();
- s.close();
- }
-
- /**
- * @tests java.net.Socket#getPort()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPort",
- args = {}
- )
- public void test_getPort() throws IOException {
- // Test for method int java.net.Socket.getPort()
- int sport = startServer("SServer getPort");
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- assertTrue("Returned incorrect port" + s.getPort(),
- s.getPort() == sport);
- }
-
- /**
- * @tests java.net.Socket#getSoLinger()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSoLinger",
- args = {}
- )
- public void test_getSoLinger() {
- // Test for method int java.net.Socket.getSoLinger()
- int sport = startServer("SServer getSoLinger");
- try {
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- s.setSoLinger(true, 200);
- assertEquals("Returned incorrect linger", 200, s.getSoLinger());
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_LINGER);
- s.setSoLinger(false, 0);
- } catch (Exception e) {
- handleException(e, SO_LINGER);
- }
-
- try {
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- s.close();
- try {
- s.getSoLinger();
- fail("SocketException was not thrown.");
- } catch(SocketException ioe) {
- //expected
- }
- } catch(Exception e) {
- fail("Unexpected exception was thrown: " + e.toString());
- }
- }
-
- /**
- * @tests java.net.Socket#getReceiveBufferSize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getReceiveBufferSize",
- args = {}
- )
- public void test_getReceiveBufferSize() {
- try {
- int sport = startServer("SServer getReceiveBufferSize");
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost().getHostName(), sport,
- null, portNumber);
- s.setReceiveBufferSize(130);
- assertTrue("Incorrect buffer size", s.getReceiveBufferSize() >= 130);
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
- } catch (Exception e) {
- handleException(e, SO_RCVBUF);
- }
-
- try {
- Socket newSocket = new Socket();
- newSocket.close();
- try {
- newSocket.getReceiveBufferSize();
- fail("SocketException was not thrown.");
- } catch(SocketException e) {
- //expected
- }
- } catch(Exception e) {
- fail("Unexpected exception.");
- }
- }
-
- /**
- * @tests java.net.Socket#getSendBufferSize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSendBufferSize",
- args = {}
- )
- public void test_getSendBufferSize() {
- int sport = startServer("SServer setSendBufferSize");
- try {
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost().getHostName(), sport,
- null, portNumber);
- s.setSendBufferSize(134);
- assertTrue("Incorrect buffer size", s.getSendBufferSize() >= 134);
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_SNDBUF);
- } catch (Exception e) {
- handleException(e, SO_SNDBUF);
- }
- try {
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- s.close();
- try {
- s.getSendBufferSize();
- fail("IOException was not thrown.");
- } catch(IOException ioe) {
- //expected
- }
- } catch(Exception e) {
- fail("Unexpected exception was thrown: " + e.toString());
- }
- }
-
- /**
- * @tests java.net.Socket#getSoTimeout()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSoTimeout",
- args = {}
- )
- public void test_getSoTimeout() {
- // Test for method int java.net.Socket.getSoTimeout()
- int sport = startServer("SServer getSoTimeout");
- try {
- s = new Socket(InetAddress.getLocalHost(), sport);
- s.setSoTimeout(100);
- assertEquals("Returned incorrect sotimeout", 100, s.getSoTimeout());
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_TIMEOUT);
- } catch (Exception e) {
- handleException(e, SO_TIMEOUT);
- }
-
- try {
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- s.close();
- try {
- s.getSoTimeout();
- fail("SocketException was not thrown.");
- } catch(SocketException ioe) {
- //expected
- }
- } catch(Exception e) {
- fail("Unexpected exception was thrown: " + e.toString());
- }
- }
-
- /**
- * @tests java.net.Socket#getTcpNoDelay()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTcpNoDelay",
- args = {}
- )
- public void test_getTcpNoDelay() {
- // Test for method boolean java.net.Socket.getTcpNoDelay()
- int sport = startServer("SServer getTcpNoDelay");
- try {
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- boolean bool = !s.getTcpNoDelay();
- s.setTcpNoDelay(bool);
- assertTrue("Failed to get no delay setting: " + s.getTcpNoDelay(),
- s.getTcpNoDelay() == bool);
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(TCP_NODELAY);
- } catch (Exception e) {
- handleException(e, TCP_NODELAY);
- }
-
- try {
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- s.close();
- try {
- s.getTcpNoDelay();
- fail("SocketException was not thrown.");
- } catch(SocketException ioe) {
- //expected
- }
- } catch(Exception e) {
- fail("Unexpected exception was thrown: " + e.toString());
- }
- }
-
- /**
- * @tests java.net.Socket#setKeepAlive(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setKeepAlive",
- args = {boolean.class}
- )
- public void test_setKeepAliveZ() throws Exception {
- // There is not really a good test for this as it is there to detect
- // crashed machines. Just make sure we can set it
- try {
- int sport = startServer("SServer setKeepAlive");
- int portNumber = Support_PortManager.getNextPort();
- Socket theSocket = new Socket(InetAddress.getLocalHost(), sport,
- null, portNumber);
- theSocket.setKeepAlive(true);
- theSocket.setKeepAlive(false);
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_KEEPALIVE);
- } catch (Exception e) {
- handleException(e, SO_KEEPALIVE);
- }
- // regression test for HARMONY-1136
- new TestSocket((SocketImpl) null).setKeepAlive(true);
-
- try {
- Socket theSocket = new Socket();
- theSocket.close();
- theSocket.setKeepAlive(true);
- fail("SocketException was not thrown.");
- } catch(SocketException ioe) {
- //expected
- }
- }
- class TestSocket extends Socket {
- public TestSocket(SocketImpl impl) throws SocketException {
- super(impl);
- }
- }
-
- /**
- * @tests java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies SecurityException.",
- method = "setSocketImplFactory",
- args = {java.net.SocketImplFactory.class}
- )
- public void test_setSocketImplFactoryLjava_net_SocketImplFactory() {
- // Test for method void
- // java.net.Socket.setSocketImplFactory(java.net.SocketImplFactory)
-
- // Cannot test as setting will cause the factory to be changed for
- // all subsequent sockets
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkSetFactory() {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- Socket.setSocketImplFactory(null);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (IOException e) {
- fail("IOException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- }
-
- /**
- * @tests java.net.Socket#setSendBufferSize(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setSendBufferSize",
- args = {int.class}
- )
- public void test_setSendBufferSizeI() {
- try {
- int sport = startServer("SServer setSendBufferSizeI");
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- s.setSendBufferSize(134);
- assertTrue("Incorrect buffer size", s.getSendBufferSize() >= 134);
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_SNDBUF);
- } catch (Exception e) {
- handleException(e, SO_SNDBUF);
- }
-
- try {
- Socket theSocket = new Socket();
- theSocket.close();
- theSocket.setSendBufferSize(1);
- fail("SocketException was not thrown.");
- } catch(SocketException ioe) {
- //expected
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- }
- }
-
- /**
- * @tests java.net.Socket#setReceiveBufferSize(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setReceiveBufferSize",
- args = {int.class}
- )
- public void test_setReceiveBufferSizeI() {
- try {
- int sport = startServer("SServer setReceiveBufferSizeI");
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- s.setReceiveBufferSize(130);
- assertTrue("Incorrect buffer size", s.getReceiveBufferSize() >= 130);
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
- } catch (Exception e) {
- handleException(e, SO_RCVBUF);
- }
-
- try {
- Socket theSocket = new Socket();
- theSocket.close();
- theSocket.setReceiveBufferSize(1);
- fail("SocketException was not thrown.");
- } catch(SocketException ioe) {
- //expected
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- }
- }
-
- /**
- * @tests java.net.Socket#setSoLinger(boolean, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setSoLinger",
- args = {boolean.class, int.class}
- )
- public void test_setSoLingerZI() {
- // Test for method void java.net.Socket.setSoLinger(boolean, int)
- try {
- int sport = startServer("SServer setSoLingerZI");
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- s.setSoLinger(true, 500);
- assertEquals("Set incorrect linger", 500, s.getSoLinger());
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_LINGER);
- s.setSoLinger(false, 0);
- } catch (Exception e) {
- handleException(e, SO_LINGER);
- }
-
- try {
- Socket theSocket = new Socket();
- theSocket.close();
- theSocket.setSoLinger(true, 1);
- fail("SocketException was not thrown.");
- } catch(SocketException ioe) {
- //expected
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- }
- }
-
- /**
- * @tests java.net.Socket#setSoTimeout(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setSoTimeout",
- args = {int.class}
- )
- public void test_setSoTimeoutI() {
- // Test for method void java.net.Socket.setSoTimeout(int)
- try {
- int sport = startServer("SServer seSoTimeoutI");
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- s.setSoTimeout(100);
- assertEquals("Set incorrect sotimeout", 100, s.getSoTimeout());
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_TIMEOUT);
- } catch (Exception e) {
- handleException(e, SO_TIMEOUT);
- }
-
- try {
- Socket theSocket = new Socket();
- theSocket.close();
- theSocket.setSoTimeout(1);
- fail("SocketException was not thrown.");
- } catch(SocketException ioe) {
- //expected
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- }
- }
-
- /**
- * @tests java.net.Socket#setTcpNoDelay(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setTcpNoDelay",
- args = {boolean.class}
- )
- public void test_setTcpNoDelayZ() {
- // Test for method void java.net.Socket.setTcpNoDelay(boolean)
- try {
- int sport = startServer("SServer setTcpNoDelayZ");
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- boolean bool;
- s.setTcpNoDelay(bool = !s.getTcpNoDelay());
- assertTrue("Failed to set no delay setting: " + s.getTcpNoDelay(),
- s.getTcpNoDelay() == bool);
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(TCP_NODELAY);
- } catch (Exception e) {
- handleException(e, TCP_NODELAY);
- }
-
- try {
- Socket theSocket = new Socket();
- theSocket.close();
- theSocket.setTcpNoDelay(true);
- fail("SocketException was not thrown.");
- } catch(SocketException ioe) {
- //expected
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- }
- }
-
- /**
- * @tests java.net.Socket#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() throws IOException {
- // Test for method java.lang.String java.net.Socket.toString()
- int sport = startServer("SServer toString");
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost().getHostName(), sport,
- InetAddress.getLocalHost(), portNumber);
- assertTrue("Returned incorrect string: " + s.toString()
- + " localHost: " + InetAddress.getLocalHost(), s.toString()
- .equals(
- "Socket[addr=" + InetAddress.getLocalHost() + ",port="
- + s.getPort() + ",localport="
- + s.getLocalPort() + "]"));
- }
-
- /**
- * @tests java.net.Socket#shutdownInput()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "shutdownInput",
- args = {}
- )
- @AndroidOnly("RI returns wrong value for EOF")
- public void test_shutdownInput() throws Exception {
- InetAddress addr = InetAddress.getLocalHost();
- int port = Support_PortManager.getNextPort();
- ServerSocket serverSocket = new ServerSocket(port, 5, addr);
- Socket theSocket = new Socket(addr, port);
- Socket servSock = serverSocket.accept();
-
- InputStream theInput = theSocket.getInputStream();
- OutputStream theOutput = servSock.getOutputStream();
-
- // shutdown the input
- theSocket.shutdownInput();
-
- // send the regular data
- String sendString = new String("Test");
- theOutput.write(sendString.getBytes());
- theOutput.flush();
-
- // give things some time to settle
- Thread.sleep(1000);
-
- // RI fails here. It is a RI bug not to return 0 to indicate EOF
- assertEquals(0, theInput.available());
-
- theSocket.close();
- serverSocket.close();
-
- Socket socket = new Socket();
- socket.close();
- try {
- socket.shutdownInput();
- fail("IOException was not thrown.");
- } catch(IOException ioe) {
- //expected
- }
- }
-
- /**
- * @tests java.net.Socket#shutdownOutput()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "shutdownOutput",
- args = {}
- )
- public void test_shutdownOutput() throws IOException {
- InetAddress addr = InetAddress.getLocalHost();
- int port = Support_PortManager.getNextPort();
- ServerSocket serverSocket = new ServerSocket(port, 5, addr);
- Socket theSocket = new Socket(addr, port);
- Socket servSock = serverSocket.accept();
-
- InputStream theInput = theSocket.getInputStream();
- OutputStream theOutput = servSock.getOutputStream();
-
- // shutdown the output
- servSock.shutdownOutput();
-
- // send the regular data
- String sendString = new String("Test");
- try {
- theOutput.write(sendString.getBytes());
- theOutput.flush();
- fail("No exception when writing on socket with output shutdown");
- } catch (Exception e) {
- }
-
- theSocket.close();
- serverSocket.close();
-
- try {
- theSocket.shutdownInput();
- fail("IOException was not thrown.");
- } catch(IOException ioe) {
- //expected
- }
- }
-
- /**
- * @tests java.net.Socket#getLocalSocketAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalSocketAddress",
- args = {}
- )
- public void test_getLocalSocketAddress() throws IOException {
- // set up server connect and then validate that we get the right
- // response for the local address
- int sport = startServer("SServer getLocSocketAddress");
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- assertTrue(
- "Returned incorrect InetSocketAddress(1):"
- + s.getLocalSocketAddress().toString()
- + "Expected: "
- + (new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)).toString(), s
- .getLocalSocketAddress().equals(
- new InetSocketAddress(InetAddress
- .getLocalHost(), portNumber)));
- s.close();
-
- // now create a socket that is not bound and validate we get the
- // right answer
- Socket theSocket = new Socket();
- assertNull(
- "Returned incorrect InetSocketAddress -unbound socket- Expected null",
- theSocket.getLocalSocketAddress());
-
- // now bind the socket and make sure we get the right answer
- portNumber = Support_PortManager.getNextPort();
- theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber));
- assertTrue(
- "Returned incorrect InetSocketAddress(2):"
- + theSocket.getLocalSocketAddress().toString()
- + "Expected: "
- + (new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)).toString(), theSocket
- .getLocalSocketAddress().equals(
- new InetSocketAddress(InetAddress
- .getLocalHost(), portNumber)));
- theSocket.close();
-
- // now validate thet behaviour when the any address is returned
- s = new Socket();
- s.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
-
- String preferIPv4StackValue = System
- .getProperty("java.net.preferIPv4Stack");
- String preferIPv6AddressesValue = System
- .getProperty("java.net.preferIPv6Addresses");
- if (((preferIPv4StackValue == null) || preferIPv4StackValue
- .equalsIgnoreCase("false"))
- && (preferIPv6AddressesValue != null)
- && (preferIPv6AddressesValue.equals("true"))) {
- assertTrue(
- "ANY address not returned correctly with preferIPv6Addresses=true, preferIPv4Stack=false "
- + s.getLocalSocketAddress(),
- ((InetSocketAddress) s.getLocalSocketAddress())
- .getAddress() instanceof Inet6Address);
- } else {
- assertTrue(
- "ANY address not returned correctly with preferIPv6Addresses=true, preferIPv4Stack=true "
- + s.getLocalSocketAddress(),
- ((InetSocketAddress) s.getLocalSocketAddress())
- .getAddress() instanceof Inet4Address);
- }
- s.close();
-
- // now validate the same for getLocalAddress
- s = new Socket();
- s.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
- if (((preferIPv4StackValue == null) || preferIPv4StackValue
- .equalsIgnoreCase("false"))
- && (preferIPv6AddressesValue != null)
- && (preferIPv6AddressesValue.equals("true"))) {
- assertTrue(
- "ANY address not returned correctly with preferIPv6Addresses=true, preferIPv4Stack=false "
- + s.getLocalSocketAddress(),
- ((InetSocketAddress) s.getLocalSocketAddress())
- .getAddress() instanceof Inet6Address);
- } else {
- assertTrue(
- "ANY address not returned correctly with preferIPv6Addresses=true, preferIPv4Stack=true "
- + s.getLocalSocketAddress(),
- ((InetSocketAddress) s.getLocalSocketAddress())
- .getAddress() instanceof Inet4Address);
- }
- s.close();
- }
-
- /**
- * @tests java.net.Socket#getRemoteSocketAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRemoteSocketAddress",
- args = {}
- )
- public void test_getRemoteSocketAddress() throws IOException {
- // set up server connect and then validate that we get the right
- // response for the remote address
- int sport = startServer("SServer getLocRemoteAddress");
- int portNumber = Support_PortManager.getNextPort();
- s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- assertTrue("Returned incorrect InetSocketAddress(1):"
- + s.getLocalSocketAddress().toString(),
- s.getRemoteSocketAddress()
- .equals(
- new InetSocketAddress(InetAddress
- .getLocalHost(), sport)));
- s.close();
-
- // now create one that is not connect and validate that we get the
- // right answer
- Socket theSocket = new Socket();
- portNumber = Support_PortManager.getNextPort();
- theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber));
-
- assertNull("Returned incorrect InetSocketAddress -unconnected socket:"
- + "Expected: NULL", theSocket.getRemoteSocketAddress());
-
- // now connect and validate we get the right answer
- theSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(),
- sport));
- assertTrue("Returned incorrect InetSocketAddress(2):"
- + theSocket.getRemoteSocketAddress().toString(),
- theSocket.getRemoteSocketAddress()
- .equals(
- new InetSocketAddress(InetAddress
- .getLocalHost(), sport)));
- theSocket.close();
-
- }
-
- /**
- * @tests java.net.Socket#isBound()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isBound",
- args = {}
- )
- public void test_isBound() throws IOException {
- InetAddress addr = InetAddress.getLocalHost();
- int port = Support_PortManager.getNextPort();
- ServerSocket serverSocket = new ServerSocket(port, 5, addr);
- Socket theSocket = new Socket(addr, port);
- Socket servSock = serverSocket.accept();
- assertTrue("Socket indicated not bound when it should be (1)",
- theSocket.isBound());
- theSocket.close();
- serverSocket.close();
-
- // now do it with the new constructors and revalidate. Connect causes
- // the socket to be bound
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPort());
- theSocket = new Socket();
- assertFalse("Socket indicated bound when it was not (2)", theSocket
- .isBound());
- serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- theSocket.connect(theAddress);
- servSock = serverSocket.accept();
- assertTrue("Socket indicated not bound when it should be (2)",
- theSocket.isBound());
- theSocket.close();
- serverSocket.close();
-
- // now test when we bind explicitely
- InetSocketAddress theLocalAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPort());
- theSocket = new Socket();
- assertFalse("Socket indicated bound when it was not (3)", theSocket
- .isBound());
- theSocket.bind(theLocalAddress);
- assertTrue("Socket indicated not bound when it should be (3a)",
- theSocket.isBound());
- theSocket.close();
- assertTrue("Socket indicated not bound when it should be (3b)",
- theSocket.isBound());
- }
-
- /**
- * @tests java.net.Socket#isConnected()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isConnected",
- args = {}
- )
- public void test_isConnected() throws IOException {
- InetAddress addr = InetAddress.getLocalHost();
- int port = Support_PortManager.getNextPort();
- ServerSocket serverSocket = new ServerSocket(port, 5, addr);
- Socket theSocket = new Socket(addr, port);
- Socket servSock = serverSocket.accept();
- assertTrue("Socket indicated not connected when it should be",
- theSocket.isConnected());
- theSocket.close();
- serverSocket.close();
-
- // now do it with the new constructors and revalidate
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPort());
- theSocket = new Socket();
- assertFalse("Socket indicated connected when it was not", theSocket
- .isConnected());
- serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- theSocket.connect(theAddress);
- servSock = serverSocket.accept();
- assertTrue("Socket indicated not connected when it should be",
- theSocket.isConnected());
- theSocket.close();
- serverSocket.close();
- }
-
- /**
- * @tests java.net.Socket#isClosed()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isClosed",
- args = {}
- )
- public void test_isClosed() throws IOException {
- InetAddress addr = InetAddress.getLocalHost();
- int port = Support_PortManager.getNextPort();
- ServerSocket serverSocket = new ServerSocket(port, 5, addr);
- Socket theSocket = new Socket(addr, port);
- Socket servSock = serverSocket.accept();
-
- // validate isClosed returns expected values
- assertFalse("Socket should indicate it is not closed(1):", theSocket
- .isClosed());
- theSocket.close();
- assertTrue("Socket should indicate it is closed(1):", theSocket
- .isClosed());
-
- theSocket = new Socket(addr, port);
- assertFalse("Socket should indicate it is not closed(2):", theSocket
- .isClosed());
- theSocket.close();
- assertTrue("Socket should indicate it is closed(2):", theSocket
- .isClosed());
-
- // validate that isClosed works ok for sockets returned from
- // ServerSocket.accept()
- assertFalse("Server Socket should indicate it is not closed:", servSock
- .isClosed());
- servSock.close();
- assertTrue("Server Socket should indicate it is closed:", servSock
- .isClosed());
- }
-
- /**
- * @tests java.net.Socket#bind(java.net.SocketAddress)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "bind",
- args = {java.net.SocketAddress.class}
- )
- public void test_bindLjava_net_SocketAddress() throws IOException {
-
- class mySocketAddress extends SocketAddress {
-
- public mySocketAddress() {
- }
- }
-
- // Address we cannot bind to
- Socket theSocket = new Socket();
- try {
- theSocket.bind(new InetSocketAddress(InetAddress
- .getByAddress(Support_Configuration.nonLocalAddressBytes),
- Support_PortManager.getNextPort()));
- fail("No exception when binding to bad address:"
- + theSocket.getLocalSocketAddress().toString());
- } catch (IOException ex) {
- }
- theSocket.close();
-
- // now create a socket that is not bound and then bind it
- theSocket = new Socket();
- int portNumber = Support_PortManager.getNextPort();
- theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber));
-
- // validate that the localSocketAddress reflects the address we
- // bound to
- assertTrue(
- "Local address not correct after bind:"
- + theSocket.getLocalSocketAddress().toString()
- + " Expected: "
- + (new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)).toString(), theSocket
- .getLocalSocketAddress().equals(
- new InetSocketAddress(InetAddress
- .getLocalHost(), portNumber)));
-
- // make sure we can now connect and that connections appear to come
- // from the address we bound to.
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPort());
- ServerSocket serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- theSocket.connect(theAddress);
- Socket servSock = serverSocket.accept();
- assertTrue(
- "Returned Remote address from server connected to does not match expected local address:"
- + servSock.getRemoteSocketAddress().toString()
- + " Expected: "
- + (new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)).toString(), servSock
- .getRemoteSocketAddress().equals(
- new InetSocketAddress(InetAddress
- .getLocalHost(), portNumber)));
- theSocket.close();
- servSock.close();
- serverSocket.close();
-
- // validate if we pass in null that it picks an address for us and
- // all is ok
- theSocket = new Socket();
- theSocket.bind(null);
- assertNotNull("Bind with null did not work", theSocket
- .getLocalSocketAddress());
- theSocket.close();
-
- // now check the error conditions
-
- // Address that we have allready bound to
- theSocket = new Socket();
- Socket theSocket2 = new Socket();
- try {
- theAddress = new InetSocketAddress(InetAddress.getLocalHost(),
- Support_PortManager.getNextPort());
- theSocket.bind(theAddress);
- theSocket2.bind(theAddress);
- fail("No exception binding to address that is not available");
- } catch (IOException ex) {
- }
- theSocket.close();
- theSocket2.close();
-
- // unsupported SocketAddress subclass
- theSocket = new Socket();
- try {
- theSocket.bind(new mySocketAddress());
- fail("No exception when binding using unsupported SocketAddress subclass");
- } catch (IllegalArgumentException ex) {
- }
- theSocket.close();
- }
-
- /**
- * @tests java.net.Socket#bind(java.net.SocketAddress)
- */
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- notes = "Checks bind on proxy.",
- method = "bind",
- args = {java.net.SocketAddress.class}
- )
- public void test_bindLjava_net_SocketAddress_Proxy() throws IOException {
- //The Proxy will not impact on the bind operation.It can be assigned with any address.
- Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 0));
- Socket socket = new Socket(proxy);
-
- try {
- InetAddress address = InetAddress.getByName("localhost");
- int port = 0;
- socket.bind(new InetSocketAddress(address, port));
-
- assertEquals(address, socket.getLocalAddress());
- assertTrue(port!=socket.getLocalPort());
-
- } finally {
- socket.close();
- }
- }
-
- /**
- * @tests java.net.Socket#connect(java.net.SocketAddress)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "connect",
- args = {java.net.SocketAddress.class}
- )
- public void test_connectLjava_net_SocketAddress() throws Exception {
- // needed for some tests
- class mySocketAddress extends SocketAddress {
-
- public mySocketAddress() {
- }
- }
-
- class SocketCloser extends Thread {
-
- int timeout = 0;
-
- Socket theSocket = null;
-
- public void run() {
- try {
- Thread.sleep(timeout);
- theSocket.close();
- } catch (Exception e) {
- }
- ;
- return;
- }
-
- public SocketCloser(int timeout, Socket theSocket) {
- this.timeout = timeout;
- this.theSocket = theSocket;
- }
- }
-
- // start by validating the error checks
- int portNumber = Support_PortManager.getNextPort();
- Socket theSocket = null;
- ServerSocket serverSocket = null;
- SocketAddress theAddress = null;
- SocketAddress nonConnectableAddress = null;
- SocketAddress nonReachableAddress = null;
- SocketAddress invalidType = null;
- // byte[] theBytes = {-1,-1,-1,-1};
- byte[] theBytes = { 0, 0, 0, 0 };
- theAddress = new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber);
- nonConnectableAddress = new InetSocketAddress(InetAddress
- .getByAddress(theBytes), portNumber);
- nonReachableAddress = new InetSocketAddress(InetAddress
- .getByName(Support_Configuration.ResolvedNotExistingHost),
- portNumber);
-
- invalidType = new mySocketAddress();
-
- try {
- theSocket = new Socket();
- theSocket.connect(null);
- fail("No exception after null address passed in");
- } catch (Exception e) {
- assertTrue("Wrong exception null address passed in: "
- + e.toString(), (e instanceof IllegalArgumentException));
- }
-
- try {
- theSocket = new Socket();
- theSocket.connect(invalidType);
- fail("No exception when invalid socket address type passed in: ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when when invalid socket address type passed in: "
- + e.toString(),
- (e instanceof IllegalArgumentException));
- }
-
- try {
- theSocket = new Socket();
- theSocket.connect(nonConnectableAddress);
- fail("No exception when non Connectable Address passed in: ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when non Connectable Address passed in: "
- + e.toString(), (e instanceof ConnectException));
- }
-
- // now validate that we get a connect exception if we try to connect to
- // an address on which nobody is listening
- try {
- theSocket = new Socket();
- theSocket.connect(theAddress);
- theSocket.close();
- fail("No exception when connecting to address nobody listening on: ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when connecting to address nobody listening on: "
- + e.toString(), (e instanceof ConnectException));
- }
-
- // now validate that we can acutally connect when sombody is listening
- theSocket = new Socket();
- serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- theSocket.connect(theAddress);
- theSocket.close();
- serverSocket.close();
-
- // now validate that we can acutally connect when sombody is listening
- theSocket = new Socket();
- serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- theSocket.connect(theAddress);
-
- // validate that when a socket is connected that it answers
- // correctly to related queries
- assertTrue("Socket did not returned connected when it is: ", theSocket
- .isConnected());
- assertFalse("Socket returned closed when it should be connected ",
- theSocket.isClosed());
- assertTrue("Socket returned not bound when it should be: ", theSocket
- .isBound());
- assertFalse(
- "Socket returned input Shutdown when it should be connected ",
- theSocket.isInputShutdown());
- assertFalse(
- "Socket returned output Shutdown when it should be connected ",
- theSocket.isOutputShutdown());
- assertTrue("Local port on connected socket was 0", theSocket
- .getLocalPort() != 0);
- theSocket.close();
- serverSocket.close();
-
- // now validate that we get the right exception if we connect when we
- // are already connected
- try {
- theSocket = new Socket();
- serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- theSocket.connect(theAddress);
- theSocket.connect(theAddress);
- theSocket.close();
- serverSocket.close();
- fail("No exception when we try to connect on a connected socket: ");
-
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when connecting on socket that is allready connected"
- + e.toString(), (e instanceof SocketException));
- assertFalse(
- "Wrong exception when connecting on socket that is allready connected"
- + e.toString(),
- (e instanceof SocketTimeoutException));
- try {
- theSocket.close();
- serverSocket.close();
- } catch (Exception e2) {
- }
-
- }
-
- // now validate that connected socket can be used to read/write
- theSocket = new Socket();
- serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- theSocket.connect(theAddress);
- Socket servSock = serverSocket.accept();
- InputStream theInput = theSocket.getInputStream();
- OutputStream theOutput = servSock.getOutputStream();
- InputStream theInput2 = servSock.getInputStream();
- OutputStream theOutput2 = theSocket.getOutputStream();
-
- String sendString = new String("Test");
- theOutput.write(sendString.getBytes());
- theOutput.flush();
-
- Thread.sleep(1000);
-
- int totalBytesRead = 0;
- byte[] myBytes = new byte[100];
- while (theInput.available() > 0) {
- int bytesRead = theInput.read(myBytes, totalBytesRead,
- myBytes.length - totalBytesRead);
- totalBytesRead = totalBytesRead + bytesRead;
- }
-
- String receivedString = new String(myBytes, 0, totalBytesRead);
- assertTrue("Could not recv on socket connected with timeout:"
- + receivedString + ":" + sendString, receivedString
- .equals(sendString));
-
- sendString = new String("SEND - Test");
- theOutput2.write(sendString.getBytes());
- theOutput2.flush();
- Thread.sleep(1000);
-
- totalBytesRead = 0;
- myBytes = new byte[100];
- while (theInput2.available() > 0) {
- int bytesRead = theInput2.read(myBytes, totalBytesRead,
- myBytes.length - totalBytesRead);
- totalBytesRead = totalBytesRead + bytesRead;
- }
-
- receivedString = new String(myBytes, 0, totalBytesRead);
- assertTrue("Could not send on socket connected with timeout:"
- + receivedString + ":" + sendString, receivedString
- .equals(sendString));
-
- theSocket.close();
- serverSocket.close();
-
- SocketChannel channel = SocketChannel.open();
- channel.configureBlocking(false);
- Socket socket = channel.socket();
- int port = Support_PortManager.getNextPort();
- try {
- socket.connect( new InetSocketAddress(InetAddress.getLocalHost(),
- Support_PortManager.getNextPort()));
- fail("IllegalBlockingModeException was not thrown.");
- } catch(IllegalBlockingModeException ibme) {
- //expected
- }
- }
-
- /**
- * @tests java.net.Socket#connect(java.net.SocketAddress, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "connect",
- args = {java.net.SocketAddress.class, int.class}
- )
- public void test_connectLjava_net_SocketAddressI() throws Exception {
-
- // needed for some tests
- class mySocketAddress extends SocketAddress {
-
- public mySocketAddress() {
- }
- }
-
- class SocketCloser extends Thread {
-
- int timeout = 0;
-
- Socket theSocket = null;
-
- public void run() {
- try {
- Thread.sleep(timeout);
- theSocket.close();
- } catch (Exception e) {
- }
- return;
- }
-
- public SocketCloser(int timeout, Socket theSocket) {
- this.timeout = timeout;
- this.theSocket = theSocket;
- }
- }
-
- class SocketConnector extends Thread {
-
- int timeout = 0;
-
- Socket theSocket = null;
-
- SocketAddress address = null;
-
- public void run() {
- try {
- theSocket.connect(address, timeout);
- } catch (Exception e) {
- }
-
- return;
- }
-
- public SocketConnector(int timeout, Socket theSocket,
- SocketAddress address) {
- this.timeout = timeout;
- this.theSocket = theSocket;
- this.address = address;
- }
- }
-
- // start by validating the error checks
- int portNumber = Support_PortManager.getNextPort();
- Socket theSocket = null;
- ServerSocket serverSocket = null;
- SocketAddress theAddress = null;
- SocketAddress nonConnectableAddress = null;
- SocketAddress nonReachableAddress = null;
- SocketAddress nonListeningAddress = null;
- SocketAddress invalidType = null;
- byte[] theBytes = { 0, 0, 0, 0 };
-
- theAddress = new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber);
- nonConnectableAddress = new InetSocketAddress(InetAddress
- .getByAddress(theBytes), portNumber);
- nonReachableAddress = new InetSocketAddress(InetAddress
- .getByName(Support_Configuration.ResolvedNotExistingHost),
- portNumber);
- // make sure we get another port
- Thread.sleep(7000);
- nonListeningAddress = new InetSocketAddress(InetAddress.getLocalHost(),
- Support_PortManager.getNextPort());
- invalidType = new mySocketAddress();
-
- try {
- theSocket = new Socket();
- theSocket.connect(theAddress, -100);
- fail("No exception after negative timeout passed in");
- } catch (Exception e) {
- assertTrue("Wrong exception when negative timeout passed in: "
- + e.toString(), (e instanceof IllegalArgumentException));
- }
-
- try {
- theSocket = new Socket();
- theSocket.connect(null, 0);
- fail("No exception after null address passed in");
- } catch (Exception e) {
- assertTrue("Wrong exception null address passed in: "
- + e.toString(), (e instanceof IllegalArgumentException));
- }
-
- try {
- theSocket = new Socket();
- theSocket.connect(invalidType, 100000);
- fail("No exception when invalid socket address type passed in: ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when when invalid socket address type passed in: "
- + e.toString(),
- (e instanceof IllegalArgumentException));
- }
-
- try {
- theSocket = new Socket();
- theSocket.connect(nonConnectableAddress, 100000);
- fail("No exception when non Connectable Address passed in: ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when non Connectable Address passed in: "
- + e.toString(), (e instanceof SocketException));
- }
-
- // now validate that we get a connect exception if we try to connect to
- // an address on which nobody is listening
- try {
- theSocket = new Socket();
- theSocket.connect(theAddress, 0);
- theSocket.close();
- fail("No timeout:No exception when connecting to address nobody listening on: ");
- } catch (Exception e) {
- assertTrue(
- "No timeout:Wrong exception when connecting to address nobody listening on: "
- + e.toString(), (e instanceof ConnectException));
- }
-
- // now validate that we can acutally connect when sombody is listening
- theSocket = new Socket();
- serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- theSocket.connect(theAddress, 0);
- theSocket.close();
- serverSocket.close();
-
- // now validate that we get a connect exception if we try to connect to
- // an address on which nobody is listening
- try {
- theSocket = new Socket();
- theSocket.connect(nonListeningAddress, 100000);
- theSocket.close();
- fail("No exception when connecting to address nobody listening on: ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when connecting to address nobody listening on: "
- + e.toString(), (e instanceof ConnectException));
- }
-
- // now validate that we get a interrupted exception if we try to connect
- // to an address on which nobody is accepting connections and the
- // timeout expired
- try {
- theSocket = new Socket();
- theSocket.connect(nonReachableAddress, 200);
- theSocket.close();
- fail("No interrupted exception when connecting to address nobody listening on with short timeout 200: ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when connecting to address nobody listening on with short timeout 200: "
- + e.toString(),
- (e instanceof SocketTimeoutException));
- }
-
- // now validate that we get a interrupted exception if we try to connect
- // to an address on which nobody is accepting connections and the
- // timeout expired
- try {
- theSocket = new Socket();
- theSocket.connect(nonReachableAddress, 40);
- theSocket.close();
- fail("No interrupted exception when connecting to address nobody listening on with short timeout 40: ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when connecting to address nobody listening on with short timeout 40: "
- + e.toString(),
- (e instanceof SocketTimeoutException));
- }
-
- // now validate that we can acutally connect when sombody is listening
- new InetSocketAddress(InetAddress.getLocalHost(), Support_PortManager
- .getNextPort());
- theSocket = new Socket();
- serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- theSocket.connect(theAddress, 100000);
-
- // validate that when a socket is connected that it answers
- // correctly to related queries
- assertTrue("Socket did not returned connected when it is: ", theSocket
- .isConnected());
- assertFalse("Socket returned closed when it should be connected ",
- theSocket.isClosed());
- assertTrue("Socket returned not bound when it should be: ", theSocket
- .isBound());
- assertFalse(
- "Socket returned input Shutdown when it should be connected ",
- theSocket.isInputShutdown());
- assertFalse(
- "Socket returned output Shutdown when it should be connected ",
- theSocket.isOutputShutdown());
- assertTrue("Local port on connected socket was 0", theSocket
- .getLocalPort() != 0);
- theSocket.close();
- serverSocket.close();
-
- // now validate that we get the right exception if we connect when we
- // are already connected
- try {
- new InetSocketAddress(InetAddress.getLocalHost(),
- Support_PortManager.getNextPort());
- theSocket = new Socket();
- serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- theSocket.connect(theAddress, 100000);
- theSocket.connect(theAddress, 100000);
- theSocket.close();
- serverSocket.close();
- fail("No exception when we try to connect on a connected socket: ");
-
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when connecting on socket that is allready connected"
- + e.toString(), (e instanceof SocketException));
- assertFalse(
- "Wrong exception when connecting on socket that is allready connected"
- + e.toString(),
- (e instanceof SocketTimeoutException));
- try {
- theSocket.close();
- serverSocket.close();
- } catch (Exception e2) {
- }
-
- }
-
- // now validate that connected socket can be used to read/write
- new InetSocketAddress(InetAddress.getLocalHost(), Support_PortManager
- .getNextPort());
- theSocket = new Socket();
- serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- theSocket.connect(theAddress, 100000);
- Socket servSock = serverSocket.accept();
- InputStream theInput = theSocket.getInputStream();
- OutputStream theOutput = servSock.getOutputStream();
- InputStream theInput2 = servSock.getInputStream();
- OutputStream theOutput2 = theSocket.getOutputStream();
-
- String sendString = new String("Test");
- theOutput.write(sendString.getBytes());
- theOutput.flush();
-
- Thread.sleep(1000);
-
- int totalBytesRead = 0;
- byte[] myBytes = new byte[100];
- while (theInput.available() > 0) {
- int bytesRead = theInput.read(myBytes, totalBytesRead,
- myBytes.length - totalBytesRead);
- totalBytesRead = totalBytesRead + bytesRead;
- }
-
- String receivedString = new String(myBytes, 0, totalBytesRead);
- assertTrue("Could not recv on socket connected with timeout:"
- + receivedString + ":" + sendString, receivedString
- .equals(sendString));
-
- sendString = new String("SEND - Test");
- theOutput2.write(sendString.getBytes());
- theOutput2.flush();
-
- totalBytesRead = 0;
- myBytes = new byte[100];
- Thread.sleep(1000);
- while (theInput2.available() > 0) {
- int bytesRead = theInput2.read(myBytes, totalBytesRead,
- myBytes.length - totalBytesRead);
- totalBytesRead = totalBytesRead + bytesRead;
- }
-
- receivedString = new String(myBytes, 0, totalBytesRead);
- assertTrue("Could not send on socket connected with timeout:"
- + receivedString + ":" + sendString, receivedString
- .equals(sendString));
-
- theSocket.close();
- serverSocket.close();
-
- // now try to set options while we are connecting
- theSocket = new Socket();
- SocketConnector connector = new SocketConnector(5000, theSocket,
- nonReachableAddress);
- connector.start();
- theSocket.setSoTimeout(100);
- Thread.sleep(10);
- assertEquals("Socket option not set during connect: 10 ", 100,
- theSocket.getSoTimeout());
- Thread.sleep(50);
- theSocket.setSoTimeout(200);
- assertEquals("Socket option not set during connect: 50 ", 200,
- theSocket.getSoTimeout());
- Thread.sleep(5000);
- theSocket.close();
-
- SocketChannel channel = SocketChannel.open();
- channel.configureBlocking(false);
- Socket socket = channel.socket();
- int port = Support_PortManager.getNextPort();
- try {
- socket.connect( new InetSocketAddress(InetAddress.getLocalHost(),
- Support_PortManager.getNextPort()), port);
- fail("IllegalBlockingModeException was not thrown.");
- } catch(IllegalBlockingModeException ibme) {
- //expected
- }
- }
-
- /**
- * @tests java.net.Socket#isInputShutdown()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isInputShutdown",
- args = {}
- )
- public void test_isInputShutdown() throws IOException {
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPort());
- Socket theSocket = new Socket();
- ServerSocket serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- theSocket.connect(theAddress);
- Socket servSock = serverSocket.accept();
- InputStream theInput = theSocket.getInputStream();
- OutputStream theOutput = servSock.getOutputStream();
-
- // make sure we get the right answer with newly connected socket
- assertFalse("Socket indicated input shutdown when it should not have",
- theSocket.isInputShutdown());
-
- // shutdown the output
- theSocket.shutdownInput();
-
- // make sure we get the right answer once it is shut down
- assertTrue(
- "Socket indicated input was NOT shutdown when it should have been",
- theSocket.isInputShutdown());
-
- theSocket.close();
- serverSocket.close();
-
- // make sure we get the right answer for closed sockets
- assertFalse(
- "Socket indicated input was shutdown when socket was closed",
- servSock.isInputShutdown());
-
- }
-
- /**
- * @tests java.net.Socket#isOutputShutdown()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isOutputShutdown",
- args = {}
- )
- public void test_isOutputShutdown() throws IOException {
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPort());
- Socket theSocket = new Socket();
- ServerSocket serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- theSocket.connect(theAddress);
- Socket servSock = serverSocket.accept();
- InputStream theInput = theSocket.getInputStream();
- OutputStream theOutput = servSock.getOutputStream();
-
- // make sure we get the right answer with newly connected socket
- assertFalse("Socket indicated output shutdown when it should not have",
- servSock.isOutputShutdown());
-
- // shutdown the output
- servSock.shutdownOutput();
-
- // make sure we get the right answer once it is shut down
- assertTrue(
- "Socket indicated output was NOT shutdown when it should have been",
- servSock.isOutputShutdown());
-
- theSocket.close();
- serverSocket.close();
-
- // make sure we get the right answer for closed sockets
- assertFalse(
- "Socket indicated output was output shutdown when the socket was closed",
- theSocket.isOutputShutdown());
-
- }
-
- /**
- * @tests java.net.Socket#setReuseAddress(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setReuseAddress",
- args = {boolean.class}
- )
- public void test_setReuseAddressZ() {
-
- try {
- InetAddress allAddresses[] = InetAddress.getAllByName(InetAddress
- .getLocalHost().getHostName());
- if (allAddresses.length > 1) {
-
- InetSocketAddress theAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), Support_PortManager
- .getNextPort());
- ServerSocket serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
-
- // try to bind to port address that is already in use with
- // reuseAddress = false.
- // On windows platforms the bind is allowed even then
- // reUseAddress is false (ONLY IF BOTH SOCKETS
- // ARE IPV4 Sockets) so our test uses the platform to determine
- // what the expected result is. It seems that on linux
- // platforms we also don't get an exception.
- InetSocketAddress theLocalAddress = new InetSocketAddress(
- (InetAddress) allAddresses[1], Support_PortManager
- .getNextPort());
- InetSocketAddress theOtherLocalAddress = new InetSocketAddress(
- (InetAddress) allAddresses[0], theLocalAddress
- .getPort());
- Socket theSocket = new Socket();
- theSocket.setReuseAddress(false);
- theSocket.bind(theLocalAddress);
- Socket theSocket2 = null;
- String platform = System.getProperty("os.name");
- try {
- theSocket2 = new Socket();
- theSocket2.setReuseAddress(false);
- theSocket2.bind(theOtherLocalAddress);
-
- if ((!platform.startsWith("Linux"))
- && ((!platform.startsWith("Windows")) ||
- // for windows we don't get an exception with
- // setreuse set to false unless one of the
- // addresses we bind to is an IPv6 address and we
- // are therefore using the IPv6 stack.
- !((((InetAddress) allAddresses[0]) instanceof Inet4Address) && (((InetAddress) allAddresses[1]) instanceof Inet4Address)))) {
- fail("No exception when setReuseAddress is false and we bind:"
- + theLocalAddress.toString()
- + ":"
- + theOtherLocalAddress.toString());
- }
- } catch (IOException ex) {
- if ((platform.startsWith("Linux"))
- || ((platform.startsWith("Windows")) && ((((InetAddress) allAddresses[0]) instanceof Inet4Address) && (((InetAddress) allAddresses[1]) instanceof Inet4Address)))) {
- fail("Got unexpected exception when binding with setReuseAddress false on windows platform:"
- + theAddress.toString() + ":" + ex.toString());
- }
- }
- theSocket.close();
- theSocket2.close();
-
- // try to bind to port that is allready in use with reuseAddress
- // = true
- theLocalAddress = new InetSocketAddress(
- (InetAddress) allAddresses[0], Support_PortManager
- .getNextPort());
- theOtherLocalAddress = new InetSocketAddress(
- (InetAddress) allAddresses[1], theLocalAddress
- .getPort());
-
- theSocket = new Socket();
- theSocket.setReuseAddress(true);
- theSocket.bind(theLocalAddress);
- try {
- theSocket2 = new Socket();
- theSocket2.setReuseAddress(true);
- theSocket2.bind(theOtherLocalAddress);
- theSocket2.close();
- } catch (IOException ex) {
- fail("IOException when setReuseAddress is true and we bind :"
- + ex.toString());
- }
- theSocket.close();
- serverSocket.close();
-
- // try with default behavior which should be the same on all
- // platforms
- theLocalAddress = new InetSocketAddress(
- (InetAddress) allAddresses[0], Support_PortManager
- .getNextPort());
- theOtherLocalAddress = new InetSocketAddress(
- (InetAddress) allAddresses[1], theLocalAddress
- .getPort());
-
- theSocket = new Socket();
- theSocket.bind(theLocalAddress);
- try {
- theSocket2 = new Socket();
- theSocket2.bind(theOtherLocalAddress);
- theSocket2.close();
- if ((!platform.startsWith("Linux"))
- && ((!platform.startsWith("Windows")) || !((((InetAddress) allAddresses[0]) instanceof Inet4Address) && (((InetAddress) allAddresses[1]) instanceof Inet4Address)))) {
- fail("No exception when setReuseAddress is default and we bind:"
- + theLocalAddress.toString()
- + ":"
- + theOtherLocalAddress.toString());
- }
- } catch (IOException ex) {
- if ((platform.startsWith("Linux"))
- || ((platform.startsWith("Windows")) && ((((InetAddress) allAddresses[0]) instanceof Inet4Address) && (((InetAddress) allAddresses[1]) instanceof Inet4Address)))) {
- fail("Got unexpected exception when binding with setReuseAddress default on windows platform:"
- + theAddress.toString() + ":" + ex.toString());
- }
- }
- theSocket.close();
- serverSocket.close();
-
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
- }
- } catch (Exception e) {
- handleException(e, SO_REUSEADDR);
- }
-
- try {
- Socket theSocket = new Socket();
- theSocket.close();
- theSocket.setReuseAddress(true);
- fail("SocketException was not thrown.");
- } catch(SocketException ioe) {
- //expected
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- }
- }
-
- /**
- * @tests java.net.Socket#getReuseAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getReuseAddress",
- args = {}
- )
- public void test_getReuseAddress() {
- try {
- Socket theSocket = new Socket();
- theSocket.setReuseAddress(true);
- assertTrue("getReuseAddress false when it should be true",
- theSocket.getReuseAddress());
- theSocket.setReuseAddress(false);
- assertFalse("getReuseAddress true when it should be False",
- theSocket.getReuseAddress());
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
- } catch (Exception e) {
- handleException(e, SO_REUSEADDR);
- }
-
- try {
- Socket newSocket = new Socket();
- newSocket.close();
- try {
- newSocket.getReuseAddress();
- fail("SocketException was not thrown.");
- } catch(SocketException e) {
- //expected
- }
- } catch(Exception e) {
- fail("Unexpected exception.");
- }
- }
-
- /**
- * @tests java.net.Socket#setOOBInline(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setOOBInline",
- args = {boolean.class}
- )
- public void test_setOOBInlineZ() {
- // mostly tested in getOOBInline. Just set to make sure call works ok
- try {
- new InetSocketAddress(InetAddress.getLocalHost(),
- Support_PortManager.getNextPort());
- Socket theSocket = new Socket();
- theSocket.setOOBInline(true);
- assertTrue("expected OOBIline to be true", theSocket.getOOBInline());
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_OOBINLINE);
- } catch (Exception e) {
- handleException(e, SO_OOBINLINE);
- }
-
- try {
- Socket theSocket = new Socket();
- theSocket.close();
- theSocket.setOOBInline(true);
- fail("SocketException was not thrown.");
- } catch(SocketException ioe) {
- //expected
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- }
- }
-
- /**
- * @tests java.net.Socket#getOOBInline()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getOOBInline",
- args = {}
- )
- public void test_getOOBInline() {
-
- try {
- new InetSocketAddress(InetAddress.getLocalHost(),
- Support_PortManager.getNextPort());
- Socket theSocket = new Socket();
-
- // validate that value reflects what we set it to true after true,
- // false after false and false after false false
- theSocket.setOOBInline(true);
- assertTrue("expected OOBIline to be true", theSocket.getOOBInline());
- theSocket.setOOBInline(false);
- assertFalse("expected OOBIline to be true", theSocket
- .getOOBInline());
- theSocket.setOOBInline(false);
- assertFalse("expected OOBIline to be true", theSocket
- .getOOBInline());
- theSocket.close();
- try {
- theSocket.getOOBInline();
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_OOBINLINE);
-
- } catch (Exception e) {
- handleException(e, SO_OOBINLINE);
- }
- }
-
- /**
- * @tests java.net.Socket#setTrafficClass(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setTrafficClass",
- args = {int.class}
- )
- public void test_setTrafficClassI() {
- try {
- int IPTOS_LOWCOST = 0x2;
- int IPTOS_RELIABILTY = 0x4;
- int IPTOS_THROUGHPUT = 0x8;
- int IPTOS_LOWDELAY = 0x10;
-
- new InetSocketAddress(InetAddress.getLocalHost(),
- Support_PortManager.getNextPort());
- Socket theSocket = new Socket();
-
- // validate that value set must be between 0 and 255
- try {
- theSocket.setTrafficClass(256);
- fail("No exception was thrown when traffic class set to 256");
- } catch (IllegalArgumentException e) {
- }
-
- try {
- theSocket.setTrafficClass(-1);
- fail("No exception was thrown when traffic class set to -1");
- } catch (IllegalArgumentException e) {
- }
-
- // now validate that we can set it to some good values
- theSocket.setTrafficClass(IPTOS_LOWCOST);
- theSocket.setTrafficClass(IPTOS_THROUGHPUT);
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(IP_TOS);
- } catch (Exception e) {
- handleException(e, IP_TOS);
- }
-
- try {
- Socket theSocket = new Socket();
- theSocket.close();
- theSocket.setTrafficClass(0);
- fail("SocketException was not thrown.");
- } catch(SocketException ioe) {
- //expected
- } catch(IOException ioe) {
- fail("IOException was thrown.");
- }
- }
-
- /**
- * @tests java.net.Socket#getTrafficClass()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "SocketException checking missing.",
- method = "getTrafficClass",
- args = {}
- )
- public void test_getTrafficClass() {
- try {
- int IPTOS_LOWCOST = 0x2;
- int IPTOS_RELIABILTY = 0x4;
- int IPTOS_THROUGHPUT = 0x8;
- int IPTOS_LOWDELAY = 0x10;
-
- new InetSocketAddress(InetAddress.getLocalHost(),
- Support_PortManager.getNextPort());
- Socket theSocket = new Socket();
-
- /*
- * we cannot actually check that the values are set as if a platform
- * does not support the option then it may come back unset even
- * though we set it so just get the value to make sure we can get it
- */
- int trafficClass = theSocket.getTrafficClass();
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(IP_TOS);
- } catch (Exception e) {
- handleException(e, IP_TOS);
- }
- }
-
- /**
- * @tests java.net.Socket#getChannel()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getChannel",
- args = {}
- )
- public void test_getChannel() throws Exception {
- assertNull(new Socket().getChannel());
-
- SocketChannel channel = SocketChannel.open();
- Socket socket = channel.socket();
- assertEquals(channel, socket.getChannel());
- socket.close();
- channel.close();
- }
-
- /**
- * @tests java.net.Socket#sendUrgentData(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sendUrgentData",
- args = {int.class}
- )
- public void test_sendUrgentDataI() {
-
- // Some platforms may not support urgent data in this case we will not
- // run these tests. For now run on all platforms until we find those
- // that do not support urgent data
- String platform = System.getProperty("os.name");
- if (!platform.equals("Dummy")) {
- // validate that when OOBInline is false that any urgent data
- // is silently ignored
- String urgentData = "U";
- try {
- InetSocketAddress theAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), Support_PortManager
- .getNextPort());
- Socket theSocket = new Socket();
- ServerSocket serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- theSocket.connect(theAddress);
- Socket servSock = serverSocket.accept();
- InputStream theInput = theSocket.getInputStream();
- OutputStream theOutput = servSock.getOutputStream();
-
- // send the regular data
- String sendString = new String("Test");
- theOutput.write(sendString.getBytes());
- theOutput.flush();
-
- // send the urgent data which should not be received
- theSocket.setOOBInline(false);
- servSock.sendUrgentData(urgentData.getBytes()[0]);
- theOutput.write(sendString.getBytes());
- theOutput.flush();
-
- // give things some time to settle
- Thread.sleep(1000);
-
- int totalBytesRead = 0;
- byte[] myBytes = new byte[100];
- while (theInput.available() > 0) {
- int bytesRead = theInput.read(myBytes, totalBytesRead,
- myBytes.length - totalBytesRead);
- totalBytesRead = totalBytesRead + bytesRead;
- }
-
- String receivedString = new String(myBytes, 0, totalBytesRead);
- //assertTrue("Urgent Data seems to have been received:"
- // + receivedString + ":" + sendString, receivedString
- // .equals(sendString + sendString));
-
- theSocket.close();
- serverSocket.close();
-
- // now validate that urgent data is received as expected. Expect
- // that it should be between the two writes.
- theAddress = new InetSocketAddress(InetAddress.getLocalHost(),
- Support_PortManager.getNextPort());
- theSocket = new Socket();
- serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- theSocket.connect(theAddress);
- servSock = serverSocket.accept();
- theInput = theSocket.getInputStream();
- theOutput = servSock.getOutputStream();
-
- // send the regular data
- sendString = new String("Test - Urgent Data");
- theOutput.write(sendString.getBytes());
- theOutput.flush();
-
- // send the urgent data which should be received
- theSocket.setOOBInline(true);
- servSock.sendUrgentData(urgentData.getBytes()[0]);
-
- theOutput.write(sendString.getBytes());
- theOutput.flush();
-
- Thread.sleep(1000);
-
- totalBytesRead = 0;
- myBytes = new byte[100];
- while (theInput.available() > 0) {
- int bytesRead = theInput.read(myBytes, totalBytesRead,
- myBytes.length - totalBytesRead);
- totalBytesRead = totalBytesRead + bytesRead;
- }
-
- receivedString = new String(myBytes, 0, totalBytesRead);
- assertTrue("Urgent Data was not received with one urgent byte:"
- + receivedString + ":" + sendString + urgentData
- + sendString, receivedString.equals(sendString
- + urgentData + sendString));
-
- theSocket.close();
- serverSocket.close();
-
- // now test case where we try to send two urgent bytes.
- theAddress = new InetSocketAddress(InetAddress.getLocalHost(),
- Support_PortManager.getNextPort());
- theSocket = new Socket();
- serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- theSocket.connect(theAddress);
- servSock = serverSocket.accept();
- theInput = theSocket.getInputStream();
- theOutput = servSock.getOutputStream();
-
- // send the regular data
- sendString = new String("Test - Urgent Data");
- theOutput.write(sendString.getBytes());
- theOutput.flush();
-
- // send the urgent data which should not be received
- theSocket.setOOBInline(true);
- servSock.sendUrgentData(urgentData.getBytes()[0]);
- servSock.sendUrgentData(urgentData.getBytes()[0]);
-
- theOutput.write(sendString.getBytes());
- theOutput.flush();
-
- Thread.sleep(1000);
-
- totalBytesRead = 0;
- myBytes = new byte[100];
- while (theInput.available() > 0) {
- int bytesRead = theInput.read(myBytes, totalBytesRead,
- myBytes.length - totalBytesRead);
- totalBytesRead = totalBytesRead + bytesRead;
- }
-
- receivedString = new String(myBytes, 0, totalBytesRead);
- assertTrue(
- "Did not get right byte of urgent data when two sent:"
- + receivedString + ":" + sendString
- + urgentData + urgentData + sendString,
- receivedString.equals(sendString + urgentData
- + urgentData + sendString));
-
- theSocket.close();
- serverSocket.close();
-
- /*
- * TODO : These do not currently pass on XP SP2 and Server 2003
- */
- if (!platform.startsWith("Windows")) {
- // now test the case were we send turn the OOBInline on/off
- theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPort());
- theSocket = new Socket();
- serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- theSocket.connect(theAddress);
- servSock = serverSocket.accept();
- theInput = theSocket.getInputStream();
- theOutput = servSock.getOutputStream();
-
- // send the regular data
- sendString = new String("Test - Urgent Data");
- theOutput.write(sendString.getBytes());
- theOutput.flush();
-
- // send the urgent data which should be received
- theSocket.setOOBInline(true);
- servSock.sendUrgentData(urgentData.getBytes()[0]);
-
- theOutput.write(sendString.getBytes());
- theOutput.flush();
-
- Thread.sleep(1000);
-
- totalBytesRead = 0;
- myBytes = new byte[100];
- while (theInput.available() > 0) {
- int bytesRead = theInput.read(myBytes, totalBytesRead,
- myBytes.length - totalBytesRead);
- totalBytesRead = totalBytesRead + bytesRead;
- }
-
- receivedString = new String(myBytes, 0, totalBytesRead);
- assertTrue(
- "Did not get urgent data when turning on/off(1):"
- + receivedString + ":" + sendString
- + urgentData + sendString, receivedString
- .equals(sendString + urgentData
- + sendString));
-
- // send the regular data
- sendString = new String("Test - Urgent Data");
- theOutput.write(sendString.getBytes());
- theOutput.flush();
-
- // send the urgent data which should not be received
- theSocket.setOOBInline(false);
- servSock.sendUrgentData(urgentData.getBytes()[0]);
-
- // send trailing data
- theOutput.write(sendString.getBytes());
- theOutput.flush();
-
- Thread.sleep(1000);
-
- totalBytesRead = 0;
- myBytes = new byte[100];
- while (theInput.available() > 0) {
- int bytesRead = theInput.read(myBytes, totalBytesRead,
- myBytes.length - totalBytesRead);
- totalBytesRead = totalBytesRead + bytesRead;
- }
-
- receivedString = new String(myBytes, 0, totalBytesRead);
- //assertTrue(
- // "Got unexpected data data when turning on/off(2):"
- // + receivedString + ":" + sendString
- // + sendString, receivedString
- // .equals(sendString + sendString));
-
- // now turn back on and get data. Here we also
- // get the previously sent byte of urgent data as it is
- // still in the urgent buffer
-
- // send the regular data
- sendString = new String("Test - Urgent Data");
- theOutput.write(sendString.getBytes());
- theOutput.flush();
-
- // send the urgent data which should be received again
- theSocket.setOOBInline(true);
- servSock.sendUrgentData(urgentData.getBytes()[0]);
-
- theOutput.write(sendString.getBytes());
- theOutput.flush();
-
- Thread.sleep(1000);
-
- totalBytesRead = 0;
- myBytes = new byte[100];
- while (theInput.available() > 0) {
- int bytesRead = theInput.read(myBytes, totalBytesRead,
- myBytes.length - totalBytesRead);
- totalBytesRead = totalBytesRead + bytesRead;
- }
-
- receivedString = new String(myBytes, 0, totalBytesRead);
- // depending on the platform we may get the previously sent
- // urgent data or not (examples windows-yes, Linux-no).
- // So accept either so long as we get the urgent data from
- // when it was on.
- //assertTrue(
- // "Did not get urgent data when turning on/off(3) GOT:"
- // + receivedString + ":Expected" + urgentData
- // + sendString + urgentData + sendString
- // + ":OR:" + sendString + urgentData
- // + sendString,
- // (receivedString.equals(urgentData + sendString
- // + urgentData + sendString) || receivedString
- // .equals(sendString + urgentData
- // + sendString)));
-
- theSocket.close();
- serverSocket.close();
- }
-
- // now test the case where there is only urgent data
- theAddress = new InetSocketAddress(InetAddress.getLocalHost(),
- Support_PortManager.getNextPort());
- theSocket = new Socket();
- serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- theSocket.connect(theAddress);
- servSock = serverSocket.accept();
- theInput = theSocket.getInputStream();
- theOutput = servSock.getOutputStream();
-
- // send the urgent data which should not be received.
- theSocket.setOOBInline(true);
- servSock.sendUrgentData(urgentData.getBytes()[0]);
-
- Thread.sleep(1000);
-
- totalBytesRead = 0;
- myBytes = new byte[100];
- while (theInput.available() > 0) {
- int bytesRead = theInput.read(myBytes, totalBytesRead,
- myBytes.length - totalBytesRead);
- totalBytesRead = totalBytesRead + bytesRead;
- }
-
- receivedString = new String(myBytes, 0, totalBytesRead);
- assertTrue("Did not get urgent data only urgent data sent:"
- + receivedString + ":" + urgentData, receivedString
- .equals(urgentData));
-
- } catch (Exception e) {
- // for platforms that do not support urgent data we expect an
- // exception. For the others report an error.
- // TODO : Need to introduce a better test for the exception
- // so that the failure only occurs on platforms that support
- // urgent data
- fail("Platform:" + platform
- + ": Got exception during sendUrgent data tests"
- + e.toString());
- }
- }
-
- try {
- Socket theSocket = new Socket();
- theSocket.close();
- theSocket.sendUrgentData(0);
- fail("IOException was not thrown.");
- } catch(IOException ioe) {
- //expected
- }
- }
-
- /*
- * @tests java.net.Socket#setPerformancePreference()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setPerformancePreferences",
- args = {int.class, int.class, int.class}
- )
- public void test_setPerformancePreference_Int_Int_Int() throws Exception {
- Socket theSocket = new Socket();
- theSocket.setPerformancePreferences(1, 1, 1);
- }
-
- /**
- * @tests java.net.Socket#Socket(Proxy)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Socket",
- args = {java.net.Proxy.class}
- )
- public void test_ConstructorLjava_net_Proxy_Exception() {
-
- SocketAddress addr1 = InetSocketAddress.createUnresolved("127.0.0.1",
- 80);
- SocketAddress addr2 = new InetSocketAddress("localhost", 80);
-
- Proxy proxy1 = new Proxy(Proxy.Type.HTTP, addr1);
- // IllegalArgumentException test
- try {
- new Socket(proxy1);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- Proxy proxy2 = new Proxy(Proxy.Type.SOCKS, addr1);
- // should not throw any exception
- new Socket(proxy2);
- new Socket(Proxy.NO_PROXY);
-
- // SecurityException test
- SecurityManager originalSecurityManager = System.getSecurityManager();
- try {
- System.setSecurityManager(new MockSecurityManager());
- } catch (SecurityException e) {
- System.err
- .println("No permission to setSecurityManager, security related test in test_ConstructorLjava_net_Proxy_Security is ignored");
- return;
- }
-
- Proxy proxy3 = new Proxy(Proxy.Type.SOCKS, addr1);
- Proxy proxy4 = new Proxy(Proxy.Type.SOCKS, addr2);
- try {
- try {
- new Socket(proxy3);
- fail("should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- }
- try {
- new Socket(proxy4);
- fail("should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- }
- } finally {
- System.setSecurityManager(originalSecurityManager);
- }
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new Socket(InetAddress.getLocalHost(), 0, true);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } catch (UnknownHostException e) {
- fail("UnknownHostException was thrown.");
- } catch (IOException e) {
- fail("IOException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- try {
- new Socket((Proxy) null);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "SocketException depends on the underlying protocol.",
- method = "Socket",
- args = {SocketImpl.class}
- )
- public void test_ConstructorLSocketImpl() {
- MockSocketImpl msi = new MockSocketImpl();
- try {
- new TestSocket(msi);
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- }
- }
-
- /**
- * @tests Socket#connect(SocketAddress) try an unknownhost
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "UnknownHostException checking only.",
- method = "connect",
- args = {java.net.SocketAddress.class, int.class}
- )
- public void test_connect_unknownhost() throws Exception {
- Socket socket = new Socket();
- try {
- socket.connect(new InetSocketAddress("unknownhost", 12345));
- fail("Should throw UnknownHostException");
- } catch (UnknownHostException e) {
- // expected
- }
- }
-
- /**
- * @tests Socket#connect(SocketAddress) try an unknownhost created by
- * createUnresolved()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "UnknownHostException checking only.",
- method = "connect",
- args = {java.net.SocketAddress.class, int.class}
- )
- public void test_connect_unresolved_unknown() throws Exception {
- Socket socket = new Socket();
- try {
- socket.connect(InetSocketAddress.createUnresolved("unknownhost",
- 12345));
- fail("Should throw UnknownHostException");
- } catch (UnknownHostException e) {
- // expected
- }
- }
-
- /**
- * @tests Socket#connect(SocketAddress) try a known host created by
- * createUnresolved()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "UnknownHostException checking only.",
- method = "connect",
- args = {java.net.SocketAddress.class, int.class}
- )
- public void test_connect_unresolved() throws Exception {
- Socket socket = new Socket();
- try {
- socket.connect(InetSocketAddress.createUnresolved(
- Support_Configuration.SocksServerTestHost,
- Support_Configuration.SocksServerTestPort));
- fail("Should throw UnknownHostException");
- } catch (UnknownHostException e) {
- // expected
- }
- }
-
- /**
- * @tests Socket#getOutputStream()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "SocketException, IllegalBlockingModeException checking.",
- method = "getOutputStream",
- args = {}
- )
- public void test_getOutputStream_shutdownOutput() throws Exception {
- // regression test for Harmony-873
- ServerSocket ss = new ServerSocket(0);
- Socket s = new Socket("127.0.0.1", ss.getLocalPort());
- ss.accept();
- s.shutdownOutput();
- try {
- s.getOutputStream();
- fail("should throw SocketException");
- } catch (IOException e) {
- // expected
- } finally {
- s.close();
- }
-
- SocketChannel channel = SocketChannel.open(
- new InetSocketAddress(ss.getInetAddress(), ss.getLocalPort()));
- channel.configureBlocking(false);
- ss.accept();
- Socket socket = channel.socket();
-
- OutputStream out = null;
-
- try {
- out = socket.getOutputStream();
- out.write(1);
- fail("IllegalBlockingModeException was not thrown.");
- } catch(IllegalBlockingModeException ibme) {
- //expected
- } finally {
- if(out != null) out.close();
- socket.close();
- channel.close();
- }
- }
-
- /**
- * @tests Socket#shutdownInput()
- * @tests Socket#shutdownOutput()
- */
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- notes = "Regression test.",
- method = "shutdownInput",
- args = {}
- )
- public void test_shutdownInputOutput_twice() throws Exception {
- // regression test for Harmony-2944
- Socket s = new Socket("0.0.0.0", 0, false);
- s.shutdownInput();
-
- try {
- s.shutdownInput();
- fail("should throw SocketException");
- } catch (SocketException se) {
- // expected
- }
- s.shutdownOutput();
-
- try {
- s.shutdownOutput();
- fail("should throw SocketException");
- } catch (SocketException se) {
- // expected
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- *
- * @throws Exception
- */
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- try {
- if (s != null)
- s.close();
- } catch (Exception e) {
- }
- try {
- if (ss != null)
- ss.close();
- } catch (Exception e) {
- }
- try {
- if (t != null)
- t.interrupt();
- } catch (Exception e) {
- }
- }
-
- static class MockSecurityManager extends SecurityManager {
-
- public void checkConnect(String host, int port) {
- if ("127.0.0.1".equals(host)) {
- throw new SecurityException("permission is not allowed");
- }
- }
-
- public void checkPermission(Permission permission) {
- return;
- }
-
- }
-
- /**
- *
- */
- protected int startServer(String name) {
- int portNumber = Support_PortManager.getNextPort();
- try {
- ss = new ServerSocket(portNumber, 5);
- } catch (IOException e) {
- fail(name + ": " + e);
- }
- return ss.getLocalPort();
- }
-
- class MockSocketImpl extends SocketImpl {
-
- public MockSocketImpl() {
- super();
- }
-
- @Override
- protected void accept(SocketImpl arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected int available() throws IOException {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- protected void bind(InetAddress arg0, int arg1) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void close() throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void connect(String arg0, int arg1) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void connect(InetAddress arg0, int arg1) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void connect(SocketAddress arg0, int arg1) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void create(boolean arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected InputStream getInputStream() throws IOException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected OutputStream getOutputStream() throws IOException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- protected void listen(int arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- protected void sendUrgentData(int arg0) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
- public Object getOption(int arg0) throws SocketException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public void setOption(int arg0, Object arg1) throws SocketException {
- // TODO Auto-generated method stub
-
- }
-
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/net/SocketTestCase.java b/luni/src/test/java/tests/api/java/net/SocketTestCase.java
deleted file mode 100644
index 4bc459b..0000000
--- a/luni/src/test/java/tests/api/java/net/SocketTestCase.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-
-@TestTargetClass(java.net.Socket.class)
-public abstract class SocketTestCase extends junit.framework.TestCase {
-
- public static final int SO_MULTICAST = 0;
-
- public static final int SO_MULTICAST_INTERFACE = 1;
-
- public static final int SO_LINGER = 2;
-
- public static final int SO_RCVBUF = 3;
-
- public static final int SO_TIMEOUT = 4;
-
- public static final int SO_SNDBUF = 5;
-
- public static final int TCP_NODELAY = 6;
-
- public static final int SO_KEEPALIVE = 7;
-
- public static final int SO_REUSEADDR = 8;
-
- public static final int SO_OOBINLINE = 9;
-
- public static final int IP_TOS = 10;
-
- public static final int SO_BROADCAST = 11;
-
- public static final int SO_USELOOPBACK = 12;
-
- public static final String LINUX = "Linux";
-
- private static final String osDoesNotSupportOperationString = "The socket does not support the operation";
-
- private static final String osDoesNotSupportOptionString = "The socket option is not supported";
-
- private static final String osDoesNotSupportOptionArgumentString = "The socket option arguments are invalid";
-
- public SocketTestCase() {
- }
-
- public SocketTestCase(String name) {
- super(name);
- }
-
- /**
- * Answer whether the OS supports the given socket option.
- */
- public boolean getOptionIsSupported(int option) {
- switch (option) {
- case SO_RCVBUF:
- case SO_SNDBUF:
- return true;
- case SO_MULTICAST:
- case SO_MULTICAST_INTERFACE:
- case SO_LINGER:
- return true;
- case TCP_NODELAY:
- case SO_TIMEOUT:
- return true;
- case SO_KEEPALIVE:
- case SO_REUSEADDR:
- return true;
- case SO_OOBINLINE:
- return true;
- case IP_TOS:
- return true;
- case SO_BROADCAST:
- return true;
- case SO_USELOOPBACK:
- return true;
- }
- return false;
- }
-
- /**
- * If the exception is "socket does not support the operation" exception and
- * it is expected on the current platform, do nothing. Otherwise, fail the
- * test.
- */
- public void handleException(Exception e, int option) {
- if (!getOptionIsSupported(option)) {
- String message = e.getMessage();
- if (message != null
- && (message.equals(osDoesNotSupportOperationString)
- || message.equals(osDoesNotSupportOptionString) || message
- .equals(osDoesNotSupportOptionArgumentString))) {
- /*
- * This exception is the correct behavior for platforms which do
- * not support the option
- */
- } else {
- fail("Threw \""
- + e
- + "\" instead of correct exception for unsupported socket option: "
- + getSocketOptionString(option));
- }
- } else {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * This method should be called at the end of a socket option test's code
- * but before the exception catch statements. It throws a failure if the
- * option given is not supported on the current platform but the VM failed
- * to throw an exception. So, on platforms which do not support the option,
- * the execution should never get to this method.
- */
- public void ensureExceptionThrownIfOptionIsUnsupportedOnOS(int option) {
- if (!getOptionIsSupported(option)) {
- String platform = System.getProperty("os.name");
- String version = System.getProperty("os.version");
- fail("Failed to throw exception for unsupported socket option: "
- + getSocketOptionString(option));
- }
- }
-
- /**
- * Answer a string for the socket option given.
- */
- private String getSocketOptionString(int option) {
- switch (option) {
- case SO_MULTICAST:
- return "Multicast";
- case SO_LINGER:
- return "Linger";
- case SO_RCVBUF:
- return "Receive buffer size";
- case SO_TIMEOUT:
- return "Socket timeout";
- case SO_SNDBUF:
- return "Send buffer size";
- case TCP_NODELAY:
- return "TCP no delay";
- case SO_KEEPALIVE:
- return "Keepalive";
- case SO_REUSEADDR:
- return "Reuse address";
- case SO_OOBINLINE:
- return "out of band data inline";
- case IP_TOS:
- return "Traffic class";
- case SO_BROADCAST:
- return "broadcast";
- case SO_USELOOPBACK:
- return "loopback";
- }
- return "Unknown socket option";
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/net/SocketTimeoutExceptionTest.java b/luni/src/test/java/tests/api/java/net/SocketTimeoutExceptionTest.java
deleted file mode 100644
index ef6a3b6..0000000
--- a/luni/src/test/java/tests/api/java/net/SocketTimeoutExceptionTest.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package tests.api.java.net;
-
-import junit.framework.TestCase;
-
-import java.net.SocketTimeoutException;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(SocketTimeoutException.class)
-public class SocketTimeoutExceptionTest extends TestCase {
-
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SocketTimeoutException",
- args = {}
- )
- public void test_Constructor() {
- SocketTimeoutException ste = new SocketTimeoutException();
- assertNull(ste.getMessage());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SocketTimeoutException",
- args = {String.class}
- )
- public void test_ConstructorLString() {
-
- String [] strs = {"", null, "Test String"};
- for(String str:strs) {
- SocketTimeoutException ste = new SocketTimeoutException(str);
- assertEquals(str, ste.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/TestServerSocketInit.java b/luni/src/test/java/tests/api/java/net/TestServerSocketInit.java
deleted file mode 100644
index 5727d7e..0000000
--- a/luni/src/test/java/tests/api/java/net/TestServerSocketInit.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import java.io.IOException;
-import java.net.ServerSocket;
-
-public class TestServerSocketInit {
-
- public static void main(String[] args) throws IOException {
- ServerSocket serverSocket = new ServerSocket();
- serverSocket.setReuseAddress(true);
- serverSocket.close();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/URISyntaxExceptionTest.java b/luni/src/test/java/tests/api/java/net/URISyntaxExceptionTest.java
deleted file mode 100644
index d370bf8..0000000
--- a/luni/src/test/java/tests/api/java/net/URISyntaxExceptionTest.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/* 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.URISyntaxException;
-import java.util.Locale;
-
-@TestTargetClass(URISyntaxException.class)
-public class URISyntaxExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.URISyntaxException#URISyntaxException(java.lang.String,
- * java.lang.String, int)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URISyntaxException",
- args = {java.lang.String.class, java.lang.String.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getIndex",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInput",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getReason",
- args = {}
- )
- })
- public void test_ConstructorLjava_lang_StringLjava_lang_StringI() {
- // test for Constructor(String str, String problem, int index);
- try {
- new URISyntaxException(null, "problem", 2);
- fail("Expected NullPointerException");
- } catch (NullPointerException npe) {
- }
-
- try {
- new URISyntaxException("str", null, 2);
- fail("Expected NullPointerException");
- } catch (NullPointerException npe) {
- }
-
- try {
- new URISyntaxException("str", "problem", -2);
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException iae) {
- }
-
- URISyntaxException e = new URISyntaxException("str", "problem", 2);
- assertEquals("returned incorrect reason", "problem", e.getReason());
- assertEquals("returned incorrect input", "str", e.getInput());
- assertEquals("returned incorrect index", 2, e.getIndex());
- }
-
- /**
- * @tests java.net.URISyntaxException#URISyntaxException(java.lang.String,
- * java.lang.String)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URISyntaxException",
- args = {java.lang.String.class, java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getIndex",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInput",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getReason",
- args = {}
- )
- })
- public void test_ConstructorLjava_lang_StringLjava_lang_String() {
- // test for Constructor(String str, String problem);
- try {
- new URISyntaxException(null, "problem");
- fail("Expected NullPointerException");
- } catch (NullPointerException npe) {
- }
-
- try {
- new URISyntaxException("str", null);
- fail("Expected NullPointerException");
- } catch (NullPointerException npe) {
- }
-
- URISyntaxException e = new URISyntaxException("str", "problem");
- assertEquals("returned incorrect reason", "problem", e.getReason());
- assertEquals("returned incorrect input", "str", e.getInput());
- assertEquals("returned incorrect index", -1, e.getIndex());
- }
-
- /**
- * @tests java.net.URISyntaxException#getMessage()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
- public void test_getMessage() {
-
- // tests for java.lang.String getMessage()
- Locale.setDefault(Locale.US);
- URISyntaxException e = new URISyntaxException("str", "problem", 3);
- assertEquals("Returned incorrect message", "problem at index 3: str", e
- .getMessage());
-
- e = new URISyntaxException("str", "problem");
- assertEquals("Returned incorrect message", "problem: str", e
- .getMessage());
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-
- protected void doneSuite() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/URITest.java b/luni/src/test/java/tests/api/java/net/URITest.java
deleted file mode 100644
index 3922b13..0000000
--- a/luni/src/test/java/tests/api/java/net/URITest.java
+++ /dev/null
@@ -1,2174 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.net.URISyntaxException;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(URI.class)
-public class URITest extends TestCase {
-
- private URI[] uris;
-
- String[] constructorTests = new String[] {
- "http://user@www.google.com:45/search?q=helpinfo#somefragment",
- // http with authority, query and fragment
- "ftp://ftp.is.co.za/rfc/rfc1808.txt", // ftp
- "gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles", // gopher
- "mailto:mduerst@ifi.unizh.ch", // mailto
- "news:comp.infosystems.www.servers.unix", // news
- "telnet://melvyl.ucop.edu/", // telnet
- "http://123.24.17.98/test", // IPv4 authority
- "http://www.google.com:80/test",// domain name authority
- "http://joe@[3ffe:2a00:100:7031::1]:80/test",
- // IPv6 authority, with userinfo and port
- "/relative", // relative starting with /
- "//relative", // relative starting with //
- "relative", // relative with no /
- "#fragment",// relative just with fragment
- "http://user@host:80", // UI, host,port
- "http://user@host", // ui, host
- "http://host", // host
- "http://host:80", // host,port
- "http://joe@:80", // ui, port (becomes registry-based)
- "file:///foo/bar", // empty authority, non empty path
- "ht?tp://hoe@host:80", // miscellaneous tests
- "mai/lto:hey?joe#man", "http://host/a%20path#frag",
- // path with an escaped octet for space char
- "http://host/a%E2%82%ACpath#frag",
- // path with escaped octet for unicode char, not USASCII
- "http://host/a\u20ACpath#frag",
- // path with unicode char, not USASCII equivalent to
- // = "http://host/a\u0080path#frag",
- "http://host%20name/", // escaped octets in host (becomes
- // registry based)
- "http://host\u00DFname/", // unicodechar in host (becomes
- // registry based)
- // equivalent to = "http://host\u00dfname/",
- "ht123-+tp://www.google.com:80/test", // legal chars in scheme
- };
-
- String[] constructorTestsInvalid = new String[] {
- "http:///a path#frag", // space char in path, not in escaped
- // octet form, with no host
- "http://host/a[path#frag", // an illegal char, not in escaped
- // octet form, should throw an
- // exception
- "http://host/a%path#frag", // invalid escape sequence in path
- "http://host/a%#frag", // incomplete escape sequence in path
-
- "http://host#a frag", // space char in fragment, not in
- // escaped octet form, no path
- "http://host/a#fr#ag", // illegal char in fragment
- "http:///path#fr%ag", // invalid escape sequence in fragment,
- // with no host
- "http://host/path#frag%", // incomplete escape sequence in
- // fragment
-
- "http://host/path?a query#frag", // space char in query, not
- // in escaped octet form
- "http://host?query%ag", // invalid escape sequence in query, no
- // path
- "http:///path?query%", // incomplete escape sequence in query,
- // with no host
-
- "mailto:user^name@fklkf.com" // invalid char in scheme
- // specific part
- };
-
- private URI[] getUris() throws URISyntaxException {
- if (uris != null) {
- return uris;
- }
-
- uris = new URI[] {
- // single arg constructor
- new URI(
- "http://user%60%20info@host/a%20path?qu%60%20ery#fr%5E%20ag"),
- // escaped octets for illegal chars
- new URI(
- "http://user%C3%9F%C2%A3info@host:80/a%E2%82%ACpath?qu%C2%A9%C2%AEery#fr%C3%A4%C3%A8g"),
- // escaped octets for unicode chars
- new URI(
- "ascheme://user\u00DF\u00A3info@host:0/a\u20ACpath?qu\u00A9\u00AEery#fr\u00E4\u00E8g"),
- // unicode chars equivalent to = new
- // URI("ascheme://user\u00df\u00a3info@host:0/a\u0080path?qu\u00a9\u00aeery#fr\u00e4\u00e8g"),
-
- // multiple arg constructors
- new URI("http", "user%60%20info", "host", 80, "/a%20path", //$NON-NLS-4$
- "qu%60%20ery", "fr%5E%20ag"),
- // escaped octets for illegal
- new URI("http", "user%C3%9F%C2%A3info", "host", -1,
- "/a%E2%82%ACpath", "qu%C2%A9%C2%AEery",
- "fr%C3%A4%C3%A8g"),
- // escaped octets for unicode
- new URI("ascheme", "user\u00DF\u00A3info", "host", 80,
- "/a\u20ACpath", "qu\u00A9\u00AEery", "fr\u00E4\u00E8g"),
- // unicode chars equivalent to = new
- // URI("ascheme", "user\u00df\u00a3info", "host", 80,
- // "/a\u0080path", "qu\u00a9\u00aeery", "fr\u00e4\u00e8g"),
- new URI("http", "user` info", "host", 81, "/a path", "qu` ery",
- "fr^ ag"), // illegal chars
- new URI("http", "user%info", "host", 0, "/a%path", "que%ry",
- "f%rag"),
- // % as illegal char, not escaped octet
-
- // urls with undefined components
- new URI("mailto", "user@domain.com", null),
- // no host, path, query or fragment
- new URI("../adirectory/file.html#"),
- // relative path with empty fragment;
- new URI("news", "comp.infosystems.www.servers.unix", null), //
- new URI(null, null, null, "fragment"), // only fragment
- new URI("telnet://server.org"), // only host
- new URI("http://reg:istry?query"),
- // malformed hostname, therefore registry-based,
- // with query
- new URI("file:///c:/temp/calculate.pl?"),
- // empty authority, non empty path, empty query
- };
- return uris;
- }
-
- /**
- * @tests java.net.URI#URI(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "URI",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // tests for public URI(String uri) throws URISyntaxException
-
- for (int i = 0; i < constructorTests.length; i++) {
- try {
- new URI(constructorTests[i]);
- } catch (URISyntaxException e) {
- fail("Failed to construct URI for: " + constructorTests[i]
- + " : " + e);
- }
- }
-
- int[] constructorTestsInvalidIndices = new int[] { 9, 13, 13, 13, 13,
- 16, 15, 21, 18, 17, 18, 11 };
-
- for (int i = 0; i < constructorTestsInvalid.length; i++) {
- try {
- new URI(constructorTestsInvalid[i]);
- fail("Failed to throw URISyntaxException for: "
- + constructorTestsInvalid[i]);
- } catch (URISyntaxException e) {
- assertTrue("Wrong index in URISytaxException for: "
- + constructorTestsInvalid[i] + " expected: "
- + constructorTestsInvalidIndices[i] + ", received: "
- + e.getIndex(),
- e.getIndex() == constructorTestsInvalidIndices[i]);
- }
- }
-
- String invalid2[] = {
- // authority validation
- "http://user@[3ffe:2x00:100:7031::1]:80/test", // malformed
- // IPv6 authority
- "http://[ipv6address]/apath#frag", // malformed ipv6 address
- "http://[ipv6address/apath#frag", // malformed ipv6 address
- "http://ipv6address]/apath#frag", // illegal char in host name
- "http://ipv6[address/apath#frag",
- "http://ipv6addr]ess/apath#frag",
- "http://ipv6address[]/apath#frag",
- // illegal char in username...
- "http://us[]er@host/path?query#frag", "http://host name/path", // illegal
- // char
- // in
- // authority
- "http://host^name#fragment", // illegal char in authority
- "telnet://us er@hostname/", // illegal char in authority
- // missing components
- "//", // Authority expected
- "ascheme://", // Authority expected
- "ascheme:", // Scheme-specific part expected
- // scheme validation
- "a scheme://reg/", // illegal char
- "1scheme://reg/", // non alpha char as 1st char
- "asche\u00dfme:ssp", // unicode char , not USASCII
- "asc%20heme:ssp" // escape octets
- };
-
- for (int i = 0; i < invalid2.length; i++) {
- try {
- new URI(invalid2[i]);
- fail("Failed to throw URISyntaxException for: " + invalid2[i]);
- } catch (URISyntaxException e) {
- }
- }
-
- try {
- new URI(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- } catch (URISyntaxException e) {
- fail("URISyntaxException was thrown.");
- }
- }
-
- /**
- * @tests java.net.URI#URI(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "URISyntaxException checked.",
- method = "URI",
- args = {java.lang.String.class}
- )
- public void test_URI_String() {
- try {
- URI myUri = new URI(":abc@mymail.com");
- fail("TestA, URISyntaxException expected, but not received.");
- } catch (URISyntaxException e) {
- assertEquals("TestA, Wrong URISyntaxException index, ", 0, e
- .getIndex());
- }
-
- try {
- URI uri = new URI("path[one");
- fail("TestB, URISyntaxException expected, but not received.");
- } catch (URISyntaxException e1) {
- assertEquals("TestB, Wrong URISyntaxException index, ", 4, e1
- .getIndex());
- }
-
- try {
- URI uri = new URI(" ");
- fail("TestC, URISyntaxException expected, but not received.");
- } catch (URISyntaxException e2) {
- assertEquals("TestC, Wrong URISyntaxException index, ", 0, e2
- .getIndex());
- }
- }
-
- /**
- * @tests java.net.URI#URI(java.lang.String, java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URI",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String() {
- // tests for public URI(String scheme, String ssp, String frag) throws
- // URISyntaxException
-
- URI uri;
- try {
- uri = new URI("mailto", "mduerst@ifi.unizh.ch", null);
- assertNull("wrong userinfo", uri.getUserInfo());
- assertNull("wrong hostname", uri.getHost());
- assertNull("wrong authority", uri.getAuthority());
- assertEquals("wrong port number", -1, uri.getPort());
- assertNull("wrong path", uri.getPath());
- assertNull("wrong query", uri.getQuery());
- assertNull("wrong fragment", uri.getFragment());
- assertEquals("wrong SchemeSpecificPart", "mduerst@ifi.unizh.ch",
- uri.getSchemeSpecificPart());
- } catch (URISyntaxException e) {
- fail("Unexpected Exception: " + e);
- }
-
- // scheme specific part can not be null
- try {
- uri = new URI("mailto", null, null);
- fail("Expected URISyntaxException");
- } catch (URISyntaxException e) {
- }
-
- // scheme needs to start with an alpha char
- try {
- uri = new URI("3scheme", "//authority/path", "fragment");
- fail("Expected URISyntaxException");
- } catch (URISyntaxException e) {
- }
-
- // scheme can not be empty string
- try {
- uri = new URI("", "//authority/path", "fragment");
- fail("Expected URISyntaxException");
- } catch (URISyntaxException e) {
- }
- }
-
- /**
- * @tests java.net.URI#URI(java.lang.String, java.lang.String,
- * java.lang.String, int, java.lang.String, java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URI",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, int.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_StringILjava_lang_StringLjava_lang_StringLjava_lang_String() {
- // tests for public URI(String scheme, String userinfo, String host, int
- // port, String path,
- // String query, String fragment) throws URISyntaxException
-
- // check for URISyntaxException for invalid Server Authority
- construct1("http", "user", "host\u00DFname", -1, "/file", "query",
- "fragment"); // unicode chars in host name
- // equivalent to construct1("http", "user", "host\u00dfname", -1,
- // "/file",
- // "query", "fragment");
- construct1("http", "user", "host%20name", -1, "/file", "query",
- "fragment"); // escaped octets in host name
- construct1("http", "user", "host name", -1, "/file", "query",
- "fragment"); // illegal char in host name
- construct1("http", "user", "host]name", -1, "/file", "query",
- "fragment"); // illegal char in host name
-
- // missing host name
- construct1("http", "user", "", 80, "/file", "query", "fragment");
-
- // missing host name
- construct1("http", "user", "", -1, "/file", "query", "fragment");
-
- // malformed ipv4 address
- construct1("telnet", null, "256.197.221.200", -1, null, null, null);
-
- // malformed ipv4 address
- construct1("ftp", null, "198.256.221.200", -1, null, null, null);
-
- // These tests fail on other implementations...
- // construct1("http", "user", null, 80, "/file", "query", "fragment");
- // //missing host name
- // construct1("http", "user", null, -1, "/file", "query", "fragment");
- // //missing host name
-
- // check for URISyntaxException for invalid scheme
- construct1("ht\u00DFtp", "user", "hostname", -1, "/file", "query",
- "fragment"); // unicode chars in scheme
- // equivalent to construct1("ht\u00dftp", "user", "hostname", -1,
- // "/file",
- // "query", "fragment");
-
- construct1("ht%20tp", "user", "hostname", -1, "/file", "query",
- "fragment"); // escaped octets in scheme
- construct1("ht tp", "user", "hostname", -1, "/file", "query",
- "fragment"); // illegal char in scheme
- construct1("ht]tp", "user", "hostname", -1, "/file", "query",
- "fragment"); // illegal char in scheme
-
- // relative path with scheme
- construct1("http", "user", "hostname", -1, "relative", "query",
- "fragment"); // unicode chars in scheme
-
- // functional test
- URI uri;
- try {
- uri = new URI("http", "us:e@r", "hostname", 85, "/file/dir#/qu?e/",
- "qu?er#y", "frag#me?nt");
- assertEquals("wrong userinfo", "us:e@r", uri.getUserInfo());
- assertEquals("wrong hostname", "hostname", uri.getHost());
- assertEquals("wrong port number", 85, uri.getPort());
- assertEquals("wrong path", "/file/dir#/qu?e/", uri.getPath());
- assertEquals("wrong query", "qu?er#y", uri.getQuery());
- assertEquals("wrong fragment", "frag#me?nt", uri.getFragment());
- assertEquals("wrong SchemeSpecificPart",
- "//us:e@r@hostname:85/file/dir#/qu?e/?qu?er#y", uri
- .getSchemeSpecificPart());
- } catch (URISyntaxException e) {
- fail("Unexpected Exception: " + e);
- }
- }
-
- /*
- * helper method checking if the 7 arg constructor throws URISyntaxException
- * for a given set of parameters
- */
- private void construct1(String scheme, String userinfo, String host,
- int port, String path, String query, String fragment) {
- try {
- URI uri = new URI(scheme, userinfo, host, port, path, query,
- fragment);
- fail("Expected URISyntaxException not thrown for URI: "
- + uri.toString());
- } catch (URISyntaxException e) {
- // this constructor throws URISyntaxException for malformed server
- // based authorities
- }
- }
-
- /**
- * @throws URISyntaxException
- * @tests java.net.URI#URI(java.lang.String, java.lang.String,
- * java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URI",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_String()
- throws URISyntaxException {
- // relative path
- try {
- URI myUri = new URI("http", "www.joe.com", "relative", "jimmy");
- fail("URISyntaxException expected but not received.");
- } catch (URISyntaxException e) {
- // Expected
- }
-
- // valid parameters for this constructor
- URI uri;
-
- uri = new URI("http", "www.joe.com", "/path", "jimmy");
-
- // illegal char in path
- uri = new URI("http", "www.host.com", "/path?q", "somefragment");
-
- // empty fragment
- uri = new URI("ftp", "ftp.is.co.za", "/rfc/rfc1808.txt", "");
-
- // path with escaped octet for unicode char, not USASCII
- uri = new URI("http", "host", "/a%E2%82%ACpath", "frag");
-
- // frag with unicode char, not USASCII
- // equivalent to = uri = new URI("http", "host", "/apath",
- // "\u0080frag");
- uri = new URI("http", "host", "/apath", "\u20ACfrag");
-
- // Regression test for Harmony-1693
- new URI(null, null, null, null);
-
- // regression for Harmony-1346
- try {
- uri = new URI("http", ":2:3:4:5:6:7:8", "/apath", "\u20ACfrag");
- fail("Should throw URISyntaxException");
- } catch (URISyntaxException e) {
- // Expected
- }
- }
-
- /**
- * @throws URISyntaxException
- * @tests java.net.URI#URI(java.lang.String, java.lang.String,
- * java.lang.String, java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URI",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_String()
- throws URISyntaxException {
- // URISyntaxException on relative path
- try {
- URI myUri = new URI("http", "www.joe.com", "relative", "query",
- "jimmy");
- fail("URISyntaxException expected but not received.");
- } catch (URISyntaxException e) {
- // Expected
- }
-
- // test if empty authority is parsed into undefined host, userinfo and
- // port and if unicode chars and escaped octets in components are
- // preserved, illegal chars are quoted
- URI uri = new URI("ht12-3+tp", "", "/p#a%E2%82%ACth", "q^u%25ery",
- "f/r\u00DFag");
-
- assertEquals("wrong scheme", "ht12-3+tp", uri.getScheme());
- assertNull("wrong authority", uri.getUserInfo());
- assertNull("wrong userinfo", uri.getUserInfo());
- assertNull("wrong hostname", uri.getHost());
- assertEquals("wrong port number", -1, uri.getPort());
- assertEquals("wrong path", "/p#a%E2%82%ACth", uri.getPath());
- assertEquals("wrong query", "q^u%25ery", uri.getQuery());
- assertEquals("wrong fragment", "f/r\u00DFag", uri.getFragment());
- // equivalent to = assertTrue("wrong fragment",
- // uri.getFragment().equals("f/r\u00dfag"));
- assertEquals("wrong SchemeSpecificPart", "///p#a%E2%82%ACth?q^u%25ery",
- uri.getSchemeSpecificPart());
- assertEquals("wrong RawSchemeSpecificPart",
- "///p%23a%25E2%2582%25ACth?q%5Eu%2525ery", uri
- .getRawSchemeSpecificPart());
- assertEquals(
- "incorrect toString()",
- "ht12-3+tp:///p%23a%25E2%2582%25ACth?q%5Eu%2525ery#f/r\u00dfag",
- uri.toString());
- assertEquals("incorrect toASCIIString()",
-
- "ht12-3+tp:///p%23a%25E2%2582%25ACth?q%5Eu%2525ery#f/r%C3%9Fag", uri
- .toASCIIString());
- }
-
- /**
- * @throws URISyntaxException
- * @tests java.net.URI#URI(java.lang.String, java.lang.String,
- * java.lang.String, java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URI",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_fiveArgConstructor() throws URISyntaxException {
- // accept [] as part of valid ipv6 host name
- URI uri = new URI("ftp", "[0001:1234::0001]", "/dir1/dir2", "query",
- "frag");
- assertEquals("Returned incorrect host", "[0001:1234::0001]", uri
- .getHost());
-
- // do not accept [] as part of invalid ipv6 address
- try {
- uri = new URI("ftp", "[www.abc.com]", "/dir1/dir2", "query", "frag");
- fail("Expected URISyntaxException for invalid ipv6 address");
- } catch (URISyntaxException e) {
- // Expected
- }
-
- // do not accept [] as part of user info
- try {
- uri = new URI("ftp", "[user]@host", "/dir1/dir2", "query", "frag");
- fail("Expected URISyntaxException invalid user info");
- } catch (URISyntaxException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.net.URI#compareTo(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compareTo",
- args = {Object.class}
- )
- public void test_compareToLjava_lang_Object() {
- // compareTo tests
-
- String[][] compareToData = new String[][] {
- // scheme tests
- { "http:test", "" }, // scheme null, scheme not null
- { "", "http:test" }, // reverse
- { "http:test", "ftp:test" }, // schemes different
- { "/test", "/test" }, // schemes null
- { "http://joe", "http://joe" }, // schemes same
- { "http://joe", "hTTp://joe" }, // schemes same ignoring case
-
- // opacity : one opaque, the other not
- { "http:opaque", "http://nonopaque" },
- { "http://nonopaque", "http:opaque" },
- { "mailto:abc", "mailto:abc" }, // same ssp
- { "mailto:abC", "mailto:Abc" }, // different, by case
- { "mailto:abc", "mailto:def" }, // different by letter
- { "mailto:abc#ABC", "mailto:abc#DEF" },
- { "mailto:abc#ABC", "mailto:abc#ABC" },
- { "mailto:abc#DEF", "mailto:abc#ABC" },
-
- // hierarchical tests..
-
- // diffrent authorities
- { "//www.test.com/test", "//www.test2.com/test" },
-
- { "/nullauth", "//nonnullauth/test" }, // one null authority
- { "//nonnull", "/null" },
- { "/hello", "/hello" }, // both authorities null
- // different userinfo
- { "http://joe@test.com:80", "http://test.com" },
- { "http://jim@test.com", "http://james@test.com" },
- // different hostnames
- { "http://test.com", "http://toast.com" },
- { "http://test.com:80", "test.com:87" }, // different ports
- { "http://test.com", "http://test.com:80" },
- // different paths
- { "http://test.com:91/dir1", "http://test.com:91/dir2" },
- // one null host
- { "http:/hostless", "http://hostfilled.com/hostless" },
-
- // queries
- { "http://test.com/dir?query", "http://test.com/dir?koory" },
- { "/test?query", "/test" },
- { "/test", "/test?query" },
- { "/test", "/test" },
-
- // fragments
- { "ftp://test.com/path?query#frag", "ftp://test.com/path?query" },
- { "ftp://test.com/path?query", "ftp://test.com/path?query#frag" },
- { "#frag", "#frag" }, { "p", "" },
-
- { "http://www.google.com", "#test" } // miscellaneous
- };
-
- int[] compareToResults = { 1, -1, 2, 0, 0, 0, 1, -1, 0, 32, -3, -3, 0,
- 3, -4, -1, 1, 0, 1, 8, -10, -12, -81, -1, -1, 6, 1, -1, 0, 1,
- -1, 0, 1, 1, };
-
- // test compareTo functionality
- for (int i = 0; i < compareToResults.length; i++) {
- try {
- URI b = new URI(compareToData[i][0]);
- URI r = new URI(compareToData[i][1]);
- if (b.compareTo(r) != compareToResults[i]) {
- fail("Test " + i + ": " + compareToData[i][0]
- + " compared to " + compareToData[i][1] + " -> "
- + b.compareTo(r) + " rather than "
- + compareToResults[i]);
- }
- } catch (Exception e) {
- fail("Error in compareTo test of " + compareToData[i][0]
- + " compared to " + compareToData[i][1] + ": " + e);
- }
- }
- }
-
- /**
- * @throws URISyntaxException
- * @tests java.net.URI#compareTo(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.net.URI.class}
- )
- public void test_compareTo2() throws URISyntaxException {
- URI uri, uri2;
-
- // test URIs with host names with different casing
- uri = new URI("http://AbC.cOm/root/news");
- uri2 = new URI("http://aBc.CoM/root/news");
- assertEquals("TestA", 0, uri.compareTo(uri2));
- assertEquals("TestB", 0, uri.compareTo(uri2));
-
- // test URIs with one undefined component
- uri = new URI("http://abc.com:80/root/news");
- uri2 = new URI("http://abc.com/root/news");
- assertTrue("TestC", uri.compareTo(uri2) > 0);
- assertTrue("TestD", uri2.compareTo(uri) < 0);
-
- // test URIs with one undefined component
- uri = new URI("http://user@abc.com/root/news");
- uri2 = new URI("http://abc.com/root/news");
- assertTrue("TestE", uri.compareTo(uri2) > 0);
- assertTrue("TestF", uri2.compareTo(uri) < 0);
- }
-
- /**
- * @tests java.net.URI#create(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "create",
- args = {java.lang.String.class}
- )
- public void test_createLjava_lang_String() {
-
-
- for (int i = 0; i < constructorTests.length; i++) {
- try {
- new URI(constructorTests[i]);
- } catch (URISyntaxException e) {
- fail("Failed to construct URI for: " + constructorTests[i]
- + " : " + e);
- }
- }
-
- for(int i = 0; i < constructorTestsInvalid.length; i++) {
- try {
- URI myUri = URI.create(constructorTestsInvalid[i]);
- fail("IllegalArgumentException expected but not received.");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- }
- }
-
- /**
- * @tests java.net.URI#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- String[][] equalsData = new String[][] {
- { "", "" }, // null frags
- { "/path", "/path#frag" },
- { "#frag", "#frag2" },
- { "#frag", "#FRag" },
-
- // case insensitive on hex escapes
- { "#fr%4F", "#fr%4f" },
-
- { "scheme:test", "scheme2:test" }, // scheme stuff
- { "test", "http:test" },
- { "http:test", "test" },
- { "SCheme:test", "schEMe:test" },
-
- // hierarchical/opaque mismatch
- { "mailto:jim", "mailto://jim" },
- { "mailto://test", "mailto:test" },
-
- // opaque
- { "mailto:name", "mailto:name" },
- { "mailtO:john", "mailto:jim" },
-
- // test hex case insensitivity on ssp
- { "mailto:te%4Fst", "mailto:te%4fst" },
-
- { "mailto:john#frag", "mailto:john#frag2" },
-
- // hierarchical
- { "/test", "/test" }, // paths
- { "/te%F4st", "/te%f4st" },
- { "/TEst", "/teSt" },
- { "", "/test" },
-
- // registry based because they don't resolve properly to
- // server-based add more tests here
- { "//host.com:80err", "//host.com:80e" },
- { "//host.com:81e%Abrr", "//host.com:81e%abrr" },
-
- { "/test", "//auth.com/test" },
- { "//test.com", "/test" },
-
- { "//test.com", "//test.com" }, // hosts
-
- // case insensitivity for hosts
- { "//HoSt.coM/", "//hOsT.cOm/" },
- { "//te%ae.com", "//te%aE.com" },
- { "//test.com:80", "//test.com:81" },
- { "//joe@test.com:80", "//test.com:80" },
- { "//jo%3E@test.com:82", "//jo%3E@test.com:82" },
- { "//test@test.com:85", "//test@test.com" }, };
-
- boolean[] equalsResults = new boolean[] { true, false, false, false,
- true, false, false, false, true, false, false, true, false,
- true, false, true, true, false, false, false, true, false,
- false, true, true, true, false, false, true, false, };
-
- // test equals functionality
- for (int i = 0; i < equalsResults.length; i++) {
- try {
- URI b = new URI(equalsData[i][0]);
- URI r = new URI(equalsData[i][1]);
- if (b.equals(r) != equalsResults[i]) {
- fail("Error: " + equalsData[i][0] + " == "
- + equalsData[i][1] + "? -> " + b.equals(r)
- + " expected " + equalsResults[i]);
- }
- } catch (Exception e) {
- fail("Exception during equals testing data " + equalsData[i][0]
- + " == " + equalsData[i][1] + "? " + e);
- }
- }
-
- }
-
- /**
- * @throws URISyntaxException
- * @tests java.net.URI#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equals2() throws URISyntaxException {
- // test URIs with empty string authority
- URI uri = new URI("http:///~/dictionary");
- URI uri2 = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(),
- uri.getQuery(), uri.getFragment());
- assertTrue(uri2.equals(uri));
-
- // test URIs with port number
- uri = new URI("http://abc.com%E2%82%AC:88/root/news");
- uri2 = new URI("http://abc.com%E2%82%AC/root/news");
- assertFalse(uri.equals(uri2));
- assertFalse(uri2.equals(uri));
-
- // test URIs with host names with different casing
- uri = new URI("http://AbC.cOm/root/news");
- uri2 = new URI("http://aBc.CoM/root/news");
- assertTrue(uri.equals(uri2));
- assertTrue(uri2.equals(uri));
- }
-
- /**
- * @tests java.net.URI#getAuthority()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAuthority",
- args = {}
- )
- public void test_getAuthority() throws Exception {
- URI[] uris = getUris();
-
- String[] getAuthorityResults = {
- "user` info@host",
- "user\u00DF\u00A3info@host:80", // =
- // "user\u00df\u00a3info@host:80",
- "user\u00DF\u00A3info@host:0", // =
- // "user\u00df\u00a3info@host:0",
- "user%60%20info@host:80",
- "user%C3%9F%C2%A3info@host",
- "user\u00DF\u00A3info@host:80", // =
- // "user\u00df\u00a3info@host:80",
- "user` info@host:81", "user%info@host:0", null, null, null,
- null, "server.org", "reg:istry", null, };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getAuthority();
- if (getAuthorityResults[i] != result
- && !getAuthorityResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getAuthority() returned: " + result
- + ", expected: " + getAuthorityResults[i]);
- }
- }
- // regression test for HARMONY-1119
- assertNull(new URI(null, null, null, 127, null, null, null)
- .getAuthority());
- }
-
- /**
- * @tests java.net.URI#getAuthority()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAuthority",
- args = {}
- )
- public void test_getAuthority2() throws Exception {
- // tests for URIs with empty string authority component
-
- URI uri = new URI("file:///tmp/");
- assertNull("Authority not null for URI: " + uri, uri.getAuthority());
- assertNull("Host not null for URI " + uri, uri.getHost());
- assertEquals("testA, toString() returned incorrect value",
- "file:///tmp/", uri.toString());
-
- uri = new URI("file", "", "/tmp", "frag");
- assertNull("Authority not null for URI: " + uri, uri.getAuthority());
- assertNull("Host not null for URI " + uri, uri.getHost());
- assertEquals("testB, toString() returned incorrect value",
- "file:///tmp#frag", uri.toString());
-
- uri = new URI("file", "", "/tmp", "query", "frag");
- assertNull("Authority not null for URI: " + uri, uri.getAuthority());
- assertNull("Host not null for URI " + uri, uri.getHost());
- assertEquals("test C, toString() returned incorrect value",
- "file:///tmp?query#frag", uri.toString());
-
- // after normalization the host string info may be lost since the
- // uri string is reconstructed
- uri = new URI("file", "", "/tmp/a/../b/c", "query", "frag");
- URI uri2 = uri.normalize();
- assertNull("Authority not null for URI: " + uri2, uri.getAuthority());
- assertNull("Host not null for URI " + uri2, uri.getHost());
- assertEquals("test D, toString() returned incorrect value",
- "file:///tmp/a/../b/c?query#frag", uri.toString());
- assertEquals("test E, toString() returned incorrect value",
- "file:/tmp/b/c?query#frag", uri2.toString());
-
- // the empty string host will give URISyntaxException
- // for the 7 arg constructor
- try {
- uri = new URI("file", "user", "", 80, "/path", "query", "frag");
- fail("Expected URISyntaxException");
- } catch (URISyntaxException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.net.URI#getFragment()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFragment",
- args = {}
- )
- public void test_getFragment() throws Exception {
- URI[] uris = getUris();
-
- String[] getFragmentResults = { "fr^ ag", "fr\u00E4\u00E8g", // =
- // "fr\u00e4\u00e8g",
- "fr\u00E4\u00E8g", // = "fr\u00e4\u00e8g",
- "fr%5E%20ag", "fr%C3%A4%C3%A8g", "fr\u00E4\u00E8g", // =
- // "fr\u00e4\u00e8g",
- "fr^ ag", "f%rag", null, "", null, "fragment", null, null, null };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getFragment();
- if (getFragmentResults[i] != result
- && !getFragmentResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getFragment() returned: " + result
- + ", expected: " + getFragmentResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getHost()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getHost",
- args = {}
- )
- public void test_getHost() throws Exception {
- URI[] uris = getUris();
-
- String[] getHostResults = { "host", "host", "host", "host", "host",
- "host", "host", "host", null, null, null, null, "server.org",
- null, null };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getHost();
- if (getHostResults[i] != result
- && !getHostResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getHost() returned: " + result + ", expected: "
- + getHostResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getPath()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPath",
- args = {}
- )
- public void test_getPath() throws Exception {
- URI[] uris = getUris();
-
- String[] getPathResults = { "/a path",
- "/a\u20ACpath", // = "/a\u0080path",
- "/a\u20ACpath", // = "/a\u0080path",
- "/a%20path", "/a%E2%82%ACpath",
- "/a\u20ACpath", // = "/a\u0080path",
- "/a path", "/a%path", null, "../adirectory/file.html", null,
- "", "", "", "/c:/temp/calculate.pl" };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getPath();
- if (getPathResults[i] != result
- && !getPathResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getPath() returned: " + result + ", expected: "
- + getPathResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getPort()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPort",
- args = {}
- )
- public void test_getPort() throws Exception {
- URI[] uris = getUris();
-
- int[] getPortResults = { -1, 80, 0, 80, -1, 80, 81, 0, -1, -1, -1, -1,
- -1, -1, -1 };
-
- for (int i = 0; i < uris.length; i++) {
- int result = uris[i].getPort();
- assertTrue("Error: For URI \"" + uris[i].toString()
- + "\", getPort() returned: " + result + ", expected: "
- + getPortResults[i], result == getPortResults[i]);
- }
- }
-
- /**
- * @tests java.net.URI#getPort()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPort",
- args = {}
- )
- public void test_getPort2() throws Exception {
- // if port value is negative, the authority should be
- // consider registry based.
-
- URI uri = new URI("http://myhost:-8096/site/index.html");
- assertEquals("TestA, returned wrong port value,", -1, uri.getPort());
- assertNull("TestA, returned wrong host value,", uri.getHost());
- try {
- uri.parseServerAuthority();
- fail("TestA, Expected URISyntaxException");
- } catch (URISyntaxException e) {
- // Expected
- }
-
- uri = new URI("http", "//myhost:-8096", null);
- assertEquals("TestB returned wrong port value,", -1, uri.getPort());
- assertNull("TestB returned wrong host value,", uri.getHost());
- try {
- uri.parseServerAuthority();
- fail("TestB, Expected URISyntaxException");
- } catch (URISyntaxException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.net.URI#getQuery()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getQuery",
- args = {}
- )
- public void test_getQuery() throws Exception {
- URI[] uris = getUris();
-
- String[] getQueryResults = { "qu` ery", "qu\u00A9\u00AEery", // =
- // "qu\u00a9\u00aeery",
- "qu\u00A9\u00AEery", // = "qu\u00a9\u00aeery",
- "qu%60%20ery", "qu%C2%A9%C2%AEery", "qu\u00A9\u00AEery", // =
- // "qu\u00a9\u00aeery",
- "qu` ery", "que%ry", null, null, null, null, null, "query", "" };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getQuery();
- if (getQueryResults[i] != result
- && !getQueryResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getQuery() returned: " + result + ", expected: "
- + getQueryResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getRawAuthority()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRawAuthority",
- args = {}
- )
- public void test_getRawAuthority() throws Exception {
- URI[] uris = getUris();
-
- String[] getRawAuthorityResults = {
- "user%60%20info@host",
- "user%C3%9F%C2%A3info@host:80",
- "user\u00DF\u00A3info@host:0", // =
- // "user\u00df\u00a3info@host:0",
- "user%2560%2520info@host:80",
- "user%25C3%259F%25C2%25A3info@host",
- "user\u00DF\u00A3info@host:80", // =
- // "user\u00df\u00a3info@host:80",
- "user%60%20info@host:81", "user%25info@host:0", null, null,
- null, null, "server.org", "reg:istry", null };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getRawAuthority();
- if (getRawAuthorityResults[i] != result
- && !getRawAuthorityResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getRawAuthority() returned: " + result
- + ", expected: " + getRawAuthorityResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getRawFragment()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRawFragment",
- args = {}
- )
- public void test_getRawFragment() throws Exception {
- URI[] uris = getUris();
-
- String[] getRawFragmentResults = { "fr%5E%20ag",
- "fr%C3%A4%C3%A8g",
- "fr\u00E4\u00E8g", // = "fr\u00e4\u00e8g",
- "fr%255E%2520ag", "fr%25C3%25A4%25C3%25A8g",
- "fr\u00E4\u00E8g", // =
- // "fr\u00e4\u00e8g",
- "fr%5E%20ag", "f%25rag", null, "", null, "fragment", null,
- null, null };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getRawFragment();
- if (getRawFragmentResults[i] != result
- && !getRawFragmentResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getRawFragment() returned: " + result
- + ", expected: " + getRawFragmentResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getRawPath()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRawPath",
- args = {}
- )
- public void test_getRawPath() throws Exception {
- URI[] uris = getUris();
-
- String[] getRawPathResults = { "/a%20path",
- "/a%E2%82%ACpath",
- "/a\u20ACpath", // = "/a\u0080path",
- "/a%2520path", "/a%25E2%2582%25ACpath",
- "/a\u20ACpath", // =
- // "/a\u0080path",
- "/a%20path", "/a%25path", null, "../adirectory/file.html",
- null, "", "", "", "/c:/temp/calculate.pl" };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getRawPath();
- if (getRawPathResults[i] != result
- && !getRawPathResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getRawPath() returned: " + result
- + ", expected: " + getRawPathResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getRawQuery()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRawQuery",
- args = {}
- )
- public void test_getRawQuery() throws Exception {
- URI[] uris = getUris();
-
- String[] getRawQueryResults = {
- "qu%60%20ery",
- "qu%C2%A9%C2%AEery",
- "qu\u00A9\u00AEery", // = "qu\u00a9\u00aeery",
- "qu%2560%2520ery",
- "qu%25C2%25A9%25C2%25AEery",
- "qu\u00A9\u00AEery", // = "qu\u00a9\u00aeery",
- "qu%60%20ery", "que%25ry", null, null, null, null, null,
- "query", "" };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getRawQuery();
- if (getRawQueryResults[i] != result
- && !getRawQueryResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getRawQuery() returned: " + result
- + ", expected: " + getRawQueryResults[i]);
- }
- }
-
- }
-
- /**
- * @tests java.net.URI#getRawSchemeSpecificPart()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRawSchemeSpecificPart",
- args = {}
- )
- public void test_getRawSchemeSpecificPart() throws Exception {
- URI[] uris = getUris();
-
- String[] getRawSspResults = {
- "//user%60%20info@host/a%20path?qu%60%20ery",
- "//user%C3%9F%C2%A3info@host:80/a%E2%82%ACpath?qu%C2%A9%C2%AEery",
- "//user\u00DF\u00A3info@host:0/a\u20ACpath?qu\u00A9\u00AEery", // =
- // "//user\u00df\u00a3info@host:0/a\u0080path?qu\u00a9\u00aeery"
- "//user%2560%2520info@host:80/a%2520path?qu%2560%2520ery",
- "//user%25C3%259F%25C2%25A3info@host/a%25E2%2582%25ACpath?qu%25C2%25A9%25C2%25AEery",
- "//user\u00DF\u00A3info@host:80/a\u20ACpath?qu\u00A9\u00AEery", // =
- // "//user\u00df\u00a3info@host:80/a\u0080path?qu\u00a9\u00aeery"
- "//user%60%20info@host:81/a%20path?qu%60%20ery",
- "//user%25info@host:0/a%25path?que%25ry", "user@domain.com",
- "../adirectory/file.html", "comp.infosystems.www.servers.unix",
- "", "//server.org", "//reg:istry?query",
- "///c:/temp/calculate.pl?" };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getRawSchemeSpecificPart();
- if (!getRawSspResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getRawSchemeSpecificPart() returned: " + result
- + ", expected: " + getRawSspResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getRawUserInfo()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRawUserInfo",
- args = {}
- )
- public void test_getRawUserInfo() throws URISyntaxException {
- URI[] uris = getUris();
-
- String[] getRawUserInfoResults = {
- "user%60%20info",
- "user%C3%9F%C2%A3info",
- "user\u00DF\u00A3info", // = "user\u00df\u00a3info",
- "user%2560%2520info",
- "user%25C3%259F%25C2%25A3info",
- "user\u00DF\u00A3info", // = "user\u00df\u00a3info",
- "user%60%20info", "user%25info", null, null, null, null, null,
- null, null };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getRawUserInfo();
- if (getRawUserInfoResults[i] != result
- && !getRawUserInfoResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getRawUserInfo() returned: " + result
- + ", expected: " + getRawUserInfoResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getScheme()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getScheme",
- args = {}
- )
- public void test_getScheme() throws Exception {
- URI[] uris = getUris();
-
- String[] getSchemeResults = { "http", "http", "ascheme", "http",
- "http", "ascheme", "http", "http", "mailto", null, "news",
- null, "telnet", "http", "file" };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getScheme();
- if (getSchemeResults[i] != result
- && !getSchemeResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getScheme() returned: " + result
- + ", expected: " + getSchemeResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getSchemeSpecificPart()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSchemeSpecificPart",
- args = {}
- )
- public void test_getSchemeSpecificPart() throws Exception {
- URI[] uris = getUris();
-
- String[] getSspResults = {
- "//user` info@host/a path?qu` ery",
- "//user\u00DF\u00A3info@host:80/a\u20ACpath?qu\u00A9\u00AEery", // =
- // "//user\u00df\u00a3info@host:80/a\u0080path?qu\u00a9\u00aeery",
- "//user\u00DF\u00A3info@host:0/a\u20ACpath?qu\u00A9\u00AEery", // =
- // "//user\u00df\u00a3info@host:0/a\u0080path?qu\u00a9\u00aeery",
- "//user%60%20info@host:80/a%20path?qu%60%20ery",
- "//user%C3%9F%C2%A3info@host/a%E2%82%ACpath?qu%C2%A9%C2%AEery",
- "//user\u00DF\u00A3info@host:80/a\u20ACpath?qu\u00A9\u00AEery", // =
- // "//user\u00df\u00a3info@host:80/a\u0080path?qu\u00a9\u00aeery",
- "//user` info@host:81/a path?qu` ery",
- "//user%info@host:0/a%path?que%ry", "user@domain.com",
- "../adirectory/file.html", "comp.infosystems.www.servers.unix",
- "", "//server.org", "//reg:istry?query",
- "///c:/temp/calculate.pl?" };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getSchemeSpecificPart();
- if (!getSspResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getSchemeSpecificPart() returned: " + result
- + ", expected: " + getSspResults[i]);
- }
- }
-
- }
-
- /**
- * @tests java.net.URI#getUserInfo()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getUserInfo",
- args = {}
- )
- public void test_getUserInfo() throws Exception {
- URI[] uris = getUris();
-
- String[] getUserInfoResults = {
- "user` info",
- "user\u00DF\u00A3info", // =
- // "user\u00df\u00a3info",
- "user\u00DF\u00A3info", // = "user\u00df\u00a3info",
- "user%60%20info",
- "user%C3%9F%C2%A3info",
- "user\u00DF\u00A3info", // = "user\u00df\u00a3info",
- "user` info", "user%info", null, null, null, null, null, null,
- null };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getUserInfo();
- if (getUserInfoResults[i] != result
- && !getUserInfoResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getUserInfo() returned: " + result
- + ", expected: " + getUserInfoResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() throws Exception {
- String[][] hashCodeData = new String[][] {
- { "", "" }, // null frags
- { "/path", "/path#frag" },
- { "#frag", "#frag2" },
- { "#frag", "#FRag" },
-
- { "#fr%4F", "#fr%4F" }, // case insensitive on hex escapes
-
- { "scheme:test", "scheme2:test" }, // scheme
- { "test", "http:test" },
- { "http:test", "test" },
-
- // case insensitivity for scheme
- { "SCheme:test", "schEMe:test" },
-
- // hierarchical/opaque mismatch
- { "mailto:jim", "mailto://jim" },
- { "mailto://test", "mailto:test" },
-
- // opaque
- { "mailto:name", "mailto:name" },
- { "mailtO:john", "mailto:jim" },
- { "mailto:te%4Fst", "mailto:te%4Fst" },
- { "mailto:john#frag", "mailto:john#frag2" },
-
- // hierarchical
- { "/test/", "/test/" }, // paths
- { "/te%F4st", "/te%F4st" },
- { "/TEst", "/teSt" },
- { "", "/test" },
-
- // registry based because they don't resolve properly to
- // server-based
- // add more tests here
- { "//host.com:80err", "//host.com:80e" },
- { "//host.com:81e%Abrr", "//host.com:81e%Abrr" },
- { "//Host.com:80e", "//hoSt.com:80e" },
-
- { "/test", "//auth.com/test" },
- { "//test.com", "/test" },
-
- { "//test.com", "//test.com" }, // server based
-
- // case insensitivity for host
- { "//HoSt.coM/", "//hOsT.cOm/" },
- { "//te%aE.com", "//te%aE.com" },
- { "//test.com:80", "//test.com:81" },
- { "//joe@test.com:80", "//test.com:80" },
- { "//jo%3E@test.com:82", "//jo%3E@test.com:82" },
- { "//test@test.com:85", "//test@test.com" }, };
-
- boolean[] hashCodeResults = new boolean[] { true, false, false, false,
- true, false, false, false, true, false, false, true, false,
- true, false, true, true, false, false, false, true, false,
- false, false, true, true, true, false, false, true, false, };
-
- for (int i = 0; i < hashCodeResults.length; i++) {
- URI b = new URI(hashCodeData[i][0]);
- URI r = new URI(hashCodeData[i][1]);
- assertEquals("Error in hashcode equals results for" + b.toString()
- + " " + r.toString(), hashCodeResults[i], b.hashCode() == r
- .hashCode());
- }
-
- }
-
- /**
- * @tests java.net.URI#isAbsolute()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isAbsolute",
- args = {}
- )
- public void test_isAbsolute() throws URISyntaxException {
- String[] isAbsoluteData = new String[] { "mailto:user@ca.ibm.com",
- "urn:isbn:123498989h", "news:software.ibm.com",
- "http://www.amazon.ca", "file:///d:/temp/results.txt",
- "scheme:ssp", "calculate.pl?isbn=123498989h",
- "?isbn=123498989h", "//www.amazon.ca", "a.html", "#top",
- "//pc1/", "//user@host/path/file" };
-
- boolean results[] = new boolean[] { true, true, true, true, true, true,
- false, false, false, false, false, false, false };
-
- for (int i = 0; i < isAbsoluteData.length; i++) {
- boolean result = new URI(isAbsoluteData[i]).isAbsolute();
- assertEquals("new URI(" + isAbsoluteData[i] + ").isAbsolute()",
- results[i], result);
- }
- }
-
- /**
- * @tests java.net.URI#isOpaque()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isOpaque",
- args = {}
- )
- public void test_isOpaque() throws URISyntaxException {
- String[] isOpaqueData = new String[] { "mailto:user@ca.ibm.com",
- "urn:isbn:123498989h", "news:software.ibm.com",
- "http://www.amazon.ca", "file:///d:/temp/results.txt",
- "scheme:ssp", "calculate.pl?isbn=123498989h",
- "?isbn=123498989h", "//www.amazon.ca", "a.html", "#top",
- "//pc1/", "//user@host/path/file" };
-
- boolean results[] = new boolean[] { true, true, true, false, false,
- true, false, false, false, false, false, false, false };
-
- for (int i = 0; i < isOpaqueData.length; i++) {
- boolean result = new URI(isOpaqueData[i]).isOpaque();
- assertEquals("new URI(" + isOpaqueData[i] + ").isOpaque()",
- results[i], result);
- }
- }
-
- /**
- * @tests java.net.URI#normalize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "normalize",
- args = {}
- )
- public void test_normalize() throws Exception {
-
- String[] normalizeData = new String[] {
- // normal
- "/",
- "/a",
- "/a/b",
- "/a/b/c",
- // single, '.'
- "/.", "/./", "/./.", "/././",
- "/./a",
- "/./a/",
- "/././a",
- "/././a/",
- "/a/.",
- "/a/./",
- "/a/./.",
- "/a/./b",
- // double, '..'
- "/a/..", "/a/../", "/a/../b", "/a/../b/..", "/a/../b/../",
- "/a/../b/../c", "/..", "/../", "/../..", "/../../", "/../a",
- "/../a/", "/../../a", "/../../a/", "/a/b/../../c",
- "/a/b/../..",
- "/a/b/../../",
- "/a/b/../../c",
- "/a/b/c/../../../d",
- "/a/b/..",
- "/a/b/../",
- "/a/b/../c",
- // miscellaneous
- "/a/b/.././../../c/./d/../e",
- "/a/../../.c././../././c/d/../g/..",
- // '.' in the middle of segments
- "/a./b", "/.a/b", "/a.b/c", "/a/b../c",
- "/a/..b/c",
- "/a/b..c/d",
- // no leading slash, miscellaneous
- "", "a", "a/b", "a/b/c", "../", ".", "..", "../g",
- "g/a/../../b/c/./g", "a/b/.././../../c/./d/../e",
- "a/../../.c././../././c/d/../g/..", };
-
- String[] normalizeResults = new String[] { "/", "/a", "/a/b", "/a/b/c",
- "/", "/", "/", "/", "/a", "/a/", "/a", "/a/", "/a/", "/a/",
- "/a/", "/a/b", "/", "/", "/b", "/", "/", "/c", "/..", "/../",
- "/../..", "/../../", "/../a", "/../a/", "/../../a",
- "/../../a/", "/c", "/", "/", "/c", "/d", "/a/", "/a/", "/a/c",
- "/../c/e", "/../c/", "/a./b", "/.a/b", "/a.b/c", "/a/b../c",
- "/a/..b/c", "/a/b..c/d", "", "a", "a/b", "a/b/c", "../", "",
- "..", "../g", "b/c/g", "../c/e", "../c/", };
-
- for (int i = 0; i < normalizeData.length; i++) {
- URI test = new URI(normalizeData[i]);
- String result = test.normalize().toString();
- assertEquals("Normalized incorrectly, ", normalizeResults[i],
- result.toString());
- }
- }
-
- /**
- * @tests java.net.URI#normalize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "normalize",
- args = {}
- )
- public void test_normalize2() throws URISyntaxException {
- URI uri1 = null, uri2 = null;
- uri1 = new URI("file:/D:/one/two/../../three");
- uri2 = uri1.normalize();
-
- assertEquals("Normalized to incorrect URI", "file:/D:/three", uri2
- .toString());
- assertTrue("Resolved URI is not absolute", uri2.isAbsolute());
- assertFalse("Resolved URI is opaque", uri2.isOpaque());
- assertEquals("Resolved URI has incorrect scheme specific part",
- "/D:/three", uri2.getRawSchemeSpecificPart());
- }
-
- /**
- * @tests java.net.URI#normalize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "normalize",
- args = {}
- )
- public void test_normalize3() throws URISyntaxException {
- // return same URI if it has a normalized path already
- URI uri1 = null, uri2 = null;
- uri1 = new URI("http://host/D:/one/two/three");
- uri2 = uri1.normalize();
- assertSame("Failed to return same URI after normalization", uri1, uri2);
-
- // try with empty path
- uri1 = new URI("http", "host", null, "fragment");
- uri2 = uri1.normalize();
- assertSame("Failed to return same URI after normalization", uri1, uri2);
- }
-
- /**
- * @tests java.net.URI#parseServerAuthority()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "parseServerAuthority",
- args = {}
- )
- public void test_parseServerAuthority() throws URISyntaxException {
- // registry based uris
- URI[] uris = null;
- uris = new URI[] {
- // port number not digits
- new URI("http://foo:bar/file#fragment"),
- new URI("http", "//foo:bar/file", "fragment"),
-
- // unicode char in the hostname = new
- // URI("http://host\u00dfname/")
- new URI("http://host\u00DFname/"),
-
- new URI("http", "//host\u00DFname/", null),
- // = new URI("http://host\u00dfname/", null),
-
- // escaped octets in host name
- new URI("http://host%20name/"),
- new URI("http", "//host%20name/", null),
-
- // missing host name, port number
- new URI("http://joe@:80"),
-
- // missing host name, no port number
- new URI("http://user@/file?query#fragment"),
-
- new URI("//host.com:80err"), // malformed port number
- new URI("//host.com:81e%Abrr"),
-
- // malformed ipv4 address
- new URI("telnet", "//256.197.221.200", null),
-
- new URI("telnet://198.256.221.200"),
- new URI("//te%ae.com"), // misc ..
- new URI("//:port"), new URI("//:80"),
-
- // last label has to start with alpha char
- new URI("//fgj234fkgj.jhj.123."),
-
- new URI("//fgj234fkgj.jhj.123"),
-
- // '-' cannot be first or last charcter in a label
- new URI("//-domain.name"), new URI("//domain.name-"),
- new URI("//domain-"),
-
- // illegal char in host name
- new URI("//doma*in"),
-
- // host expected
- new URI("http://:80/"), new URI("http://user@/"),
-
- // ipv6 address not enclosed in "[]"
- new URI("http://3ffe:2a00:100:7031:22:1:80:89/"),
-
- // expected ipv6 addresses to be enclosed in "[]"
- new URI("http", "34::56:78", "/path", "query", "fragment"),
-
- // expected host
- new URI("http", "user@", "/path", "query", "fragment") };
- // these URIs do not have valid server based authorities,
- // but single arg, 3 and 5 arg constructors
- // parse them as valid registry based authorities
-
- // exception should occur when parseServerAuthority is
- // requested on these uris
- for (int i = 0; i < uris.length; i++) {
- try {
- URI uri = uris[i].parseServerAuthority();
- fail("URISyntaxException expected but not received for URI: "
- + uris[i].toString());
- } catch (URISyntaxException e) {
- // Expected
- }
- }
-
- // valid Server based authorities
- new URI("http", "3ffe:2a00:100:7031:2e:1:80:80", "/path", "fragment")
- .parseServerAuthority();
- new URI("http", "host:80", "/path", "query", "fragment")
- .parseServerAuthority();
- new URI("http://[::3abc:4abc]:80/").parseServerAuthority();
- new URI("http", "34::56:78", "/path", "fragment")
- .parseServerAuthority();
- new URI("http", "[34:56::78]:80", "/path", "fragment")
- .parseServerAuthority();
-
- // invalid authorities (neither server nor registry)
- try {
- URI uri = new URI("http://us[er@host:80/");
- fail("Expected URISyntaxException for URI " + uri.toString());
- } catch (URISyntaxException e) {
- // Expected
- }
-
- try {
- URI uri = new URI("http://[ddd::hgghh]/");
- fail("Expected URISyntaxException for URI " + uri.toString());
- } catch (URISyntaxException e) {
- // Expected
- }
-
- try {
- URI uri = new URI("http", "[3ffe:2a00:100:7031:2e:1:80:80]a:80",
- "/path", "fragment");
- fail("Expected URISyntaxException for URI " + uri.toString());
- } catch (URISyntaxException e) {
- // Expected
- }
-
- try {
- URI uri = new URI("http", "host:80", "/path", "fragment");
- fail("Expected URISyntaxException for URI " + uri.toString());
- } catch (URISyntaxException e) {
- // Expected
- }
-
- // regression test for HARMONY-1126
- assertNotNull(URI.create("file://C:/1.txt").parseServerAuthority());
- }
-
- /**
- * @tests java.net.URI#relativize(java.net.URI)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "relativize",
- args = {java.net.URI.class}
- )
- public void test_relativizeLjava_net_URI() {
- // relativization tests
- String[][] relativizeData = new String[][] {
- // first is base, second is the one to relativize
- { "http://www.google.com/dir1/dir2", "mailto:test" }, // rel =
- // opaque
- { "mailto:test", "http://www.google.com" }, // base = opaque
-
- // different authority
- { "http://www.eclipse.org/dir1",
- "http://www.google.com/dir1/dir2" },
-
- // different scheme
- { "http://www.google.com", "ftp://www.google.com" },
-
- { "http://www.google.com/dir1/dir2/",
- "http://www.google.com/dir3/dir4/file.txt" },
- { "http://www.google.com/dir1/",
- "http://www.google.com/dir1/dir2/file.txt" },
- { "./dir1/", "./dir1/hi" },
- { "/dir1/./dir2", "/dir1/./dir2/hi" },
- { "/dir1/dir2/..", "/dir1/dir2/../hi" },
- { "/dir1/dir2/..", "/dir1/dir2/hi" },
- { "/dir1/dir2/", "/dir1/dir3/../dir2/text" },
- { "//www.google.com", "//www.google.com/dir1/file" },
- { "/dir1", "/dir1/hi" }, { "/dir1/", "/dir1/hi" }, };
-
- // expected results
- String[] relativizeResults = new String[] { "mailto:test",
- "http://www.google.com", "http://www.google.com/dir1/dir2",
- "ftp://www.google.com",
- "http://www.google.com/dir3/dir4/file.txt", "dir2/file.txt",
- "hi", "hi", "hi", "dir2/hi", "text", "dir1/file", "hi", "hi", };
-
- for (int i = 0; i < relativizeData.length; i++) {
- try {
- URI b = new URI(relativizeData[i][0]);
- URI r = new URI(relativizeData[i][1]);
- if (!b.relativize(r).toString().equals(relativizeResults[i])) {
- fail("Error: relativize, " + relativizeData[i][0] + ", "
- + relativizeData[i][1] + " returned: "
- + b.relativize(r) + ", expected:"
- + relativizeResults[i]);
- }
- } catch (URISyntaxException e) {
- fail("Exception on relativize test on data "
- + relativizeData[i][0] + ", " + relativizeData[i][1]
- + ": " + e);
- }
- }
-
- try {
- URI b = new URI(relativizeData[0][0]);
- b.relativize(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- } catch (URISyntaxException e) {
- fail("URISyntaxException was thrown.");
- }
- }
-
- /**
- * @tests java.net.URI#relativize(java.net.URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "NullPointerException checking missed.",
- method = "relativize",
- args = {java.net.URI.class}
- )
- public void test_relativize2() throws Exception {
- URI a = new URI("http://host/dir");
- URI b = new URI("http://host/dir/file?query");
- assertEquals("relativized incorrectly,", new URI("file?query"), a
- .relativize(b));
-
- // one URI with empty host
- a = new URI("file:///~/dictionary");
- b = new URI("file://tools/~/dictionary");
- assertEquals("relativized incorrectly,", new URI(
- "file://tools/~/dictionary"), a.relativize(b));
- assertEquals("relativized incorrectly,",
- new URI("file:///~/dictionary"), b.relativize(a));
-
- // two URIs with empty hosts
- b = new URI("file:///~/therasus");
- assertEquals("relativized incorrectly,", new URI("file:///~/therasus"),
- a.relativize(b));
- assertEquals("relativized incorrectly,",
- new URI("file:///~/dictionary"), b.relativize(a));
- }
-
- /**
- * @tests java.net.URI#resolve(java.net.URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "NullPointerException checking missed.",
- method = "resolve",
- args = {java.net.URI.class}
- )
- public void test_resolve() throws URISyntaxException {
- URI uri1 = null, uri2 = null;
- uri1 = new URI("file:/D:/one/two/three");
- uri2 = uri1.resolve(new URI(".."));
-
- assertEquals("Resolved to incorrect URI", "file:/D:/one/", uri2
- .toString());
- assertTrue("Resolved URI is not absolute", uri2.isAbsolute());
- assertFalse("Resolved URI is opaque", uri2.isOpaque());
- assertEquals("Resolved URI has incorrect scheme specific part",
- "/D:/one/", uri2.getRawSchemeSpecificPart());
- }
-
- /**
- * @tests java.net.URI#resolve(java.net.URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "resolve",
- args = {java.net.URI.class}
- )
- public void test_resolveLjava_net_URI() {
- // resolution tests
- String[][] resolveData = new String[][] {
- // authority in given URI
- { "http://www.test.com/dir",
- "//www.test.com/hello?query#fragment" },
- // no authority, absolute path
- { "http://www.test.com/dir", "/abspath/file.txt" },
- // no authority, relative paths
- { "/", "dir1/file.txt" }, { "/dir1", "dir2/file.txt" },
- { "/dir1/", "dir2/file.txt" }, { "", "dir1/file.txt" },
- { "dir1", "dir2/file.txt" }, { "dir1/", "dir2/file.txt" },
- // normalization required
- { "/dir1/dir2/../dir3/./", "dir4/./file.txt" },
- // allow a standalone fragment to be resolved
- { "http://www.google.com/hey/joe?query#fragment", "#frag2" },
- // return given when base is opaque
- { "mailto:idontexist@uk.ibm.com", "dir1/dir2" },
- // return given when given is absolute
- { "http://www.google.com/hi/joe", "http://www.oogle.com" }, };
-
- // expected results
- String[] resolveResults = new String[] {
- "http://www.test.com/hello?query#fragment",
- "http://www.test.com/abspath/file.txt", "/dir1/file.txt",
- "/dir2/file.txt", "/dir1/dir2/file.txt", "dir1/file.txt",
- "dir2/file.txt", "dir1/dir2/file.txt",
- "/dir1/dir3/dir4/file.txt",
- "http://www.google.com/hey/joe?query#frag2", "dir1/dir2",
- "http://www.oogle.com", };
-
- for (int i = 0; i < resolveResults.length; i++) {
- try {
- URI b = new URI(resolveData[i][0]);
- URI r = new URI(resolveData[i][1]);
- URI result = b.resolve(r);
- if (!result.toString().equals(resolveResults[i])) {
- fail("Error: resolve, " + resolveData[i][0] + ", "
- + resolveData[i][1] + " returned: " + result
- + ", expected:" + resolveResults[i]);
- }
- if (!b.isOpaque()) {
- assertEquals(b + " and " + result
- + " incorrectly differ in absoluteness", b
- .isAbsolute(), result.isAbsolute());
- }
- } catch (URISyntaxException e) {
- fail("Exception on resolve test on data " + resolveData[i][0]
- + ", " + resolveData[i][1] + ": " + e);
- }
- }
-
- try {
- URI b = new URI(resolveData[0][0]);
- b.resolve((URI) null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- } catch (URISyntaxException e) {
- fail("URISyntaxException was thrown.");
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "resolve",
- args = {java.lang.String.class}
- )
- public void test_resolveLjava_lang_String() {
- // resolution tests
- String[][] resolveData = new String[][] {
- // authority in given URI
- { "http://www.test.com/dir",
- "//www.test.com/hello?query#fragment" },
- // no authority, absolute path
- { "http://www.test.com/dir", "/abspath/file.txt" },
- // no authority, relative paths
- { "/", "dir1/file.txt" }, { "/dir1", "dir2/file.txt" },
- { "/dir1/", "dir2/file.txt" }, { "", "dir1/file.txt" },
- { "dir1", "dir2/file.txt" }, { "dir1/", "dir2/file.txt" },
- // normalization required
- { "/dir1/dir2/../dir3/./", "dir4/./file.txt" },
- // allow a standalone fragment to be resolved
- { "http://www.google.com/hey/joe?query#fragment", "#frag2" },
- // return given when base is opaque
- { "mailto:idontexist@uk.ibm.com", "dir1/dir2" },
- // return given when given is absolute
- { "http://www.google.com/hi/joe", "http://www.oogle.com" }, };
-
- // expected results
- String[] resolveResults = new String[] {
- "http://www.test.com/hello?query#fragment",
- "http://www.test.com/abspath/file.txt", "/dir1/file.txt",
- "/dir2/file.txt", "/dir1/dir2/file.txt", "dir1/file.txt",
- "dir2/file.txt", "dir1/dir2/file.txt",
- "/dir1/dir3/dir4/file.txt",
- "http://www.google.com/hey/joe?query#frag2", "dir1/dir2",
- "http://www.oogle.com", };
-
- for (int i = 0; i < resolveResults.length; i++) {
- try {
- URI b = new URI(resolveData[i][0]);
- URI result = b.resolve(resolveData[i][1]);
- if (!result.toString().equals(resolveResults[i])) {
- fail("Error: resolve, " + resolveData[i][0] + ", "
- + resolveData[i][1] + " returned: " + result
- + ", expected:" + resolveResults[i]);
- }
- if (!b.isOpaque()) {
- assertEquals(b + " and " + result
- + " incorrectly differ in absoluteness", b
- .isAbsolute(), result.isAbsolute());
- }
- } catch (URISyntaxException e) {
- fail("Exception on resolve test on data " + resolveData[i][0]
- + ", " + resolveData[i][1] + ": " + e);
- }
- }
-
- try {
- URI b = new URI(resolveData[0][0]);
- b.resolve((String) null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- } catch (URISyntaxException e) {
- fail("URISyntaxException was thrown.");
- }
-
- try {
- URI b = new URI(resolveData[0][0]);
- b.resolve("http://a/b/c/g?y/./x\n");
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- } catch (URISyntaxException e) {
- fail("URISyntaxException was thrown.");
- }
- }
-
- /**
- * @tests java.net.URI#toASCIIString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toASCIIString",
- args = {}
- )
- public void test_toASCIIString() throws Exception {
- URI[] uris = getUris();
-
- String[] toASCIIStringResults0 = new String[] {
- "http://user%60%20info@host/a%20path?qu%60%20ery#fr%5E%20ag",
- "http://user%C3%9F%C2%A3info@host:80/a%E2%82%ACpath?qu%C2%A9%C2%AEery#fr%C3%A4%C3%A8g",
- "ascheme://user%C3%9F%C2%A3info@host:0/a%E2%82%ACpath?qu%C2%A9%C2%AEery#fr%C3%A4%C3%A8g",
- "http://user%2560%2520info@host:80/a%2520path?qu%2560%2520ery#fr%255E%2520ag",
- "http://user%25C3%259F%25C2%25A3info@host/a%25E2%2582%25ACpath?qu%25C2%25A9%25C2%25AEery#fr%25C3%25A4%25C3%25A8g",
- "ascheme://user%C3%9F%C2%A3info@host:80/a%E2%82%ACpath?qu%C2%A9%C2%AEery#fr%C3%A4%C3%A8g",
- "http://user%60%20info@host:81/a%20path?qu%60%20ery#fr%5E%20ag",
- "http://user%25info@host:0/a%25path?que%25ry#f%25rag",
- "mailto:user@domain.com", "../adirectory/file.html#",
- "news:comp.infosystems.www.servers.unix", "#fragment",
- "telnet://server.org", "http://reg:istry?query",
- "file:///c:/temp/calculate.pl?" };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].toASCIIString();
- assertTrue("Error: For URI \"" + uris[i].toString()
- + "\", toASCIIString() returned: " + result
- + ", expected: " + toASCIIStringResults0[i], result
- .equals(toASCIIStringResults0[i]));
- }
-
- String[] toASCIIStringData = new String[] {
- "http://www.test.com/\u00DF/dir/",
- "http://www.test.com/\u20AC/dir", "http://www.\u20AC.com/dir",
- "http://www.test.com/\u20AC/dir/file#fragment",
- "mailto://user@domain.com", "mailto://user\u00DF@domain.com", };
-
- String[] toASCIIStringResults = new String[] {
- "http://www.test.com/%C3%9F/dir/",
- "http://www.test.com/%E2%82%AC/dir",
- "http://www.%E2%82%AC.com/dir",
- "http://www.test.com/%E2%82%AC/dir/file#fragment",
- "mailto://user@domain.com", "mailto://user%C3%9F@domain.com", };
-
- for (int i = 0; i < toASCIIStringData.length; i++) {
- URI test = new URI(toASCIIStringData[i]);
- String result = test.toASCIIString();
- assertTrue("Error: new URI(\"" + toASCIIStringData[i]
- + "\").toASCIIString() returned: " + result
- + ", expected: " + toASCIIStringResults[i], result
- .equals(toASCIIStringResults[i]));
- }
- }
-
- /**
- * @tests java.net.URI#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() throws Exception {
- URI[] uris = getUris();
-
- String[] toStringResults = {
- "http://user%60%20info@host/a%20path?qu%60%20ery#fr%5E%20ag",
- "http://user%C3%9F%C2%A3info@host:80/a%E2%82%ACpath?qu%C2%A9%C2%AEery#fr%C3%A4%C3%A8g",
- "ascheme://user\u00DF\u00A3info@host:0/a\u20ACpath?qu\u00A9\u00AEery#fr\u00E4\u00E8g",
- // =
- // "ascheme://user\u00df\u00a3info@host:0/a\u0080path?qu\u00a9\u00aeery#fr\u00e4\u00e8g",
- "http://user%2560%2520info@host:80/a%2520path?qu%2560%2520ery#fr%255E%2520ag",
- "http://user%25C3%259F%25C2%25A3info@host/a%25E2%2582%25ACpath?qu%25C2%25A9%25C2%25AEery#fr%25C3%25A4%25C3%25A8g",
- "ascheme://user\u00DF\u00A3info@host:80/a\u20ACpath?qu\u00A9\u00AEery#fr\u00E4\u00E8g",
- // =
- // "ascheme://user\u00df\u00a3info@host:80/a\u0080path?qu\u00a9\u00aeery#fr\u00e4\u00e8g",
- "http://user%60%20info@host:81/a%20path?qu%60%20ery#fr%5E%20ag",
- "http://user%25info@host:0/a%25path?que%25ry#f%25rag",
- "mailto:user@domain.com", "../adirectory/file.html#",
- "news:comp.infosystems.www.servers.unix", "#fragment",
- "telnet://server.org", "http://reg:istry?query",
- "file:///c:/temp/calculate.pl?" };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].toString();
- assertTrue("Error: For URI \"" + uris[i].toString()
- + "\", toString() returned: " + result + ", expected: "
- + toStringResults[i], result.equals(toStringResults[i]));
- }
- }
-
- /**
- * @tests java.net.URI#toURL()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toURL",
- args = {}
- )
- public void test_toURL() throws Exception {
- String absoluteuris[] = new String[] { "mailto:user@ca.ibm.com",
- "urn:isbn:123498989h", "news:software.ibm.com",
- "http://www.amazon.ca", "file:///d:/temp/results.txt",
- "scheme:ssp", };
-
- String relativeuris[] = new String[] { "calculate.pl?isbn=123498989h",
- "?isbn=123498989h", "//www.amazon.ca", "a.html", "#top",
- "//pc1/", "//user@host/path/file" };
-
- for (int i = 0; i < absoluteuris.length; i++) {
- try {
- new URI(absoluteuris[i]).toURL();
- } catch (MalformedURLException e) {
- // not all the URIs can be translated into valid URLs
- }
- }
-
- for (int i = 0; i < relativeuris.length; i++) {
- try {
- new URI(relativeuris[i]).toURL();
- fail("Expected IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/URLClassLoaderTest.java b/luni/src/test/java/tests/api/java/net/URLClassLoaderTest.java
deleted file mode 100644
index 26672d3..0000000
--- a/luni/src/test/java/tests/api/java/net/URLClassLoaderTest.java
+++ /dev/null
@@ -1,718 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.BrokenTest;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.File;
-import java.io.FilePermission;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.DatagramSocket;
-import java.net.MalformedURLException;
-import java.net.SocketException;
-import java.net.URI;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.net.URLStreamHandler;
-import java.net.URLStreamHandlerFactory;
-import java.security.CodeSource;
-import java.security.Permission;
-import java.security.PermissionCollection;
-import java.security.Permissions;
-import java.security.cert.Certificate;
-import java.util.Enumeration;
-import java.util.NoSuchElementException;
-import java.util.StringTokenizer;
-import java.util.Vector;
-import java.util.jar.Manifest;
-
-import org.apache.harmony.luni.util.InvalidJarIndexException;
-import org.apache.harmony.security.tests.support.TestCertUtils;
-
-import tests.support.Support_Configuration;
-import tests.support.resource.Support_Resources;
-
-@TestTargetClass(URLClassLoader.class)
-public class URLClassLoaderTest extends junit.framework.TestCase {
-
- class BogusClassLoader extends ClassLoader {
- public URL getResource(String res) {
- try {
- return new URL("http://test/BogusClassLoader");
- } catch (MalformedURLException e) {
- return null;
- }
- }
- }
-
- public class URLClassLoaderExt extends URLClassLoader {
-
- public URLClassLoaderExt(URL[] urls) {
- super(urls);
- }
-
- public Class<?> findClass(String cl) throws ClassNotFoundException {
- return super.findClass(cl);
- }
- }
-
- URLClassLoader ucl;
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkCreateClassLoader() {
- throw new SecurityException();
- }
- };
-
- /**
- * @tests java.net.URLClassLoader#URLClassLoader(java.net.URL[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URLClassLoader",
- args = {java.net.URL[].class}
- )
- public void test_Constructor$Ljava_net_URL() throws MalformedURLException {
- URL[] u = new URL[0];
- ucl = new URLClassLoader(u);
- assertTrue("Failed to set parent", ucl != null
- && ucl.getParent() == URLClassLoader.getSystemClassLoader());
-
-
- URL [] urls = {new URL("http://foo.com/foo"),
- new URL("jar:file://foo.jar!/foo.c"),
- new URL("ftp://foo1/foo2/foo.c")};
-
- URLClassLoader ucl1 = new URLClassLoader(urls);
- assertTrue(urls.length == ucl1.getURLs().length);
-
- try {
- Class.forName("test", false, ucl);
- fail("Should throw ClassNotFoundException");
- } catch (ClassNotFoundException e) {
- // expected
- }
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new URLClassLoader(u);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- try {
- new URLClassLoader(new URL[] { null });
- } catch(Exception e) {
- fail("Unexpected exception was thrown: " + e.getMessage());
- }
- }
-
- /**
- * @tests java.net.URLClassLoader#URLClassLoader(java.net.URL[],
- * java.lang.ClassLoader)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URLClassLoader",
- args = {java.net.URL[].class, java.lang.ClassLoader.class}
- )
- public void test_Constructor$Ljava_net_URLLjava_lang_ClassLoader() {
- ClassLoader cl = new BogusClassLoader();
- URL[] u = new URL[0];
- ucl = new URLClassLoader(u, cl);
- URL res = ucl.getResource("J");
- assertNotNull(res);
- assertEquals("Failed to set parent", "/BogusClassLoader", res.getFile());
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new URLClassLoader(u, cl);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.net.URLClassLoader#findResources(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException checking missed.",
- method = "findResources",
- args = {java.lang.String.class}
- )
- @BrokenTest("web address used from support doesn't work anymore")
- public void test_findResourcesLjava_lang_String() throws IOException {
- Enumeration res = null;
- String[] resValues = { "This is a test resource file.",
- "This is a resource from a subdir" };
-
- URL[] urls = new URL[2];
- urls[0] = new URL(Support_Resources.getResourceURL("/"));
- urls[1] = new URL(Support_Resources.getResourceURL("/subdir1/"));
- ucl = new URLClassLoader(urls);
- res = ucl.findResources("RESOURCE.TXT");
- assertNotNull("Failed to locate resources", res);
-
- int i = 0;
- while (res.hasMoreElements()) {
- StringBuffer sb = new StringBuffer();
- InputStream is = ((URL) res.nextElement()).openStream();
- int c;
- while ((c = is.read()) != -1) {
- sb.append((char) c);
- }
- assertEquals("Returned incorrect resource/or in wrong order",
- resValues[i++], sb.toString());
- }
- assertTrue("Incorrect number of resources returned: " + i, i == 2);
- }
-
- /**
- * @tests java.net.URLClassLoader#getURLs()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getURLs",
- args = {}
- )
- public void test_getURLs() throws MalformedURLException {
- URL[] urls = new URL[4];
- urls[0] = new URL("http://" + Support_Configuration.HomeAddress);
- urls[1] = new URL("http://" + Support_Configuration.TestResources + "/");
- urls[2] = new URL("ftp://" + Support_Configuration.TestResources + "/");
- urls[3] = new URL("jar:file:c://" + Support_Configuration.TestResources
- + "!/");
- ucl = new URLClassLoader(urls);
- URL[] ucUrls = ucl.getURLs();
- for (int i = 0; i < urls.length; i++) {
- assertEquals("Returned incorrect URL[]", urls[i], ucUrls[i]);
- }
- }
-
- /**
- * @tests java.net.URLClassLoader#newInstance(java.net.URL[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "newInstance",
- args = {java.net.URL[].class}
- )
- @BrokenTest("web address used from support doesn't work anymore")
- public void test_newInstance$Ljava_net_URL() throws MalformedURLException,
- ClassNotFoundException {
- // Verify that loaded class' have correct permissions
- Class cl = null;
- URL res = null;
- URL[] urls = new URL[1];
- urls[0] = new URL(Support_Resources.getResourceURL("/UCL/UCL.jar"));
- ucl = URLClassLoader.newInstance(urls);
- cl = ucl.loadClass("ucl.ResClass");
-
- res = cl.getClassLoader().getResource("XX.class");
- assertNotNull("Failed to load class", cl);
- assertNotNull(
- "Loaded class unable to access resource from same codeSource",
- res);
- cl = null;
-
- urls[0] = new URL("jar:"
- + Support_Resources.getResourceURL("/UCL/UCL.jar!/"));
- ucl = URLClassLoader.newInstance(urls);
- cl = ucl.loadClass("ucl.ResClass");
- assertNotNull("Failed to load class from explicit jar URL", cl);
- }
-
- /**
- * @tests java.net.URLClassLoader#newInstance(java.net.URL[],
- * java.lang.ClassLoader)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "newInstance",
- args = {java.net.URL[].class, java.lang.ClassLoader.class}
- )
- public void test_newInstance$Ljava_net_URLLjava_lang_ClassLoader() {
- ClassLoader cl = new BogusClassLoader();
- URL[] u = new URL[0];
- ucl = URLClassLoader.newInstance(u, cl);
- URL res = ucl.getResource("J");
- assertNotNull(res);
- assertEquals("Failed to set parent", "/BogusClassLoader", res.getFile());
- }
-
- /**
- * @tests java.net.URLClassLoader#URLClassLoader(java.net.URL[],
- * java.lang.ClassLoader, java.net.URLStreamHandlerFactory)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URLClassLoader",
- args = {java.net.URL[].class, java.lang.ClassLoader.class,
- java.net.URLStreamHandlerFactory.class}
- )
- public void test_Constructor$Ljava_net_URLLjava_lang_ClassLoaderLjava_net_URLStreamHandlerFactory() {
- class TestFactory implements URLStreamHandlerFactory {
- public URLStreamHandler createURLStreamHandler(String protocol) {
- return null;
- }
- }
- ClassLoader cl = new BogusClassLoader();
- URL[] u = new URL[0];
- ucl = new URLClassLoader(u, cl, new TestFactory());
- URL res = ucl.getResource("J");
- assertNotNull(res);
- assertEquals("Failed to set parent", "/BogusClassLoader", res.getFile());
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new URLClassLoader(u, cl, new TestFactory());
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addURL",
- args = { URL.class }
- )
- public void test_addURLLjava_net_URL() throws MalformedURLException {
- URL[] u = new URL[0];
-
- URL [] urls = {new URL("http://foo.com/foo"),
- new URL("jar:file://foo.jar!/foo.c"),
- new URL("ftp://foo1/foo2/foo.c"), null};
-
- TestURLClassLoader tucl = new TestURLClassLoader(u);
-
- for(int i = 0; i < urls.length;) {
- tucl.addURL(urls[i]);
- i++;
- URL [] result = tucl.getURLs();
- assertEquals("Result array length is incorrect: " + i,
- i, result.length);
- for(int j = 0; j < result.length; j++) {
- assertEquals("Result array item is incorrect: " + j,
- urls[j], result[j]);
- }
- }
- }
-
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "",
- method = "getPermissions",
- args = { CodeSource.class }
- )
- public void test_getPermissions() throws MalformedURLException {
- URL url = new URL("http://" + Support_Configuration.SpecialInetTestAddress);
- Certificate[] chain = TestCertUtils.getCertChain();
- CodeSource cs = new CodeSource(url, chain);
- TestURLClassLoader cl = new TestURLClassLoader(new URL[] {url});
- PermissionCollection permCol = cl.getPermissions(cs);
- assertNotNull(permCol);
-
- URL url1 = new URL("file://foo/foo.c");
- TestURLClassLoader cl1 = new TestURLClassLoader(new URL[] {url});
- CodeSource cs1 = new CodeSource(url1, chain);
- PermissionCollection permCol1 = cl1.getPermissions(cs1);
- assertNotNull(permCol1);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "definePackage",
- args = { java.lang.String.class, java.util.jar.Manifest.class,
- java.net.URL.class }
- )
- public void test_definePackage() throws MalformedURLException {
- Manifest manifest = new Manifest();
- URL[] u = new URL[0];
- TestURLClassLoader tucl = new TestURLClassLoader(u);
-
- URL [] urls = {new URL("http://foo.com/foo"),
- new URL("jar:file://foo.jar!/foo.c"),
- new URL("ftp://foo1/foo2/foo.c"),
- new URL("file://new/package/name/"),
- null};
-
- String packageName = "new.package.name";
-
- for(int i = 0; i < urls.length; i++) {
- Package pack = tucl.definePackage(packageName + i, manifest, urls[i]);
- assertEquals(packageName + i, pack.getName());
- assertNull("Implementation Title is not null",
- pack.getImplementationTitle());
- assertNull("Implementation Vendor is not null",
- pack.getImplementationVendor());
- assertNull("Implementation Version is not null.",
- pack.getImplementationVersion());
- }
-
- try {
- tucl.definePackage(packageName + "0", manifest, null);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- class TestURLClassLoader extends URLClassLoader {
- public TestURLClassLoader(URL[] urls) {
- super(urls);
- }
-
- public void addURL(URL url) {
- super.addURL(url);
- }
-
- public Package definePackage(String name,
- Manifest man,
- URL url)
- throws IllegalArgumentException {
- return super.definePackage(name, man, url);
- }
-
- public Class<?> findClass(String name)
- throws ClassNotFoundException {
- return super.findClass(name);
- }
-
- protected PermissionCollection getPermissions(CodeSource codesource) {
- return super.getPermissions(codesource);
- }
- }
-
- /**
- * @throws ClassNotFoundException
- * @throws IOException
- * @tests java.net.URLClassLoader#findClass(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "findClass",
- args = {java.lang.String.class}
- )
- @BrokenTest("")
- public void test_findClassLjava_lang_String()
- throws ClassNotFoundException, IOException {
- File resources = Support_Resources.createTempFolder();
- String resPath = resources.toString();
- if (resPath.charAt(0) == '/' || resPath.charAt(0) == '\\') {
- resPath = resPath.substring(1);
- }
-
- java.net.URL[] urls = new java.net.URL[1];
- java.net.URLClassLoader ucl = null;
- boolean classFound;
- boolean exception;
- boolean goodException;
- Enumeration en;
- boolean resourcesFound;
- Support_Resources.copyFile(resources, "JarIndex", "hyts_11.jar");
- Support_Resources.copyFile(resources, "JarIndex", "hyts_12.jar");
- Support_Resources.copyFile(resources, "JarIndex", "hyts_13.jar");
- Support_Resources.copyFile(resources, "JarIndex", "hyts_14.jar");
- urls[0] = new URL("file:/" + resPath + "/JarIndex/hyts_11.jar");
- ucl = URLClassLoader.newInstance(urls, null);
- URL resURL = ucl.findResource("Test.txt");
- URL reference = new URL("jar:file:/" + resPath.replace('\\', '/')
- + "/JarIndex/hyts_14.jar!/Test.txt");
- assertTrue("Resource not found: " + resURL + " ref: " + reference,
- resURL.equals(reference));
-
- Class c = Class.forName("cpack.CNothing", true, ucl);
- assertNotNull(c);
-
- Support_Resources.copyFile(resources, "JarIndex", "hyts_21.jar");
- Support_Resources.copyFile(resources, "JarIndex", "hyts_22.jar");
- Support_Resources.copyFile(resources, "JarIndex", "hyts_23.jar");
- urls[0] = new URL("file:/" + resPath + "/JarIndex/hyts_21.jar");
- ucl = URLClassLoader.newInstance(urls, null);
- en = ucl.findResources("bpack/");
-
- try {
- resourcesFound = true;
- URL url1 = (URL) en.nextElement();
- URL url2 = (URL) en.nextElement();
- System.out.println(url1);
- System.out.println(url2);
- resourcesFound = resourcesFound
- && url1.equals(new URL("jar:file:/"
- + resPath.replace('\\', '/')
- + "/JarIndex/hyts_22.jar!/bpack/"));
- resourcesFound = resourcesFound
- && url2.equals(new URL("jar:file:/"
- + resPath.replace('\\', '/')
- + "/JarIndex/hyts_23.jar!/bpack/"));
- if (en.hasMoreElements()) {
- resourcesFound = false;
- }
- } catch (NoSuchElementException e) {
- resourcesFound = false;
- }
- assertTrue("Resources not found (1)", resourcesFound);
-
- Class c2 = Class.forName("bpack.Homer", true, ucl);
- assertNotNull(c2);
-
- try {
- Class.forName("bpack.Bart", true, ucl);
- fail("InvalidJarIndexException should be thrown");
- } catch (InvalidJarIndexException e) {
- // expected
- }
-
- try {
- Class.forName("Main4", true, ucl);
- fail("ClassNotFoundException should be thrown");
- } catch (ClassNotFoundException e) {
- // Expected
- }
-
- Support_Resources.copyFile(resources, "JarIndex", "hyts_22-new.jar");
- urls[0] = new URL("file:/" + resPath + "/JarIndex/hyts_22-new.jar");
- ucl = URLClassLoader.newInstance(urls, null);
- assertNotNull("Cannot find resource", ucl.findResource("cpack/"));
- Support_Resources.copyFile(resources, "JarIndex", "hyts_11.jar");
- urls[0] = new URL("file:/" + resPath + "/JarIndex/hyts_31.jar");
- ucl = URLClassLoader.newInstance(urls, null);
-
- try {
- Class.forName("cpack.Mock", true, ucl);
- fail("ClassNotFoundException should be thrown");
- } catch (ClassNotFoundException e) {
- // Expected
- }
-
- // testing circular reference
- Support_Resources.copyFile(resources, "JarIndex", "hyts_41.jar");
- Support_Resources.copyFile(resources, "JarIndex", "hyts_42.jar");
- urls[0] = new URL("file:/" + resPath + "/JarIndex/hyts_41.jar");
- ucl = URLClassLoader.newInstance(urls, null);
- en = ucl.findResources("bpack/");
- resourcesFound = resourcesFound
- && ((URL) en.nextElement()).equals(new URL("jar:file:/"
- + resPath.replace('\\', '/')
- + "/JarIndex/hyts_42.jar!/bpack/"));
- assertTrue("Resources not found (2)", resourcesFound);
- assertFalse("No more resources expected", en.hasMoreElements());
-
- // Regression test for HARMONY-2357.
- try {
- URLClassLoaderExt cl = new URLClassLoaderExt(new URL[557]);
- cl.findClass("0");
- fail("NullPointerException should be thrown");
- } catch (NullPointerException npe) {
- // Expected
- }
-
- // Regression test for HARMONY-2871.
- URLClassLoader cl = new URLClassLoader(new URL[] { new URL("file:/foo.jar") });
-
- try {
- Class.forName("foo.Foo", false, cl);
- } catch (Exception ex) {
- // Don't care
- }
-
- try {
- Class.forName("foo.Foo", false, cl);
- fail("NullPointerException should be thrown");
- } catch (ClassNotFoundException cnfe) {
- // Expected
- }
- }
-
- /**
- * @tests java.net.URLClassLoader#findResource(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "findResource",
- args = {java.lang.String.class}
- )
- @BrokenTest("web address used from support doesn't work anymore")
- public void test_findResourceLjava_lang_String()
- throws MalformedURLException {
- URL res = null;
-
- URL[] urls = new URL[2];
- urls[0] = new URL("http://" + Support_Configuration.HomeAddress);
- urls[1] = new URL(Support_Resources.getResourceURL("/"));
- ucl = new URLClassLoader(urls);
- res = ucl.findResource("RESOURCE.TXT");
- assertNotNull("Failed to locate resource", res);
-
- StringBuffer sb = new StringBuffer();
- try {
- java.io.InputStream is = res.openStream();
-
- int c;
- while ((c = is.read()) != -1) {
- sb.append((char) c);
- }
- is.close();
- } catch (IOException e) {
- }
- assertTrue("Returned incorrect resource", !sb.toString().equals(
- "This is a test resource file"));
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Checks getResource, indirectly checks findResource",
- method = "getResource",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Checks getResource, indirectly checks findResource",
- method = "findResource",
- args = {java.lang.String.class}
- )
- })
- public void testFindResource_H3461() throws Exception {
- File tmpDir = new File(System.getProperty("java.io.tmpdir"));
- File dir = new File(tmpDir, "encode#me");
- File f, f2;
- URLClassLoader loader;
- URL dirUrl;
-
- if (!dir.exists()) {
- dir.mkdir();
- }
- dir.deleteOnExit();
- dirUrl = dir.toURI().toURL();
- loader = new URLClassLoader( new URL[] { dirUrl });
-
- f = File.createTempFile("temp", ".dat", dir);
- f.deleteOnExit();
- f2 = File.createTempFile("bad#name#", ".dat", dir);
- f2.deleteOnExit();
-
- assertNotNull("Unable to load resource from path with problematic name",
- loader.getResource(f.getName()));
- assertEquals("URL was not correctly encoded",
- f2.toURI().toURL(),
- loader.getResource(f2.getName()));
- }
-
- /**
- * @tests java.net.URLClassLoader#getResource(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getResource",
- args = {java.lang.String.class}
- )
- public void test_getResourceLjava_lang_String()
- throws MalformedURLException {
- URL url1 = new URL("file:///");
- URLClassLoader loader = new URLClassLoader(new URL[] { url1 }, null);
- long start = System.currentTimeMillis();
- // try without the leading /
- URL result = loader.getResource("dir1/file1");
- long end = System.currentTimeMillis();
- long time = end - start;
- if (time < 100) {
- time = 100;
- }
-
- start = System.currentTimeMillis();
- // try with the leading forward slash
- result = loader.getResource("/dir1/file1");
- end = System.currentTimeMillis();
- long uncTime = end - start;
- assertTrue("too long. UNC path formed? UNC time: " + uncTime
- + " regular time: " + time, uncTime <= (time * 4));
- }
-
- /**
- * Regression for Harmony-2237
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Regression test",
- method = "findResource",
- args = {java.lang.String.class}
- )
- public void test_getResource() throws Exception {
- URLClassLoader urlLoader = getURLClassLoader();
- assertNull(urlLoader.findResource("XXX")); //$NON-NLS-1$
- }
-
- private static URLClassLoader getURLClassLoader() {
- String classPath = System.getProperty("java.class.path");
- StringTokenizer tok = new StringTokenizer(classPath, File.pathSeparator);
- Vector<URL> urlVec = new Vector<URL>();
- String resPackage = Support_Resources.RESOURCE_PACKAGE;
- try {
- while (tok.hasMoreTokens()) {
- String path = tok.nextToken();
- String url;
- if (new File(path).isDirectory())
- url = "file:" + path + resPackage + "subfolder/";
- else
- url = "jar:file:" + path + "!" + resPackage + "subfolder/";
- urlVec.addElement(new URL(url));
- }
- } catch (MalformedURLException e) {
- // do nothing
- }
- URL[] urls = new URL[urlVec.size()];
- for (int i = 0; i < urlVec.size(); i++) {
- urls[i] = urlVec.elementAt(i);
- }
- URLClassLoader loader = new URLClassLoader(urls, null);
- return loader;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/URLDecoderTest.java b/luni/src/test/java/tests/api/java/net/URLDecoderTest.java
deleted file mode 100644
index e960f25..0000000
--- a/luni/src/test/java/tests/api/java/net/URLDecoderTest.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URL;
-import java.net.URLDecoder;
-import java.net.URLEncoder;
-
-import tests.support.Support_Configuration;
-
-@TestTargetClass(URLDecoder.class)
-public class URLDecoderTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.URLDecoder#URLDecoder()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URLDecoder",
- args = {}
- )
- public void test_Constructor() throws Exception {
- URLDecoder ud = new URLDecoder();
- assertNotNull("Constructor failed.", ud);
- }
-
- /**
- * @tests java.net.URLDecoder#decode(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "decode",
- args = {java.lang.String.class}
- )
- public void test_decodeLjava_lang_String() throws Exception {
- // Test for method java.lang.String
- // java.net.URLDecoder.decode(java.lang.String)
- final String URL = "http://" + Support_Configuration.HomeAddress;
- final String URL2 = "telnet://justWantToHaveFun.com:400";
- final String URL3 = "file://myServer.org/a file with spaces.jpg";
- assertTrue("1. Incorrect encoding/decoding", URLDecoder.decode(
- URLEncoder.encode(URL)).equals(URL));
- assertTrue("2. Incorrect encoding/decoding", URLDecoder.decode(
- URLEncoder.encode(URL2)).equals(URL2));
- assertTrue("3. Incorrect encoding/decoding", URLDecoder.decode(
- URLEncoder.encode(URL3)).equals(URL3));
- }
-
- /**
- * @tests java.net.URLDecoder#decode(java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "decode",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_decodeLjava_lang_String_Ljava_lang_String() {
- // Regression for HARMONY-467
-
- String enc = "UTF-8";
-
- String [] urls = { "http://" + Support_Configuration.HomeAddress +
- "/test?hl=en&q=te+st",
- "file://a+b/c/d.e-f*g_+l",
- "jar:file://a.jar+!/b.c/",
- "ftp://test:pwd@localhost:2121/%D0%9C",
- "%D0%A2%D0%B5%D1%81%D1%82+URL+for+test"};
-
- String [] expected = {"http://" + Support_Configuration.HomeAddress +
- "/test?hl=en&q=te st",
- "file://a b/c/d.e-f*g_ l",
- "jar:file://a.jar !/b.c/"};
-
- for(int i = 0; i < urls.length - 2; i++) {
- try {
- assertEquals(expected[i], URLDecoder.decode(urls[i], enc));
- } catch (UnsupportedEncodingException e) {
- fail("UnsupportedEncodingException: " + e.getMessage());
- }
- }
-
- try {
- URLDecoder.decode(urls[urls.length - 2], enc);
- URLDecoder.decode(urls[urls.length - 1], enc);
- } catch (UnsupportedEncodingException e) {
- fail("UnsupportedEncodingException: " + e.getMessage());
- }
-
- try {
- URLDecoder.decode("", "");
- fail("UnsupportedEncodingException expected");
- } catch (UnsupportedEncodingException e) {
- //expected
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/URLEncoderTest.java b/luni/src/test/java/tests/api/java/net/URLEncoderTest.java
deleted file mode 100644
index 5d4e403..0000000
--- a/luni/src/test/java/tests/api/java/net/URLEncoderTest.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URLDecoder;
-import java.net.URLEncoder;
-
-import tests.support.Support_Configuration;
-
-@TestTargetClass(URLEncoder.class)
-public class URLEncoderTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.URLEncoder#encode(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "encode",
- args = {java.lang.String.class}
- )
- public void test_encodeLjava_lang_String() {
- // Test for method java.lang.String
- // java.net.URLEncoder.encode(java.lang.String)
- final String URL = "http://" + Support_Configuration.HomeAddress;
- final String URL2 = "telnet://justWantToHaveFun.com:400";
- final String URL3 = "file://myServer.org/a file with spaces.jpg";
- try {
- assertTrue("1. Incorrect encoding/decoding", URLDecoder.decode(
- URLEncoder.encode(URL)).equals(URL));
- assertTrue("2. Incorrect encoding/decoding", URLDecoder.decode(
- URLEncoder.encode(URL2)).equals(URL2));
- assertTrue("3. Incorrect encoding/decoding", URLDecoder.decode(
- URLEncoder.encode(URL3)).equals(URL3));
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "encode",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_encodeLjava_lang_StringLjava_lang_String() {
-
- String enc = "UTF-8";
-
- String [] urls = {"http://" + Support_Configuration.HomeAddress +
- "/test?hl=en&q=te st",
- "file://a b/c/d.e-f*g_ l",
- "jar:file://a.jar !/b.c/\u1052",
- "ftp://test:pwd@localhost:2121/%D0%9C"};
-
- String [] expected = { "http%3A%2F%2Fjcltest.apache.org%2Ftest%3Fhl%" +
- "3Den%26q%3Dte+st",
- "file%3A%2F%2Fa+b%2Fc%2Fd.e-f*g_+l",
- "jar%3Afile%3A%2F%2Fa.jar+%21%2Fb.c%2F%E1%81%92"};
-
- for(int i = 0; i < urls.length-1; i++) {
- try {
- String encodedString = URLEncoder.encode(urls[i], enc);
- assertEquals(expected[i], encodedString);
- assertEquals(urls[i], URLDecoder.decode(encodedString, enc));
- } catch (UnsupportedEncodingException e) {
- fail("UnsupportedEncodingException: " + e.getMessage());
- }
- }
-
- try {
- String encodedString = URLEncoder.encode(urls[urls.length - 1], enc);
- assertEquals(urls[urls.length - 1], URLDecoder.decode(encodedString, enc));
- } catch (UnsupportedEncodingException e) {
- fail("UnsupportedEncodingException: " + e.getMessage());
- }
-
- try {
- URLDecoder.decode("", "");
- fail("UnsupportedEncodingException expected");
- } catch (UnsupportedEncodingException e) {
- //expected
- }
-
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/URLStreamHandlerFactoryTest.java b/luni/src/test/java/tests/api/java/net/URLStreamHandlerFactoryTest.java
deleted file mode 100644
index 7f4d735..0000000
--- a/luni/src/test/java/tests/api/java/net/URLStreamHandlerFactoryTest.java
+++ /dev/null
@@ -1,132 +0,0 @@
-package tests.api.java.net;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import tests.support.Support_Configuration;
-
-import java.io.IOException;
-import java.lang.reflect.Field;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLConnection;
-import java.net.URLStreamHandler;
-import java.net.URLStreamHandlerFactory;
-
-@TestTargetClass(URLStreamHandlerFactory.class)
-public class URLStreamHandlerFactoryTest extends TestCase {
-
- URLStreamHandlerFactory oldFactory = null;
- Field factoryField = null;
-
- boolean isTestable = false;
-
- boolean isOpenConnectionCalled = false;
- boolean isCreateURLStreamHandlerCalled = false;
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "createURLStreamHandler",
- args = {java.lang.String.class}
- )
- public void test_createURLStreamHandler() throws MalformedURLException {
-
- if(isTestable) {
-
- TestURLStreamHandlerFactory shf = new TestURLStreamHandlerFactory();
- assertFalse(isCreateURLStreamHandlerCalled);
- URL.setURLStreamHandlerFactory(shf);
- URL url = new URL("http://" +
- Support_Configuration.SpecialInetTestAddress);
-
- try {
- url.openConnection();
- assertTrue(isCreateURLStreamHandlerCalled);
- assertTrue(isOpenConnectionCalled);
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
-
- }
-
- try {
- URL.setURLStreamHandlerFactory(shf);
- fail("java.lang.Error was not thrown.");
- } catch(java.lang.Error e) {
- //expected
- }
-
- try {
- URL.setURLStreamHandlerFactory(null);
- fail("java.lang.Error was not thrown.");
- } catch(java.lang.Error e) {
- //expected
- }
-
- } else {
- TestURLStreamHandlerFactory shf = new TestURLStreamHandlerFactory();
- URLStreamHandler sh = shf.createURLStreamHandler("");
- assertNotNull(sh.toString());
- }
- }
-
- public void setUp() {
- Field [] fields = URL.class.getDeclaredFields();
- int counter = 0;
- for (Field field : fields) {
- if (URLStreamHandlerFactory.class.equals(field.getType())) {
- counter++;
- factoryField = field;
- }
- }
-
- if(counter == 1) {
-
- isTestable = true;
-
- factoryField.setAccessible(true);
- try {
- oldFactory = (URLStreamHandlerFactory) factoryField.get(null);
- } catch (IllegalArgumentException e) {
- fail("IllegalArgumentException was thrown during setUp: "
- + e.getMessage());
- } catch (IllegalAccessException e) {
- fail("IllegalAccessException was thrown during setUp: "
- + e.getMessage());
- }
- }
- }
-
- public void tearDown() {
- if(isTestable) {
- try {
- factoryField.set(null, oldFactory);
- } catch (IllegalArgumentException e) {
- fail("IllegalArgumentException was thrown during tearDown: "
- + e.getMessage());
- } catch (IllegalAccessException e) {
- fail("IllegalAccessException was thrown during tearDown: "
- + e.getMessage());
- }
- }
- }
-
- class TestURLStreamHandlerFactory implements URLStreamHandlerFactory {
-
- public URLStreamHandler createURLStreamHandler(String protocol) {
- isCreateURLStreamHandlerCalled = true;
- return new TestURLStreamHandler();
- }
- }
-
- class TestURLStreamHandler extends URLStreamHandler {
- @Override
- protected URLConnection openConnection(URL u) throws IOException {
- isOpenConnectionCalled = true;
- return null;
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/URLStreamHandlerTest.java b/luni/src/test/java/tests/api/java/net/URLStreamHandlerTest.java
deleted file mode 100644
index 8b365c5..0000000
--- a/luni/src/test/java/tests/api/java/net/URLStreamHandlerTest.java
+++ /dev/null
@@ -1,328 +0,0 @@
-package tests.api.java.net;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.MalformedURLException;
-import java.net.Proxy;
-import java.net.URL;
-import java.net.URLConnection;
-import java.net.URLStreamHandler;
-import java.net.UnknownHostException;
-
-@TestTargetClass(URLStreamHandler.class)
-public class URLStreamHandlerTest extends TestCase {
-
- MockURLStreamHandler handler = null;
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {URL.class, URL.class}
- )
- public void test_equalsLjava_net_URLLjava_net_URL() {
- try {
- URL url1 = new URL("ftp://test_url/test?a=b&c=%D0+%D1");
- URL url2 = new URL("http://test_url/test?a=b&c=%D0+%D1");
- assertFalse(url1.equals(url2));
-
- URL url3 = new URL("http://test_url+/test?a=b&c=%D0+%D1");
- assertFalse(handler.equals(url1,url2));
-
- try {
- assertFalse(handler.equals(null, url1));
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- } catch (MalformedURLException e) {
- fail("MalformedURLException was thrown.");
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDefaultPort",
- args = {}
- )
- public void test_getDefaultPort() {
- assertEquals(-1, handler.getDefaultPort());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getHostAddress",
- args = {URL.class}
- )
- public void test_getHostAddress() throws MalformedURLException,
- UnknownHostException {
- URL url1 = new URL("ftp://test_url/test?a=b&c=%D0+%D1");
- assertNull(handler.getHostAddress(url1));
-
- URL url2 = new URL("http://test:pwd@host/test?a=b&c=%D0+%D1");
- assertNull("testHost", handler.getHostAddress(url2));handler.getHostAddress(url2);
-
- URL url3 = new URL("http://localhost/test");
- assertEquals(InetAddress.getLocalHost(), handler.getHostAddress(url3));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {URL.class}
- )
- public void test_hashCodeLjava_net_URL() {
- try {
- URL url1 = new URL("ftp://test_url/test?a=b&c=%D0+%D1");
- URL url2 = new URL("http://test_url/test?a=b&c=%D0+%D1");
- assertTrue(handler.hashCode(url1) != handler.hashCode(url2));
-
- URL url3 = new URL("http://test_url+/test?a=b&c=%D0+%D1");
- assertFalse(handler.equals(url1,url2));
-
- try {
- handler.hashCode(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- } catch (MalformedURLException e) {
- fail("MalformedURLException was thrown.");
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hostsEqual",
- args = {URL.class, URL.class}
- )
- public void test_hostsEqualLjava_net_URLLjava_net_URL() throws
- MalformedURLException {
- URL url1 = new URL("ftp://localhost:21/*test");
- URL url2 = new URL("http://127.0.0.1/_test");
- assertTrue(handler.hostsEqual(url1, url2));
-
- URL url3 = new URL("http://foo/_test_goo");
- assertFalse(handler.hostsEqual(url1, url3));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "openConnection",
- args = { URL.class }
- )
- public void test_openConnectionLjava_net_URL() throws IOException {
- // abstract method, it doesn't check anything
- assertNull(handler.openConnection(null));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "openConnection",
- args = {URL.class, Proxy.class}
- )
- public void test_openConnectionLjava_net_URLLjava_net_Proxy() {
- try {
- handler.openConnection(null, null);
- fail("UnsupportedOperationException was not thrown.");
- } catch(UnsupportedOperationException uoe) {
- //expected
- } catch (IOException e) {
- fail("IOException was thrown.");
- }
- }
-
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Completed testing of this method requres set up " +
- "URLStreamHandlerFactory that can be done at most once.",
- method = "parseURL",
- args = {URL.class, String.class, int.class, int.class}
- )
- public void test_parseURLLjava_net_URLLjava_lang_StringII()
- throws MalformedURLException {
- String str = "http://test.org/foo?a=123&b=%D5D6D7&c=++&d=";
- URL url = new URL("http://test.org");
-
- try {
- handler.parseURL(url, str, 0, str.length());
- fail("SecurityException should be thrown.");
- } catch(SecurityException se) {
- //SecurityException is expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sameFile",
- args = {URL.class, URL.class}
- )
- public void test_sameFile() throws MalformedURLException {
- URL url1 = new URL("http://test:pwd@localhost:80/foo/foo1.c");
- URL url2 = new URL("http://test:pwd@127.0.01:80/foo/foo1.c");
- URL url3 = new URL("http://test:pwd@127.0.01:80/foo/foo2.c");
- URL url4 = new URL("ftp://test:pwd@127.0.01:21/foo/foo2.c");
- URL url5 = new URL("ftp://test:pwd@127.0.01:21/foo/foo1/foo2.c");
- URL url6 = new URL("http://test/foo/foo1.c");
-
- assertTrue("Test case 1", handler.sameFile(url1, url2));
- assertFalse("Test case 2", handler.sameFile(url3, url2));
- assertFalse("Test case 3", handler.sameFile(url3, url4));
- assertFalse("Test case 4", handler.sameFile(url4, url5));
- assertFalse("Test case 5", handler.sameFile(url1, url6));
- }
-
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Completed testing of this method requres set up " +
- "URLStreamHandlerFactory that can be done at most once.",
- method = "setURL",
- args = {java.net.URL.class, java.lang.String.class,
- java.lang.String.class, int.class, java.lang.String.class,
- java.lang.String.class}
- )
- public void test_setURL1() throws MalformedURLException {
- URL url = new URL("http://test.org");
-
- try {
- handler.setURL(url, "http", "localhost", 80, "foo.c", "ref");
- fail("SecurityException should be thrown.");
- } catch(SecurityException se) {
- //SecurityException is expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Completed testing of this method requres set up " +
- "URLStreamHandlerFactory that can be done at most once.",
- method = "setURL",
- args = {java.net.URL.class, java.lang.String.class,
- java.lang.String.class, int.class, java.lang.String.class,
- java.lang.String.class, java.lang.String.class,
- java.lang.String.class, java.lang.String.class}
- )
- public void test_setURL2() throws MalformedURLException {
- URL url = new URL("http://test.org");
-
- try {
- handler.setURL(url, "http", "localhost", 80, "authority",
- "user", "foo.c", "query", "ref");
- fail("SecurityException should be thrown.");
- } catch(SecurityException se) {
- //SecurityException is expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toExternalForm",
- args = {URL.class}
- )
- public void test_toExternalForm() throws MalformedURLException {
- URL [] urls = { new URL("ftp://test_url/test?a=b&c=%D0+%D1"),
- new URL("http://test_url/test?a=b&c=%D0+%D1"),
- new URL("http://test:pwd@localhost:80/foo/foo1.c")};
-
- for(URL url:urls) {
- assertEquals("Test case for " + url.toString(),
- url.toString(), handler.toExternalForm(url));
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URLStreamHandler",
- args = {}
- )
- public void test_Constructor() {
- MockURLStreamHandler msh = new MockURLStreamHandler();
- assertEquals(-1, msh.getDefaultPort());
- }
-
- public void setUp() {
- handler = new MockURLStreamHandler();
- }
-
- class MockURLStreamHandler extends URLStreamHandler {
-
- @Override
- protected URLConnection openConnection(URL arg0) throws IOException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public boolean equals(URL u1, URL u2) {
- return super.equals(u1, u2);
- }
-
- public int getDefaultPort() {
- return super.getDefaultPort();
- }
-
- public InetAddress getHostAddress(URL u) {
- return super.getHostAddress(u);
- }
-
- public int hashCode(URL u) {
- return super.hashCode(u);
- }
-
- public boolean hostsEqual(URL u1, URL u2) {
- return super.hostsEqual(u1, u2);
- }
-
- public URLConnection openConnection(URL u, Proxy p) throws IOException {
- return super.openConnection(u, p);
- }
-
- public void parseURL(URL u, String spec, int start, int limit) {
- super.parseURL(u, spec, start, limit);
- }
-
- public boolean sameFile(URL u1, URL u2) {
- return super.sameFile(u1, u2);
- }
-
- public void setURL(URL u,
- String protocol,
- String host,
- int port,
- String file,
- String ref) {
- super.setURL(u, protocol, host, port, file, ref);
- }
-
- public void setURL(URL u,
- String protocol,
- String host,
- int port,
- String authority,
- String userInfo,
- String path,
- String query,
- String ref) {
- super.setURL(u, protocol, host, port, authority,
- userInfo, path, query, ref);
- }
-
- public String toExternalForm(URL u) {
- return super.toExternalForm(u);
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/UnknownHostExceptionTest.java b/luni/src/test/java/tests/api/java/net/UnknownHostExceptionTest.java
deleted file mode 100644
index 1849865..0000000
--- a/luni/src/test/java/tests/api/java/net/UnknownHostExceptionTest.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(java.net.UnknownHostException.class)
-public class UnknownHostExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.UnknownHostException#UnknownHostException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnknownHostException",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.net.UnknownHostException()
- try {
- try {
- java.net.InetAddress.getByName("a.b.c.x.y.z.com");
- } catch (java.net.UnknownHostException e) {
- return;
- }
- fail("Failed to generate Exception");
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.net.UnknownHostException#UnknownHostException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnknownHostException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.net.UnknownHostException(java.lang.String)
- try {
- try {
- java.net.InetAddress.getByName("a.b.c.x.y.z.com");
- } catch (java.net.UnknownHostException e) {
- return;
- }
- fail("Failed to generate Exception");
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/UnknownServiceExceptionTest.java b/luni/src/test/java/tests/api/java/net/UnknownServiceExceptionTest.java
deleted file mode 100644
index 9fc287c..0000000
--- a/luni/src/test/java/tests/api/java/net/UnknownServiceExceptionTest.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * 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 tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.URL;
-import java.net.UnknownServiceException;
-
-@TestTargetClass(UnknownServiceException.class)
-public class UnknownServiceExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.UnknownServiceException#UnknownServiceException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnknownServiceException",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.net.UnknownServiceException()
- try {
- new URL("file://moo.txt").openConnection().getOutputStream();
- } catch (UnknownServiceException e) {
- // correct
- return;
- } catch (Exception e) {
- fail("Wrong exception during test : " + e.getMessage());
- }
- fail("Exception not thrown");
- }
-
- /**
- * @tests java.net.UnknownServiceException#UnknownServiceException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnknownServiceException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.net.UnknownServiceException(java.lang.String)
- try {
- if (true)
- throw new UnknownServiceException("HelloWorld");
- } catch (UnknownServiceException e) {
- assertTrue("Wrong exception message: " + e.toString(), e
- .getMessage().equals("HelloWorld"));
- return;
- }
- fail("Constructor failed");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/AbstractListTest.java b/luni/src/test/java/tests/api/java/util/AbstractListTest.java
deleted file mode 100644
index a2002b2..0000000
--- a/luni/src/test/java/tests/api/java/util/AbstractListTest.java
+++ /dev/null
@@ -1,353 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.AbstractList;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.RandomAccess;
-
-@TestTargetClass(AbstractList.class)
-public class AbstractListTest extends junit.framework.TestCase {
-
- static class SimpleList extends AbstractList {
- ArrayList arrayList;
-
- SimpleList() {
- this.arrayList = new ArrayList();
- }
-
- public Object get(int index) {
- return this.arrayList.get(index);
- }
-
- public void add(int i, Object o) {
- this.arrayList.add(i, o);
- }
-
- public Object remove(int i) {
- return this.arrayList.remove(i);
- }
-
- public int size() {
- return this.arrayList.size();
- }
- }
-
- /**
- * @tests java.util.AbstractList#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
-
- List list = new ArrayList();
- list.add(new Integer(3));
- list.add(new Integer(15));
- list.add(new Integer(5));
- list.add(new Integer(1));
- list.add(new Integer(7));
- int hashCode = 1;
- Iterator i = list.iterator();
- while (i.hasNext()) {
- Object obj = i.next();
- hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode());
- }
- assertTrue("Incorrect hashCode returned. Wanted: " + hashCode
- + " got: " + list.hashCode(), hashCode == list.hashCode());
- }
-
- /**
- * @tests java.util.AbstractList#iterator()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "iterator",
- args = {}
- )
- public void test_iterator() {
- SimpleList list = new SimpleList();
- list.add(new Object());
- list.add(new Object());
- Iterator it = list.iterator();
- it.next();
- it.remove();
- it.next();
- }
-
- /**
- * @tests java.util.AbstractList#listIterator()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "listIterator",
- args = {}
- )
- public void test_listIterator() {
- Integer tempValue;
- List list = new ArrayList();
- list.add(new Integer(3));
- list.add(new Integer(15));
- list.add(new Integer(5));
- list.add(new Integer(1));
- list.add(new Integer(7));
- ListIterator lit = list.listIterator();
- assertTrue("Should not have previous", !lit.hasPrevious());
- assertTrue("Should have next", lit.hasNext());
- tempValue = (Integer) lit.next();
- assertTrue("next returned wrong value. Wanted 3, got: " + tempValue,
- tempValue.intValue() == 3);
- tempValue = (Integer) lit.previous();
-
- SimpleList list2 = new SimpleList();
- list2.add(new Object());
- ListIterator lit2 = list2.listIterator();
- lit2.add(new Object());
- lit2.next();
- }
-
- /**
- * @tests java.util.AbstractList#subList(int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies each of the SubList operations to ensure a ConcurrentModificationException does not occur on an AbstractList which does not update modCount.",
- method = "subList",
- args = {int.class, int.class}
- )
- public void test_subListII() {
- // Test each of the SubList operations to ensure a
- // ConcurrentModificationException does not occur on an AbstractList
- // which does not update modCount
- SimpleList mList = new SimpleList();
- mList.add(new Object());
- mList.add(new Object());
- List sList = mList.subList(0, 2);
- sList.add(new Object()); // calls add(int, Object)
- sList.get(0);
-
- sList.add(0, new Object());
- sList.get(0);
-
- sList.addAll(Arrays.asList(new String[] { "1", "2" }));
- sList.get(0);
-
- sList.addAll(0, Arrays.asList(new String[] { "3", "4" }));
- sList.get(0);
-
- sList.remove(0);
- sList.get(0);
-
- ListIterator lit = sList.listIterator();
- lit.add(new Object());
- lit.next();
- lit.remove();
- lit.next();
-
- sList.clear(); // calls removeRange()
- sList.add(new Object());
-
- // test the type of sublist that is returned
- List al = new ArrayList();
- for (int i = 0; i < 10; i++) {
- al.add(new Integer(i));
- }
- assertTrue(
- "Sublist returned should have implemented Random Access interface",
- al.subList(3, 7) instanceof RandomAccess);
-
- List ll = new LinkedList();
- for (int i = 0; i < 10; i++) {
- ll.add(new Integer(i));
- }
- assertTrue(
- "Sublist returned should not have implemented Random Access interface",
- !(ll.subList(3, 7) instanceof RandomAccess));
-
- }
-
- /**
- * @tests java.util.AbstractList#subList(int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IndexOutOfBoundsException.",
- method = "subList",
- args = {int.class, int.class}
- )
- public void test_subList_empty() {
- // Regression for HARMONY-389
- List al = new ArrayList();
- al.add("one");
- List emptySubList = al.subList(0, 0);
-
- try {
- emptySubList.get(0);
- fail("emptySubList.get(0) should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- emptySubList.set(0, "one");
- fail("emptySubList.set(0,Object) should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- emptySubList.remove(0);
- fail("emptySubList.remove(0) should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.AbstractList#subList(int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify IndexOutOfBoundsException, IllegalArgumentException.",
- method = "subList",
- args = {int.class, int.class}
- )
- public void test_subList_addAll() {
- // Regression for HARMONY-390
- List mainList = new ArrayList();
- Object[] mainObjects = { "a", "b", "c" };
- mainList.addAll(Arrays.asList(mainObjects));
- List subList = mainList.subList(1, 2);
- assertFalse("subList should not contain \"a\"", subList.contains("a"));
- assertFalse("subList should not contain \"c\"", subList.contains("c"));
- assertTrue("subList should contain \"b\"", subList.contains("b"));
-
- Object[] subObjects = { "one", "two", "three" };
- subList.addAll(Arrays.asList(subObjects));
- assertFalse("subList should not contain \"a\"", subList.contains("a"));
- assertFalse("subList should not contain \"c\"", subList.contains("c"));
-
- Object[] expected = { "b", "one", "two", "three" };
- ListIterator iter = subList.listIterator();
- for (int i = 0; i < expected.length; i++) {
- assertTrue("subList should contain " + expected[i], subList
- .contains(expected[i]));
- assertTrue("should be more elements", iter.hasNext());
- assertEquals("element in incorrect position", expected[i], iter
- .next());
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "indexOf",
- args = {java.lang.Object.class}
- )
- public void test_indexOfLjava_lang_Object() {
- AbstractList al = new ArrayList();
- al.add(0);
- al.add(1);
- al.add(2);
- al.add(3);
- al.add(4);
-
- assertEquals(-1, al.indexOf(5));
- assertEquals(2, al.indexOf(2));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lastIndexOf",
- args = {java.lang.Object.class}
- )
- public void test_lastIndexOfLjava_lang_Object() {
- AbstractList al = new ArrayList();
- al.add(0);
- al.add(1);
- al.add(2);
- al.add(2);
- al.add(2);
- al.add(2);
- al.add(2);
- al.add(3);
- al.add(4);
-
- assertEquals(-1, al.lastIndexOf(5));
- assertEquals(6, al.lastIndexOf(2));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "listIterator",
- args = {int.class}
- )
- public void test_listIteratorI() {
- AbstractList al1 = new ArrayList();
- AbstractList al2 = new ArrayList();
- al1.add(0);
- al1.add(1);
- al1.add(2);
- al1.add(3);
- al1.add(4);
- al2.add(2);
- al2.add(3);
- al2.add(4);
-
- Iterator li1 = al1.listIterator(2);
- Iterator li2 = al2.listIterator();
-
- while(li1.hasNext()&&li2.hasNext()) {
- assertEquals(li1.next(), li2.next());
- }
- assertSame(li1.hasNext(),li2.hasNext());
-
- try {
- al1.listIterator(-1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
-
- try {
- al1.listIterator(al1.size() + 1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
- }
-
- protected void doneSuite() {}
-}
diff --git a/luni/src/test/java/tests/api/java/util/AbstractMapTest.java b/luni/src/test/java/tests/api/java/util/AbstractMapTest.java
deleted file mode 100644
index c6a612c..0000000
--- a/luni/src/test/java/tests/api/java/util/AbstractMapTest.java
+++ /dev/null
@@ -1,310 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.AbstractMap;
-import java.util.AbstractSet;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.IdentityHashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-import java.util.Vector;
-import java.util.WeakHashMap;
-
-@TestTargetClass(AbstractMap.class)
-public class AbstractMapTest extends junit.framework.TestCase {
-
- static final String specialKey = "specialKey".intern();
-
- static final String specialValue = "specialValue".intern();
-
- // The impl of MyMap is not realistic, but serves to create a type
- // that uses the default remove behavior.
- class MyMap extends AbstractMap {
- final Set mySet = new HashSet(1);
-
- MyMap() {
- mySet.add(new Map.Entry() {
- public Object getKey() {
- return specialKey;
- }
-
- public Object getValue() {
- return specialValue;
- }
-
- public Object setValue(Object object) {
- return null;
- }
- });
- }
-
- public Object put(Object key, Object value) {
- return null;
- }
-
- public Set entrySet() {
- return mySet;
- }
- }
-
- /**
- * @tests java.util.AbstractMap#keySet()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify returned set of keys.",
- method = "keySet",
- args = {}
- )
- public void test_keySet() {
- AbstractMap map1 = new HashMap(0);
- assertSame("HashMap(0)", map1.keySet(), map1.keySet());
-
- AbstractMap map2 = new HashMap(10);
- assertSame("HashMap(10)", map2.keySet(), map2.keySet());
-
- Map map3 = Collections.EMPTY_MAP;
- assertSame("EMPTY_MAP", map3.keySet(), map3.keySet());
-
- AbstractMap map4 = new IdentityHashMap(1);
- assertSame("IdentityHashMap", map4.keySet(), map4.keySet());
-
- AbstractMap map5 = new LinkedHashMap(122);
- assertSame("LinkedHashMap", map5.keySet(), map5.keySet());
-
- AbstractMap map6 = new TreeMap();
- assertSame("TreeMap", map6.keySet(), map6.keySet());
-
- AbstractMap map7 = new WeakHashMap();
- assertSame("WeakHashMap", map7.keySet(), map7.keySet());
- }
-
- /**
- * @tests java.util.AbstractMap#remove(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify UnsupportedOperationException.",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_removeLjava_lang_Object() {
- Object key = new Object();
- Object value = new Object();
-
- AbstractMap map1 = new HashMap(0);
- map1.put("key", value);
- assertSame("HashMap(0)", map1.remove("key"), value);
-
- AbstractMap map4 = new IdentityHashMap(1);
- map4.put(key, value);
- assertSame("IdentityHashMap", map4.remove(key), value);
-
- AbstractMap map5 = new LinkedHashMap(122);
- map5.put(key, value);
- assertSame("LinkedHashMap", map5.remove(key), value);
-
- AbstractMap map6 = new TreeMap(new Comparator() {
- // Bogus comparator
- public int compare(Object object1, Object object2) {
- return 0;
- }
- });
- map6.put(key, value);
- assertSame("TreeMap", map6.remove(key), value);
-
- AbstractMap map7 = new WeakHashMap();
- map7.put(key, value);
- assertSame("WeakHashMap", map7.remove(key), value);
-
- AbstractMap aSpecialMap = new MyMap();
- aSpecialMap.put(specialKey, specialValue);
- Object valueOut = aSpecialMap.remove(specialKey);
- assertSame("MyMap", valueOut, specialValue);
- }
-
- /**
- * @tests java.util.AbstractMap#values()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify returned Collection.",
- method = "values",
- args = {}
- )
- public void test_values() {
- AbstractMap map1 = new HashMap(0);
- assertSame("HashMap(0)", map1.values(), map1.values());
-
- AbstractMap map2 = new HashMap(10);
- assertSame("HashMap(10)", map2.values(), map2.values());
-
- Map map3 = Collections.EMPTY_MAP;
- assertSame("EMPTY_MAP", map3.values(), map3.values());
-
- AbstractMap map4 = new IdentityHashMap(1);
- assertSame("IdentityHashMap", map4.values(), map4.values());
-
- AbstractMap map5 = new LinkedHashMap(122);
- assertSame("IdentityHashMap", map5.values(), map5.values());
-
- AbstractMap map6 = new TreeMap();
- assertSame("TreeMap", map6.values(), map6.values());
-
- AbstractMap map7 = new WeakHashMap();
- assertSame("WeakHashMap", map7.values(), map7.values());
- }
-
- /**
- * @tests java.util.AbstractMap#clone()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify CloneNotSupportedException.",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- class MyMap extends AbstractMap implements Cloneable {
- private Map map = new HashMap();
-
- public Set entrySet() {
- return map.entrySet();
- }
-
- public Object put(Object key, Object value) {
- return map.put(key, value);
- }
-
- public Map getMap() {
- return map;
- }
-
- public Object clone() {
- try {
- return super.clone();
- } catch (CloneNotSupportedException e) {
- return null;
- }
- }
- }
- ;
- MyMap map = new MyMap();
- map.put("one", "1");
- Map.Entry entry = (Map.Entry) map.entrySet().iterator().next();
- assertTrue("entry not added", entry.getKey() == "one"
- && entry.getValue() == "1");
- MyMap mapClone = (MyMap) map.clone();
- assertTrue("clone not shallow", map.getMap() == mapClone.getMap());
- }
-
- public class AMT extends AbstractMap {
-
- // Very crude AbstractMap implementation
- Vector values = new Vector();
- Vector keys = new Vector();
-
- public Set entrySet() {
- return new AbstractSet() {
- public Iterator iterator() {
- return new Iterator() {
- int index = 0;
-
- public boolean hasNext() {
- return index < values.size();
- }
-
- public Object next() {
- if (index < values.size()) {
- Map.Entry me = new Map.Entry() {
- Object v = values.elementAt(index);
-
- Object k = keys.elementAt(index);
-
- public Object getKey() {
- return k;
- }
-
- public Object getValue() {
- return v;
- }
-
- public Object setValue(Object value) {
- return null;
- }
- };
- index++;
- return me;
- }
- return null;
- }
-
- public void remove() {
- }
- };
- }
-
- public int size() {
- return values.size();
- }
- };
- }
-
- public Object put(Object k, Object v) {
- keys.add(k);
- values.add(v);
- return v;
- }
- }
-
- /**
- * @tests {@link java.util.AbstractMap#putAll(Map)}
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify exceptions.",
- method = "putAll",
- args = {java.util.Map.class}
- )
- public void test_putAllLMap() {
- Hashtable ht = new Hashtable();
- AMT amt = new AMT();
- ht.put("this", "that");
- amt.putAll(ht);
-
- assertEquals("Should be equal", amt, ht);
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/AbstractQueueTest.java b/luni/src/test/java/tests/api/java/util/AbstractQueueTest.java
deleted file mode 100644
index c69ca42..0000000
--- a/luni/src/test/java/tests/api/java/util/AbstractQueueTest.java
+++ /dev/null
@@ -1,425 +0,0 @@
-/* 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.AbstractQueue;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.NoSuchElementException;
-import java.util.Vector;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(AbstractQueue.class)
-public class AbstractQueueTest extends TestCase {
-
- private MockAbstractQueue<Object> queue;
-
- private class MockAbstractQueue<E> extends AbstractQueue<E> {
-
- static final int CAPACITY = 10;
-
- private int size = 0;
-
- private Object[] elements = new Object[CAPACITY];
-
- public Iterator<E> iterator() {
- return new Iterator<E>() {
-
- private int currentIndex = -1;
-
- public boolean hasNext() {
- return size > 0 && currentIndex < size;
- }
-
- public E next() {
- if (!hasNext()) {
- throw new NoSuchElementException();
- }
- currentIndex++;
- return (E) elements[currentIndex];
- }
-
- public void remove() {
- if (-1 == currentIndex) {
- throw new IllegalStateException();
- }
- for (int i = currentIndex; i < size - 1; i++) {
- elements[i] = elements[i + 1];
- }
- size--;
- }
- };
- }
-
- public int size() {
- return size;
- }
-
- public boolean offer(E o) {
- if (null == o) {
- throw new NullPointerException();
- }
-
- if (size >= CAPACITY) {
- return false;
- }
-
- elements[size++] = o;
- return true;
- }
-
- public E poll() {
- if (isEmpty()) {
- return null;
- }
- E e = (E) elements[0];
- for (int i = 0; i < size - 1; i++) {
- elements[i] = elements[i + 1];
- }
- size--;
- return e;
- }
-
- public E peek() {
- if (isEmpty()) {
- return null;
- }
- return (E) elements[0];
- }
-
- }
-
- /**
- * @tests java.util.AbstractQueue.add(E)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "add",
- args = {java.lang.Object.class}
- )
- public void test_addLE_null() {
- try {
- queue.add(null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.AbstractQueue.add(E)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalStateException.",
- method = "add",
- args = {java.lang.Object.class}
- )
- public void test_addLE_Full() {
- Object o = new Object();
-
- for(int i = 0; i < MockAbstractQueue.CAPACITY; i++ ) {
- queue.add(o);
- }
-
- try {
- queue.add(o);
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.AbstractQueue#add(E)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify NullPointerException, IllegalStateException.",
- method = "add",
- args = {java.lang.Object.class}
- )
- public void test_addLE() {
- Object o = new Object();
- final int LAST_INDEX = 4;
- for (int i = 0; i < LAST_INDEX; i++) {
- queue.add(o);
- }
- Integer I = new Integer(123456);
- queue.add(I);
- assertTrue(queue.contains(I));
- Iterator iter = queue.iterator();
- for (int i = 0; i < LAST_INDEX; i++) {
- iter.next();
- }
- assertTrue(I == iter.next());
- }
-
- /**
- * @tests java.util.AbstractQueue#addAll(E)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "addAll",
- args = {java.util.Collection.class}
- )
- public void test_addAllLE_null() {
- try {
- queue.addAll(null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.AbstractQueue#addAll(E)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "addAll",
- args = {java.util.Collection.class}
- )
- public void test_addAllLE_with_null() {
- List list = Arrays.asList("MYTESTSTRING", null, new Float(123.456));
- try {
- queue.addAll(list);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.AbstractQueue#addAll(E)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalStateException.",
- method = "addAll",
- args = {java.util.Collection.class}
- )
- public void test_addAllLE_full() {
- List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
- try {
- queue.addAll(list);
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.AbstractQueue#addAll(E)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test. Doesn't verify returned true value.",
- method = "addAll",
- args = {java.util.Collection.class}
- )
- public void test_addAllLE_empty() {
- // Regression test for HARMONY-1178
- List list = new ArrayList<Object>(0);
- assertFalse("Non modification to queue should return false", queue.addAll(list));
- }
-
- /**
- * @tests java.util.AbstractQueue#addAll(E)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalArgumentException.",
- method = "addAll",
- args = {java.util.Collection.class}
- )
- public void test_addAllLE_this() {
- try {
- queue.addAll(queue);
- fail("should throw IllegalArgumentException ");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks functionality",
- method = "addAll",
- args = {java.util.Collection.class}
- )
- public void test_addAllLjava_lang_Object() {
- Collection c = new Vector();
-
- c.add(0);
- c.add(1);
- c.add(2);
- c.add(3);
- c.add(4);
- c.add(5);
-
- assertTrue(queue.addAll(c));
- assertEquals(6, queue.size());
- }
-
- /**
- * @tests java.util.AbstractQueue#clear()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies clear method for empty queue.",
- method = "clear",
- args = {}
- )
- public void test_clear_empty() {
- queue.clear();
- assertTrue(queue.isEmpty());
- assertNull(queue.peek());
- }
-
- /**
- * @tests java.util.AbstractQueue#clear()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- List list = Arrays.asList(123.456, "MYTESTSTRING", new Object(), 'c');
- queue.addAll(list);
- queue.clear();
- assertTrue(queue.isEmpty());
- assertNull(queue.peek());
- }
-
- /**
- * @tests java.util.AbstractQueue#AbstractQueue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AbstractQueue",
- args = {}
- )
- public void test_Constructor() {
- MockAbstractQueue queue = new MockAbstractQueue();
- assertNotNull(queue);
- }
-
- /**
- * @tests java.util.AbstractQueue#remove()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NoSuchElementException.",
- method = "remove",
- args = {}
- )
- public void test_remove_null() {
- try {
- queue.remove();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // expected
- }
-
- }
-
- /**
- * @tests java.util.AbstractQueue#remove()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies positive functionality, NoSuchElementException.",
- method = "remove",
- args = {}
- )
- public void test_remove() {
- char c = 'a';
- queue.add(c);
- c = 'b';
- queue.add(c);
- assertEquals('a', queue.remove());
- assertEquals('b', queue.remove());
- try {
- queue.remove();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.AbstractQueue#element()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NoSuchElementException.",
- method = "element",
- args = {}
- )
- public void test_element_empty() {
- try {
- queue.element();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.AbstractQueue#element()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify NoSuchElementException.",
- method = "element",
- args = {}
- )
- public void test_element() {
- String s = "MYTESTSTRING_ONE";
- queue.add(s);
- s = "MYTESTSTRING_TWO";
- queue.add(s);
- assertEquals("MYTESTSTRING_ONE", queue.element());
- // still the first element
- assertEquals("MYTESTSTRING_ONE", queue.element());
- }
-
- protected void setUp() throws Exception {
- super.setUp();
- queue = new MockAbstractQueue<Object>();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- queue = null;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/AbstractSequentialListTest.java b/luni/src/test/java/tests/api/java/util/AbstractSequentialListTest.java
deleted file mode 100644
index 169afe3..0000000
--- a/luni/src/test/java/tests/api/java/util/AbstractSequentialListTest.java
+++ /dev/null
@@ -1,659 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.AbstractSequentialList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.ListIterator;
-import java.util.Vector;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(AbstractSequentialList.class)
-public class AbstractSequentialListTest extends TestCase {
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- class ASLT<E> extends AbstractSequentialList<E> {
-
- LinkedList<E> l = new LinkedList<E>();
-
- @Override
- public ListIterator<E> listIterator(int index) {
- return l.listIterator(index);
- }
-
- @Override
- public int size() {
- return l.size();
- }
- }
-
- /**
- * @tests {@link java.util.AbstractSequentialList#addAll(int, java.util.Collection)}
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify all exceptions according to the specification.",
- method = "addAll",
- args = {int.class, java.util.Collection.class}
- )
- public void test_addAll_ILCollection() {
- AbstractSequentialList<String> al = new ASLT<String>();
- String[] someList = { "Aardvark" , //$NON-NLS-1$
- "Bear" , //$NON-NLS-1$
- "Chimpanzee", //$NON-NLS-1$
- "Duck" }; //$NON-NLS-1$
- Collection<String> c = Arrays.asList(someList);
- al.addAll(c);
- assertTrue("Should return true", al.addAll(2, c)); //$NON-NLS-1$
- }
-
- class Mock_unsupportedListIterator implements ListIterator {
- public void add(Object o) {
- throw new UnsupportedOperationException();
- }
-
- public boolean hasNext() {
- return false;
- }
-
- public boolean hasPrevious() {
- return false;
- }
-
- public Object next() {
- return null;
- }
-
- public int nextIndex() {
- return 0;
- }
-
- public Object previous() {
- return null;
- }
-
- public int previousIndex() {
- return 0;
- }
-
- public void remove() {
- }
-
- public void set(Object o) {
- throw new UnsupportedOperationException();
- }
- }
-
- class Mock_ListIterator<E> implements ListIterator<E> {
- final String wrongElement = "String";
- public void add(E o) {
- if (o.equals(wrongElement)) throw new IllegalArgumentException();
- if (o == null) throw new NullPointerException();
- }
-
- public boolean hasNext() {
- return false;
- }
-
- public boolean hasPrevious() {
- return false;
- }
-
- public E next() {
- return null;
- }
-
- public int nextIndex() {
- return 0;
- }
-
- public E previous() {
- return null;
- }
-
- public int previousIndex() {
- return 0;
- }
-
- public void remove() {
- }
-
- public void set(E o) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addAll",
- args = {int.class, java.util.Collection.class}
- )
- public void test_addAllILjava_util_Collection() {
- AbstractSequentialList asl = new AbstractSequentialList() {
-
- @Override
- public int size() {
- return 0;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- return new Mock_unsupportedListIterator();
- }
- };
- Collection strV = new Vector<String>();
-
- strV.add("String");
- strV.add("1");
- strV.add("3.14");
-
- try {
- asl.addAll(0, strV);
- fail("UnsupportedOperationException expected.");
- } catch (UnsupportedOperationException ee) {
- //expected
- }
- try {
- asl.addAll(0, null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- //ClassCastException can not be checked for this method.
-
- asl = new AbstractSequentialList() {
-
- @Override
- public int size() {
- return 0;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- return new Mock_ListIterator();
- }
- };
-
- try {
- asl.addAll(0, strV);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- strV.remove("String");
- strV.add(null);
-
- try {
- asl.addAll(0, strV);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- strV.remove(null);
- asl.addAll(0, strV);
-
- asl = new LinkedList();
-
- try {
- asl.addAll(-10, strV);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- asl.addAll(1, strV);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "add",
- args = {int.class, java.lang.Object.class}
- )
- public void test_addILjava_lang_Object() {
- AbstractSequentialList asl = new AbstractSequentialList() {
-
- @Override
- public int size() {
- return 0;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- return new Mock_unsupportedListIterator();
- }
- };
-
- try {
- asl.add(0, 1);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
-
- asl = new AbstractSequentialList() {
-
- @Override
- public int size() {
- return 0;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- return new Mock_ListIterator();
- }
- };
-
- try {
- asl.add(0, "String");
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ee) {
- //expected
- }
-
- try {
- asl.add(0, null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- //ClassCastException can not be checked for this method.
-
- asl.add(0, 1);
-
- asl = new LinkedList();
-
- try {
- asl.add(-1, 1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
-
- asl.add(0, 1);
-
- try {
- asl.add(2, 1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {int.class}
- )
- public void test_getI() {
- final String buff[] = {"0", "1", "2", "3", "4", "5"};
- AbstractSequentialList asl = new AbstractSequentialList() {
- int currPos = 0;
-
- @Override
- public int size() {
- return buff.length;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- currPos = index;
- return new ListIterator() {
- public void add(Object o) {
- }
-
- public boolean hasNext() {
- return true;
- }
-
- public boolean hasPrevious() {
- return false;
- }
-
- public Object next() {
- return buff[currPos];
- }
-
- public int nextIndex() {
- return 0;
- }
-
- public Object previous() {
- return null;
- }
-
- public int previousIndex() {
- return 0;
- }
-
- public void remove() {
- }
-
- public void set(Object o) {
- }
- };
- }
- };
-
- for (int i = 0; i < buff.length; i++) {
- assertEquals(buff[i], asl.get(i));
- }
-
- try {
- asl.get(asl.size() + 1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- asl.get(-1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "iterator",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AbstractSequentialList",
- args = {}
- )
- })
- public void test_iterrator() {
- AbstractSequentialList asl = new AbstractSequentialList() {
-
- @Override
- public int size() {
- return 0;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- return new Mock_unsupportedListIterator();
- }
- };
-
- assertTrue(asl.iterator().getClass().toString().contains("Mock_unsupportedListIterator"));
-
- asl = new AbstractSequentialList() {
-
- @Override
- public int size() {
- return 0;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- return new Mock_ListIterator();
- }
- };
-
- assertTrue(asl.iterator().getClass().toString().contains("Mock_ListIterator"));
-
- asl = new AbstractSequentialList() {
-
- @Override
- public int size() {
- return 0;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- return null;
- }
- };
- assertNull(asl.iterator());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {int.class}
- )
- public void test_removeI() {
- AbstractSequentialList asl = new AbstractSequentialList() {
- String buff[] = {"0", "1", "2", "3", "4", "5"};
- int currPos = 0;
-
- @Override
- public int size() {
- return buff.length;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- currPos = index;
- return new ListIterator() {
- public void add(Object o) {
- }
-
- public boolean hasNext() {
- return true;
- }
-
- public boolean hasPrevious() {
- return false;
- }
-
- public Object next() {
- return buff[currPos];
- }
-
- public int nextIndex() {
- return 0;
- }
-
- public Object previous() {
- return null;
- }
-
- public int previousIndex() {
- return 0;
- }
-
- public void remove() {
- buff[currPos] = "removed element";
- }
-
- public void set(Object o) {
- }
- };
- }
- };
-
- try {
- asl.remove(asl.size() + 1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- asl.remove(-1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- for(int i = 0; i < asl.size(); i++) {
- assertFalse(asl.get(i).toString().contains("removed element"));
- asl.remove(i);
- assertTrue(asl.get(i).toString().contains("removed element"));
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "set",
- args = {int.class, java.lang.Object.class}
- )
- public void test_setILjava_lang_Object() {
- AbstractSequentialList asl = new AbstractSequentialList() {
- String buff[] = {"0", "1", "2", "3", "4", "5"};
- final String illegalStr = "Illegal element";
- int currPos = 0;
-
- @Override
- public int size() {
- return buff.length;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- currPos = index;
- return new ListIterator() {
- public void add(Object o) {
- }
-
- public boolean hasNext() {
- return true;
- }
-
- public boolean hasPrevious() {
- return false;
- }
-
- public Object next() {
- return buff[currPos];
- }
-
- public int nextIndex() {
- return 0;
- }
-
- public Object previous() {
- return null;
- }
-
- public int previousIndex() {
- return 0;
- }
-
- public void remove() {
- buff[currPos] = "removed element";
- }
-
- public void set(Object o) {
- if (o == null) throw new NullPointerException();
- if (o.equals(illegalStr)) throw new IllegalArgumentException();
- buff[currPos] = (String) o;
- }
- };
- }
- };
-
- try {
- asl.set(asl.size() + 1, "new element");
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- asl.set(-1, "new element");
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- for(int i = 0; i < asl.size(); i++) {
- assertFalse(asl.get(i).toString().contains("new element"));
- asl.set(i, "new element");
- assertTrue(asl.get(i).toString().contains("new element"));
- }
-
- try {
- asl.set(1, new Double(1));
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //
- }
-
- try {
- asl.set(1, "Illegal element");
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ee) {
- //expected
- }
-
- try {
- asl.set(1, null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- asl = new AbstractSequentialList() {
-
- @Override
- public int size() {
- return 0;
- }
-
- @Override
- public ListIterator listIterator(int index) {
- return new Mock_unsupportedListIterator();
- }
- };
-
- try {
- asl.set(0, "New element");
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/AllTests.java b/luni/src/test/java/tests/api/java/util/AllTests.java
deleted file mode 100644
index c2651d9..0000000
--- a/luni/src/test/java/tests/api/java/util/AllTests.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-/**
- * TODO Type description
- */
-public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(AllTests.suite());
- }
-
- public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Test for java.util");
-
- // $JUnit-BEGIN$
- suite.addTestSuite(AbstractListTest.class);
- suite.addTestSuite(AbstractMapTest.class);
- suite.addTestSuite(AbstractQueueTest.class);
- suite.addTestSuite(AbstractSequentialListTest.class);
- suite.addTestSuite(ArrayListTest.class);
- suite.addTestSuite(ArraysTest.class);
- suite.addTestSuite(BitSetTest.class);
- suite.addTestSuite(CalendarTest.class);
- suite.addTestSuite(CollectionsTest.class);
- suite.addTestSuite(ConcurrentModificationExceptionTest.class);
- suite.addTestSuite(ConcurrentModTest.class);
- suite.addTestSuite(CurrencyTest.class);
- suite.addTestSuite(DateTest.class);
- suite.addTestSuite(EmptyStackExceptionTest.class);
- suite.addTestSuite(EnumMapTest.class);
- suite.addTestSuite(EnumSetTest.class);
- suite.addTestSuite(EventObjectTest.class);
- suite.addTestSuite(FormattableFlagsTest.class);
- suite.addTestSuite(FormatterTest.class);
- suite.addTestSuite(GregorianCalendarTest.class);
- suite.addTestSuite(HashMapTest.class);
- suite.addTestSuite(HashSetTest.class);
- suite.addTestSuite(HashtableTest.class);
- suite.addTestSuite(IdentityHashMapTest.class);
- suite.addTestSuite(InvalidPropertiesFormatExceptionTest.class);
- suite.addTestSuite(LinkedHashMapTest.class);
- suite.addTestSuite(LinkedHashSetTest.class);
- suite.addTestSuite(LinkedListTest.class);
- suite.addTestSuite(ListResourceBundleTest.class);
- suite.addTestSuite(LocaleTest.class);
- suite.addTestSuite(MissingResourceExceptionTest.class);
- suite.addTestSuite(NoSuchElementExceptionTest.class);
- suite.addTestSuite(ObservableTest.class);
- suite.addTestSuite(PriorityQueueTest.class);
- suite.addTestSuite(PropertiesTest.class);
- suite.addTestSuite(PropertyPermissionTest.class);
- suite.addTestSuite(PropertyResourceBundleTest.class);
- suite.addTestSuite(RandomTest.class);
- suite.addTestSuite(ResourceBundleTest.class);
- suite.addTestSuite(ScannerTest.class);
- suite.addTestSuite(SimpleTimeZoneTest.class);
- suite.addTestSuite(StackTest.class);
- suite.addTestSuite(StringTokenizerTest.class);
- suite.addTestSuite(TimerTaskTest.class);
- suite.addTestSuite(TimerTest.class);
- suite.addTestSuite(TimeZoneTest.class);
- suite.addTestSuite(TooManyListenersExceptionTest.class);
- suite.addTestSuite(TreeMapTest.class);
- suite.addTestSuite(TreeSetTest.class);
- suite.addTestSuite(VectorTest.class);
- suite.addTestSuite(WeakHashMapTest.class);
- // $JUnit-END$
-
- return suite;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/ArrayListTest.java b/luni/src/test/java/tests/api/java/util/ArrayListTest.java
deleted file mode 100644
index b9cfd58..0000000
--- a/luni/src/test/java/tests/api/java/util/ArrayListTest.java
+++ /dev/null
@@ -1,846 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.ConcurrentModificationException;
-import java.util.Vector;
-
-import tests.support.Support_ListTest;
-
-@TestTargetClass(ArrayList.class)
-public class ArrayListTest extends junit.framework.TestCase {
-
- List alist;
-
- static Object[] objArray;
- {
- objArray = new Object[100];
- for (int i = 0; i < objArray.length; i++)
- objArray[i] = new Integer(i);
- }
-
- /**
- * @tests java.util.ArrayList#ArrayList()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ArrayList",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.ArrayList()
- new Support_ListTest("", alist).runTest();
-
- ArrayList subList = new ArrayList();
- for (int i = -50; i < 150; i++)
- subList.add(new Integer(i));
- new Support_ListTest("", subList.subList(50, 150)).runTest();
- }
-
- /**
- * @tests java.util.ArrayList#ArrayList(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ArrayList",
- args = {int.class}
- )
- public void test_ConstructorI() {
- // Test for method java.util.ArrayList(int)
- ArrayList al = new ArrayList(5);
- assertEquals("Incorrect arrayList created", 0, al.size());
-
- try {
- new ArrayList(-10);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.ArrayList#ArrayList(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Doesn't verify NullPointerException.",
- method = "ArrayList",
- args = {java.util.Collection.class}
- )
- public void test_ConstructorLjava_util_Collection() {
- // Test for method java.util.ArrayList(java.util.Collection)
- ArrayList al = new ArrayList(Arrays.asList(objArray));
- assertTrue("arrayList created from collection has incorrect size", al
- .size() == objArray.length);
- for (int counter = 0; counter < objArray.length; counter++)
- assertTrue(
- "arrayList created from collection has incorrect elements",
- al.get(counter) == objArray[counter]);
- try {
- new ArrayList(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- }
-
- /**
- * @tests java.util.ArrayList#add(int, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "add",
- args = {int.class, java.lang.Object.class}
- )
- public void test_addILjava_lang_Object() {
- // Test for method void java.util.ArrayList.add(int, java.lang.Object)
- Object o;
- alist.add(50, o = new Object());
- assertTrue("Failed to add Object", alist.get(50) == o);
- assertTrue("Failed to fix up list after insert",
- alist.get(51) == objArray[50]
- && (alist.get(52) == objArray[51]));
- Object oldItem = alist.get(25);
- alist.add(25, null);
- assertNull("Should have returned null", alist.get(25));
- assertTrue("Should have returned the old item from slot 25", alist
- .get(26) == oldItem);
-
- try {
- alist.add(-1, null);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- alist.add(alist.size() + 1, null);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.ArrayList#add(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "add",
- args = {java.lang.Object.class}
- )
- public void test_addLjava_lang_Object() {
- // Test for method boolean java.util.ArrayList.add(java.lang.Object)
- Object o = new Object();
- alist.add(o);
- assertTrue("Failed to add Object", alist.get(alist.size() - 1) == o);
- alist.add(null);
- assertNull("Failed to add null", alist.get(alist.size() - 1));
- }
-
- /**
- * @tests java.util.ArrayList#addAll(int, java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addAll",
- args = {int.class, java.util.Collection.class}
- )
- public void test_addAllILjava_util_Collection() {
- // Test for method boolean java.util.ArrayList.addAll(int,
- // java.util.Collection)
- alist.addAll(50, alist);
- assertEquals("Returned incorrect size after adding to existing list",
- 200, alist.size());
- for (int i = 0; i < 50; i++)
- assertTrue("Manipulated elements < index",
- alist.get(i) == objArray[i]);
- for (int i = 0; i >= 50 && (i < 150); i++)
- assertTrue("Failed to ad elements properly",
- alist.get(i) == objArray[i - 50]);
- for (int i = 0; i >= 150 && (i < 200); i++)
- assertTrue("Failed to ad elements properly",
- alist.get(i) == objArray[i - 100]);
- ArrayList listWithNulls = new ArrayList();
- listWithNulls.add(null);
- listWithNulls.add(null);
- listWithNulls.add("yoink");
- listWithNulls.add("kazoo");
- listWithNulls.add(null);
- alist.addAll(100, listWithNulls);
- assertTrue("Incorrect size: " + alist.size(), alist.size() == 205);
- assertNull("Item at slot 100 should be null", alist.get(100));
- assertNull("Item at slot 101 should be null", alist.get(101));
- assertEquals("Item at slot 102 should be 'yoink'",
- "yoink", alist.get(102));
- assertEquals("Item at slot 103 should be 'kazoo'",
- "kazoo", alist.get(103));
- assertNull("Item at slot 104 should be null", alist.get(104));
- alist.addAll(205, listWithNulls);
- assertTrue("Incorrect size2: " + alist.size(), alist.size() == 210);
-
- try {
- alist.addAll(-1, listWithNulls);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- alist.addAll(alist.size() + 1, listWithNulls);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- alist.addAll(0, null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.ArrayList#addAll(int, java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IndexOutOfBoundsException.",
- method = "addAll",
- args = {int.class, java.util.Collection.class}
- )
- public void test_addAllILjava_util_Collection_2() {
- // Regression for HARMONY-467
- ArrayList obj = new ArrayList();
- try {
- obj.addAll((int) -1, (Collection) null);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * @tests java.util.ArrayList#addAll(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Doesn't verify NullPointerException.",
- method = "addAll",
- args = {java.util.Collection.class}
- )
- public void test_addAllLjava_util_Collection() {
- // Test for method boolean
- // java.util.ArrayList.addAll(java.util.Collection)
- List l = new ArrayList();
- l.addAll(alist);
- for (int i = 0; i < alist.size(); i++)
- assertTrue("Failed to add elements properly", l.get(i).equals(
- alist.get(i)));
- alist.addAll(alist);
- assertEquals("Returned incorrect size after adding to existing list",
- 200, alist.size());
- for (int i = 0; i < 100; i++) {
- assertTrue("Added to list in incorrect order", alist.get(i)
- .equals(l.get(i)));
- assertTrue("Failed to add to existing list", alist.get(i + 100)
- .equals(l.get(i)));
- }
- Set setWithNulls = new HashSet();
- setWithNulls.add(null);
- setWithNulls.add(null);
- setWithNulls.add("yoink");
- setWithNulls.add("kazoo");
- setWithNulls.add(null);
- alist.addAll(100, setWithNulls);
- Iterator i = setWithNulls.iterator();
- assertTrue("Item at slot 100 is wrong: " + alist.get(100), alist
- .get(100) == i.next());
- assertTrue("Item at slot 101 is wrong: " + alist.get(101), alist
- .get(101) == i.next());
- assertTrue("Item at slot 103 is wrong: " + alist.get(102), alist
- .get(102) == i.next());
-
-
- // Regression test for Harmony-3481
- ArrayList<Integer> originalList = new ArrayList<Integer>(12);
- for (int j = 0; j < 12; j++) {
- originalList.add(j);
- }
-
- originalList.remove(0);
- originalList.remove(0);
-
- ArrayList<Integer> additionalList = new ArrayList<Integer>(11);
- for (int j = 0; j < 11; j++) {
- additionalList.add(j);
- }
- assertTrue(originalList.addAll(additionalList));
- assertEquals(21, originalList.size());
-
- try {
- alist.addAll(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.ArrayList#clear()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- // Test for method void java.util.ArrayList.clear()
- alist.clear();
- assertEquals("List did not clear", 0, alist.size());
- alist.add(null);
- alist.add(null);
- alist.add(null);
- alist.add("bam");
- alist.clear();
- assertEquals("List with nulls did not clear", 0, alist.size());
- /*
- * for (int i = 0; i < alist.size(); i++) assertNull("Failed to clear
- * list", alist.get(i));
- */
-
- }
-
- /**
- * @tests java.util.ArrayList#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- // Test for method java.lang.Object java.util.ArrayList.clone()
- ArrayList x = (ArrayList) (((ArrayList) (alist)).clone());
- assertTrue("Cloned list was inequal to original", x.equals(alist));
- for (int i = 0; i < alist.size(); i++)
- assertTrue("Cloned list contains incorrect elements",
- alist.get(i) == x.get(i));
-
- alist.add(null);
- alist.add(25, null);
- x = (ArrayList) (((ArrayList) (alist)).clone());
- assertTrue("nulls test - Cloned list was inequal to original", x
- .equals(alist));
- for (int i = 0; i < alist.size(); i++)
- assertTrue("nulls test - Cloned list contains incorrect elements",
- alist.get(i) == x.get(i));
-
- }
-
- /**
- * @tests java.util.ArrayList#contains(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "contains",
- args = {java.lang.Object.class}
- )
- public void test_containsLjava_lang_Object() {
- // Test for method boolean
- // java.util.ArrayList.contains(java.lang.Object)
- assertTrue("Returned false for valid element", alist
- .contains(objArray[99]));
- assertTrue("Returned false for equal element", alist
- .contains(new Integer(8)));
- assertTrue("Returned true for invalid element", !alist
- .contains(new Object()));
- assertTrue("Returned true for null but should have returned false",
- !alist.contains(null));
- alist.add(null);
- assertTrue("Returned false for null but should have returned true",
- alist.contains(null));
- }
-
- /**
- * @tests java.util.ArrayList#ensureCapacity(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ensureCapacity",
- args = {int.class}
- )
- public void test_ensureCapacityI() {
- // Test for method void java.util.ArrayList.ensureCapacity(int)
- // TODO : There is no good way to test this as it only really impacts on
- // the private implementation.
-
- Object testObject = new Object();
- int capacity = 20;
- ArrayList al = new ArrayList(capacity);
- int i;
- for (i = 0; i < capacity / 2; i++) {
- al.add(i, new Object());
- }
- al.add(i, testObject);
- int location = al.indexOf(testObject);
- try {
- al.ensureCapacity(capacity);
- assertTrue("EnsureCapacity moved objects around in array1.",
- location == al.indexOf(testObject));
- al.remove(0);
- al.ensureCapacity(capacity);
- assertTrue("EnsureCapacity moved objects around in array2.",
- --location == al.indexOf(testObject));
- al.ensureCapacity(capacity + 2);
- assertTrue("EnsureCapacity did not change location.",
- location == al.indexOf(testObject));
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.util.ArrayList#get(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {int.class}
- )
- public void test_getI() {
- // Test for method java.lang.Object java.util.ArrayList.get(int)
- assertTrue("Returned incorrect element", alist.get(22) == objArray[22]);
- try {
- alist.get(8765);
- fail("Failed to throw expected exception for index > size");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * @tests java.util.ArrayList#indexOf(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "indexOf",
- args = {java.lang.Object.class}
- )
- public void test_indexOfLjava_lang_Object() {
- // Test for method int java.util.ArrayList.indexOf(java.lang.Object)
- assertEquals("Returned incorrect index",
- 87, alist.indexOf(objArray[87]));
- assertEquals("Returned index for invalid Object", -1, alist
- .indexOf(new Object()));
- alist.add(25, null);
- alist.add(50, null);
- assertTrue("Wrong indexOf for null. Wanted 25 got: "
- + alist.indexOf(null), alist.indexOf(null) == 25);
- }
-
- /**
- * @tests java.util.ArrayList#isEmpty()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isEmpty",
- args = {}
- )
- public void test_isEmpty() {
- // Test for method boolean java.util.ArrayList.isEmpty()
- assertTrue("isEmpty returned false for new list", new ArrayList()
- .isEmpty());
- assertTrue("Returned true for existing list with elements", !alist
- .isEmpty());
- }
-
- /**
- * @tests java.util.ArrayList#lastIndexOf(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lastIndexOf",
- args = {java.lang.Object.class}
- )
- public void test_lastIndexOfLjava_lang_Object() {
- // Test for method int java.util.ArrayList.lastIndexOf(java.lang.Object)
- alist.add(new Integer(99));
- assertEquals("Returned incorrect index",
- 100, alist.lastIndexOf(objArray[99]));
- assertEquals("Returned index for invalid Object", -1, alist
- .lastIndexOf(new Object()));
- alist.add(25, null);
- alist.add(50, null);
- assertTrue("Wrong lastIndexOf for null. Wanted 50 got: "
- + alist.lastIndexOf(null), alist.lastIndexOf(null) == 50);
- }
-
- /**
- * @tests java.util.ArrayList#remove(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {int.class}
- )
- public void test_removeI() {
- // Test for method java.lang.Object java.util.ArrayList.remove(int)
- alist.remove(10);
- assertEquals("Failed to remove element",
- -1, alist.indexOf(objArray[10]));
- try {
- alist.remove(999);
- fail("Failed to throw exception when index out of range");
- } catch (IndexOutOfBoundsException e) {
- }
-
- ArrayList myList = (ArrayList) (((ArrayList) (alist)).clone());
- alist.add(25, null);
- alist.add(50, null);
- alist.remove(50);
- alist.remove(25);
- assertTrue("Removing nulls did not work", alist.equals(myList));
-
- List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c",
- "d", "e", "f", "g" }));
- assertTrue("Removed wrong element 1", list.remove(0) == "a");
- assertTrue("Removed wrong element 2", list.remove(4) == "f");
- String[] result = new String[5];
- list.toArray(result);
- assertTrue("Removed wrong element 3", Arrays.equals(result,
- new String[] { "b", "c", "d", "e", "g" }));
-
- List l = new ArrayList(0);
- l.add(new Object());
- l.add(new Object());
- l.remove(0);
- l.remove(0);
- try {
- l.remove(-1);
- fail("-1 should cause exception");
- } catch (IndexOutOfBoundsException e) {
- }
- try {
- l.remove(0);
- fail("0 should case exception");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * @tests java.util.ArrayList#set(int, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "set",
- args = {int.class, java.lang.Object.class}
- )
- public void test_setILjava_lang_Object() {
- // Test for method java.lang.Object java.util.ArrayList.set(int,
- // java.lang.Object)
- Object obj;
- alist.set(65, obj = new Object());
- assertTrue("Failed to set object", alist.get(65) == obj);
- alist.set(50, null);
- assertNull("Setting to null did not work", alist.get(50));
- assertTrue("Setting increased the list's size to: " + alist.size(),
- alist.size() == 100);
-
- try {
- alist.set(-1, null);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- alist.set(alist.size() + 1, null);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.ArrayList#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- public void test_size() {
- // Test for method int java.util.ArrayList.size()
- assertEquals("Returned incorrect size for exiting list",
- 100, alist.size());
- assertEquals("Returned incorrect size for new list", 0, new ArrayList()
- .size());
- }
-
- /**
- * @tests java.util.ArrayList#toArray()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toArray",
- args = {}
- )
- public void test_toArray() {
- // Test for method java.lang.Object [] java.util.ArrayList.toArray()
- alist.set(25, null);
- alist.set(75, null);
- Object[] obj = alist.toArray();
- assertEquals("Returned array of incorrect size", objArray.length,
- obj.length);
-
- for (int i = 0; i < obj.length; i++) {
- if ((i == 25) || (i == 75))
- assertNull("Should be null at: " + i + " but instead got: "
- + obj[i], obj[i]);
- else
- assertTrue("Returned incorrect array: " + i,
- obj[i] == objArray[i]);
- }
-
- }
-
- /**
- * @tests java.util.ArrayList#toArray(java.lang.Object[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toArray",
- args = {java.lang.Object[].class}
- )
- public void test_toArray$Ljava_lang_Object() {
- // Test for method java.lang.Object []
- // java.util.ArrayList.toArray(java.lang.Object [])
- alist.set(25, null);
- alist.set(75, null);
- Integer[] argArray = new Integer[100];
- Object[] retArray;
- retArray = alist.toArray(argArray);
- assertTrue("Returned different array than passed", retArray == argArray);
- argArray = new Integer[1000];
- retArray = alist.toArray(argArray);
- assertNull("Failed to set first extra element to null", argArray[alist
- .size()]);
- for (int i = 0; i < 100; i++) {
- if ((i == 25) || (i == 75))
- assertNull("Should be null: " + i, retArray[i]);
- else
- assertTrue("Returned incorrect array: " + i,
- retArray[i] == objArray[i]);
- }
-
- String[] strArray = new String[100];
- try {
- alist.toArray(strArray);
- fail("ArrayStoreException expected");
- } catch (ArrayStoreException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.ArrayList#trimToSize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "trimToSize",
- args = {}
- )
- public void test_trimToSize_01() {
- // Test for method void java.util.ArrayList.trimToSize()
- for (int i = 99; i > 24; i--)
- alist.remove(i);
- ((ArrayList) alist).trimToSize();
- assertEquals("Returned incorrect size after trim", 25, alist.size());
- for (int i = 0; i < alist.size(); i++)
- assertTrue("Trimmed list contained incorrect elements", alist
- .get(i) == objArray[i]);
- Vector v = new Vector();
- v.add("a");
- v.add("b");
- ArrayList al = new ArrayList(v);
- Iterator it = al.iterator();
- al.remove(0);
- al.trimToSize();
- try {
- it.next();
- fail("should throw a ConcurrentModificationException");
- } catch (ConcurrentModificationException ioobe) {
- // expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "trimToSize",
- args = {}
- )
- public void test_trimToSize_02() {
- ArrayList list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c",
- "d", "e", "f", "g" }));
- list.remove("a");
- list.remove("f");
- list.trimToSize();
- }
-
- /**
- * @test java.util.ArrayList#addAll(int, Collection)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify NullPointerException.",
- method = "addAll",
- args = {int.class, java.util.Collection.class}
- )
- public void test_addAll() {
- ArrayList list = new ArrayList();
- list.add("one");
- list.add("two");
- assertEquals(2, list.size());
-
- list.remove(0);
- assertEquals(1, list.size());
-
- ArrayList collection = new ArrayList();
- collection.add("1");
- collection.add("2");
- collection.add("3");
- assertEquals(3, collection.size());
-
- list.addAll(0, collection);
- assertEquals(4, list.size());
-
- list.remove(0);
- list.remove(0);
- assertEquals(2, list.size());
-
- collection.add("4");
- collection.add("5");
- collection.add("6");
- collection.add("7");
- collection.add("8");
- collection.add("9");
- collection.add("10");
- collection.add("11");
- collection.add("12");
-
- assertEquals(12, collection.size());
-
- list.addAll(0, collection);
- assertEquals(14, list.size());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_removeLjava_lang_Object() {
- List list = new ArrayList(Arrays.asList(new String[] { "a", "b", "c",
- "d", "e", "f", "g" }));
- assertTrue("Removed wrong element 1", list.remove("a"));
- assertTrue("Removed wrong element 2", list.remove("f"));
- String[] result = new String[5];
- list.toArray(result);
- assertTrue("Removed wrong element 3", Arrays.equals(result,
- new String[] { "b", "c", "d", "e", "g" }));
- }
-
- class Mock_ArrayList extends ArrayList {
- public Mock_ArrayList() {
- }
-
- public void removeRange(int begin, int end) {
- super.removeRange(begin, end);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "removeRange",
- args = {int.class, int.class}
- )
- public void test_removeRangeII() {
- Mock_ArrayList mal = new Mock_ArrayList();
- mal.add("a");
- mal.add("b");
- mal.add("c");
- mal.add("d");
- mal.add("e");
- mal.add("f");
- mal.add("g");
- mal.add("h");
-
- mal.removeRange(2, 4);
-
- String[] result = new String[6];
- mal.toArray(result);
- assertTrue("Removed wrong element 3", Arrays.equals(result,
- new String[] { "a", "b", "e", "f", "g", "h"}));
- }
-
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() throws Exception {
- super.setUp();
- alist = new ArrayList();
- for (int i = 0; i < objArray.length; i++)
- alist.add(objArray[i]);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/ArraysTest.java b/luni/src/test/java/tests/api/java/util/ArraysTest.java
deleted file mode 100644
index d149226..0000000
--- a/luni/src/test/java/tests/api/java/util/ArraysTest.java
+++ /dev/null
@@ -1,2462 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.lang.reflect.Method;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.LinkedList;
-import java.util.List;
-
-import tests.support.Support_UnmodifiableCollectionTest;
-
-@TestTargetClass(Arrays.class)
-public class ArraysTest extends junit.framework.TestCase {
-
- public static class ReversedIntegerComparator implements Comparator {
- public int compare(Object o1, Object o2) {
- return -(((Integer) o1).compareTo((Integer) o2));
- }
-
- public boolean equals(Object o1, Object o2) {
- return ((Integer) o1).compareTo((Integer) o2) == 0;
- }
- }
-
- final static int arraySize = 100;
-
- static Object[] objArray;
-
- static boolean[] booleanArray;
-
- static byte[] byteArray;
-
- static char[] charArray;
-
- static double[] doubleArray;
-
- static float[] floatArray;
-
- static int[] intArray;
-
- static long[] longArray;
-
- static Object[] objectArray;
-
- static short[] shortArray;
- {
- objArray = new Object[arraySize];
- for (int i = 0; i < objArray.length; i++)
- objArray[i] = new Integer(i);
- }
-
- /**
- * @tests java.util.Arrays#asList(java.lang.Object[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "asList",
- args = {java.lang.Object[].class}
- )
- public void test_asList$Ljava_lang_Object() {
- // Test for method java.util.List
- // java.util.Arrays.asList(java.lang.Object [])
- List convertedList = Arrays.asList(objectArray);
- for (int counter = 0; counter < arraySize; counter++) {
- assertTrue(
- "Array and List converted from array do not contain identical elements",
- convertedList.get(counter) == objectArray[counter]);
- }
- convertedList.set(50, new Integer(1000));
- assertTrue("set/get did not work on coverted list", convertedList.get(
- 50).equals(new Integer(1000)));
- convertedList.set(50, new Integer(50));
- new Support_UnmodifiableCollectionTest("", convertedList).runTest();
-
- Object[] myArray = (Object[]) (objectArray.clone());
- myArray[30] = null;
- myArray[60] = null;
- convertedList = Arrays.asList(myArray);
- for (int counter = 0; counter < arraySize; counter++) {
- assertTrue(
- "Array and List converted from array do not contain identical elements",
- convertedList.get(counter) == myArray[counter]);
- }
-
- try {
- Arrays.asList((Object[])null);
- fail("asList with null arg didn't throw NPE");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.util.Arrays#binarySearch(byte[], byte)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "binarySearch",
- args = {byte[].class, byte.class}
- )
- public void test_binarySearch$BB() {
- // Test for method int java.util.Arrays.binarySearch(byte [], byte)
- for (byte counter = 0; counter < arraySize; counter++)
- assertTrue("Binary search on byte[] answered incorrect position",
- Arrays.binarySearch(byteArray, counter) == counter);
- assertEquals("Binary search succeeded for value not present in array 1",
- -1, Arrays.binarySearch(intArray, (byte) -1));
- assertTrue(
- "Binary search succeeded for value not present in array 2",
- Arrays.binarySearch(intArray, (byte) arraySize) == -(arraySize + 1));
- for (byte counter = 0; counter < arraySize; counter++)
- byteArray[counter] -= 50;
- for (byte counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on byte[] involving negative numbers answered incorrect position",
- Arrays.binarySearch(byteArray, (byte) (counter - 50)) == counter);
- }
-
- /**
- * @tests java.util.Arrays#binarySearch(char[], char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "binarySearch",
- args = {char[].class, char.class}
- )
- public void test_binarySearch$CC() {
- // Test for method int java.util.Arrays.binarySearch(char [], char)
- for (char counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on char[] answered incorrect position",
- Arrays.binarySearch(charArray, (char) (counter + 1)) == counter);
- assertEquals("Binary search succeeded for value not present in array 1",
- -1, Arrays.binarySearch(charArray, '\u0000'));
- assertTrue(
- "Binary search succeeded for value not present in array 2",
- Arrays.binarySearch(charArray, (char) (arraySize + 1)) == -(arraySize + 1));
- }
-
- /**
- * @tests java.util.Arrays#binarySearch(double[], double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "binarySearch",
- args = {double[].class, double.class}
- )
- public void test_binarySearch$DD() {
- // Test for method int java.util.Arrays.binarySearch(double [], double)
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on double[] answered incorrect position",
- Arrays.binarySearch(doubleArray, (double) counter) == (double) counter);
- assertEquals("Binary search succeeded for value not present in array 1",
- -1, Arrays.binarySearch(doubleArray, (double) -1));
- assertTrue(
- "Binary search succeeded for value not present in array 2",
- Arrays.binarySearch(doubleArray, (double) arraySize) == -(arraySize + 1));
- for (int counter = 0; counter < arraySize; counter++)
- doubleArray[counter] -= (double) 50;
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on double[] involving negative numbers answered incorrect position",
- Arrays.binarySearch(doubleArray, (double) (counter - 50)) == (double) counter);
-
- double[] specials = new double[] { Double.NEGATIVE_INFINITY,
- -Double.MAX_VALUE, -2d, -Double.MIN_VALUE, -0d, 0d,
- Double.MIN_VALUE, 2d, Double.MAX_VALUE,
- Double.POSITIVE_INFINITY, Double.NaN };
- for (int i = 0; i < specials.length; i++) {
- int result = Arrays.binarySearch(specials, specials[i]);
- assertTrue(specials[i] + " invalid: " + result, result == i);
- }
- assertEquals("-1d", -4, Arrays.binarySearch(specials, -1d));
- assertEquals("1d", -8, Arrays.binarySearch(specials, 1d));
-
- }
-
- /**
- * @tests java.util.Arrays#binarySearch(float[], float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "binarySearch",
- args = {float[].class, float.class}
- )
- public void test_binarySearch$FF() {
- // Test for method int java.util.Arrays.binarySearch(float [], float)
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on float[] answered incorrect position",
- Arrays.binarySearch(floatArray, (float) counter) == (float) counter);
- assertEquals("Binary search succeeded for value not present in array 1",
- -1, Arrays.binarySearch(floatArray, (float) -1));
- assertTrue(
- "Binary search succeeded for value not present in array 2",
- Arrays.binarySearch(floatArray, (float) arraySize) == -(arraySize + 1));
- for (int counter = 0; counter < arraySize; counter++)
- floatArray[counter] -= (float) 50;
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on float[] involving negative numbers answered incorrect position",
- Arrays.binarySearch(floatArray, (float) counter - 50) == (float) counter);
-
- float[] specials = new float[] { Float.NEGATIVE_INFINITY,
- -Float.MAX_VALUE, -2f, -Float.MIN_VALUE, -0f, 0f,
- Float.MIN_VALUE, 2f, Float.MAX_VALUE, Float.POSITIVE_INFINITY,
- Float.NaN };
- for (int i = 0; i < specials.length; i++) {
- int result = Arrays.binarySearch(specials, specials[i]);
- assertTrue(specials[i] + " invalid: " + result, result == i);
- }
- assertEquals("-1f", -4, Arrays.binarySearch(specials, -1f));
- assertEquals("1f", -8, Arrays.binarySearch(specials, 1f));
- }
-
- /**
- * @tests java.util.Arrays#binarySearch(int[], int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "binarySearch",
- args = {int[].class, int.class}
- )
- public void test_binarySearch$II() {
- // Test for method int java.util.Arrays.binarySearch(int [], int)
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue("Binary search on int[] answered incorrect position",
- Arrays.binarySearch(intArray, counter) == counter);
- assertEquals("Binary search succeeded for value not present in array 1",
- -1, Arrays.binarySearch(intArray, -1));
- assertTrue("Binary search succeeded for value not present in array 2",
- Arrays.binarySearch(intArray, arraySize) == -(arraySize + 1));
- for (int counter = 0; counter < arraySize; counter++)
- intArray[counter] -= 50;
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on int[] involving negative numbers answered incorrect position",
- Arrays.binarySearch(intArray, counter - 50) == counter);
- }
-
- /**
- * @tests java.util.Arrays#binarySearch(long[], long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "binarySearch",
- args = {long[].class, long.class}
- )
- public void test_binarySearch$JJ() {
- // Test for method int java.util.Arrays.binarySearch(long [], long)
- for (long counter = 0; counter < arraySize; counter++)
- assertTrue("Binary search on long[] answered incorrect position",
- Arrays.binarySearch(longArray, counter) == counter);
- assertEquals("Binary search succeeded for value not present in array 1",
- -1, Arrays.binarySearch(longArray, (long) -1));
- assertTrue(
- "Binary search succeeded for value not present in array 2",
- Arrays.binarySearch(longArray, (long) arraySize) == -(arraySize + 1));
- for (long counter = 0; counter < arraySize; counter++)
- longArray[(int) counter] -= (long) 50;
- for (long counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on long[] involving negative numbers answered incorrect position",
- Arrays.binarySearch(longArray, counter - (long) 50) == counter);
- }
-
- /**
- * @tests java.util.Arrays#binarySearch(java.lang.Object[],
- * java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "binarySearch",
- args = {java.lang.Object[].class, java.lang.Object.class}
- )
- public void test_binarySearch$Ljava_lang_ObjectLjava_lang_Object() {
- // Test for method int java.util.Arrays.binarySearch(java.lang.Object
- // [], java.lang.Object)
- assertEquals(
- "Binary search succeeded for non-comparable value in empty array",
- -1, Arrays.binarySearch(new Object[] {}, new Object()));
- assertEquals(
- "Binary search succeeded for comparable value in empty array",
- -1, Arrays.binarySearch(new Object[] {}, new Integer(-1)));
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on Object[] answered incorrect position",
- Arrays.binarySearch(objectArray, objArray[counter]) == counter);
- assertEquals("Binary search succeeded for value not present in array 1",
- -1, Arrays.binarySearch(objectArray, new Integer(-1)));
- assertTrue(
- "Binary search succeeded for value not present in array 2",
- Arrays.binarySearch(objectArray, new Integer(arraySize)) == -(arraySize + 1));
-
- String[] sArray = new String[]{"1", "2", "3", "4", ""};
- Object[] oArray = sArray;
-
- try {
- Arrays.binarySearch(oArray, new Integer(10));
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Arrays#binarySearch(java.lang.Object[],
- * java.lang.Object, java.util.Comparator)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ClassCastException.",
- method = "binarySearch",
- args = {java.lang.Object[].class, java.lang.Object.class, java.util.Comparator.class}
- )
- public void test_binarySearch$Ljava_lang_ObjectLjava_lang_ObjectLjava_util_Comparator() {
- // Test for method int java.util.Arrays.binarySearch(java.lang.Object
- // [], java.lang.Object, java.util.Comparator)
- Comparator comp = new ReversedIntegerComparator();
- for (int counter = 0; counter < arraySize; counter++)
- objectArray[counter] = objArray[arraySize - counter - 1];
- assertTrue(
- "Binary search succeeded for value not present in array 1",
- Arrays.binarySearch(objectArray, new Integer(-1), comp) == -(arraySize + 1));
- assertEquals("Binary search succeeded for value not present in array 2",
- -1, Arrays.binarySearch(objectArray, new Integer(arraySize), comp));
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on Object[] with custom comparator answered incorrect position",
- Arrays.binarySearch(objectArray, objArray[counter], comp) == arraySize
- - counter - 1);
- }
-
- /**
- * @tests java.util.Arrays#binarySearch(short[], short)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "binarySearch",
- args = {short[].class, short.class}
- )
- public void test_binarySearch$SS() {
- // Test for method int java.util.Arrays.binarySearch(short [], short)
- for (short counter = 0; counter < arraySize; counter++)
- assertTrue("Binary search on short[] answered incorrect position",
- Arrays.binarySearch(shortArray, counter) == counter);
- assertEquals("Binary search succeeded for value not present in array 1",
- -1, Arrays.binarySearch(intArray, (short) -1));
- assertTrue(
- "Binary search succeeded for value not present in array 2",
- Arrays.binarySearch(intArray, (short) arraySize) == -(arraySize + 1));
- for (short counter = 0; counter < arraySize; counter++)
- shortArray[counter] -= 50;
- for (short counter = 0; counter < arraySize; counter++)
- assertTrue(
- "Binary search on short[] involving negative numbers answered incorrect position",
- Arrays.binarySearch(shortArray, (short) (counter - 50)) == counter);
- }
-
- /**
- * @tests java.util.Arrays#fill(byte[], byte)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fill",
- args = {byte[].class, byte.class}
- )
- public void test_fill$BB() {
- // Test for method void java.util.Arrays.fill(byte [], byte)
-
- byte d[] = new byte[1000];
- Arrays.fill(d, Byte.MAX_VALUE);
- for (int i = 0; i < d.length; i++)
- assertTrue("Failed to fill byte array correctly",
- d[i] == Byte.MAX_VALUE);
- }
-
- /**
- * @tests java.util.Arrays#fill(byte[], int, int, byte)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fill",
- args = {byte[].class, int.class, int.class, byte.class}
- )
- public void test_fill$BIIB() {
- // Test for method void java.util.Arrays.fill(byte [], int, int, byte)
- byte val = Byte.MAX_VALUE;
- byte d[] = new byte[1000];
- Arrays.fill(d, 400, d.length, val);
- for (int i = 0; i < 400; i++)
- assertTrue("Filled elements not in range", !(d[i] == val));
- for (int i = 400; i < d.length; i++)
- assertTrue("Failed to fill byte array correctly", d[i] == val);
-
- int result;
- try {
- Arrays.fill(new byte[2], 2, 1, (byte) 27);
- result = 0;
- } catch (ArrayIndexOutOfBoundsException e) {
- result = 1;
- } catch (IllegalArgumentException e) {
- result = 2;
- }
- assertEquals("Wrong exception1", 2, result);
- try {
- Arrays.fill(new byte[2], -1, 1, (byte) 27);
- result = 0;
- } catch (ArrayIndexOutOfBoundsException e) {
- result = 1;
- } catch (IllegalArgumentException e) {
- result = 2;
- }
- assertEquals("Wrong exception2", 1, result);
- try {
- Arrays.fill(new byte[2], 1, 4, (byte) 27);
- result = 0;
- } catch (ArrayIndexOutOfBoundsException e) {
- result = 1;
- } catch (IllegalArgumentException e) {
- result = 2;
- }
- assertEquals("Wrong exception", 1, result);
- }
-
- /**
- * @tests java.util.Arrays#fill(short[], short)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fill",
- args = {short[].class, short.class}
- )
- public void test_fill$SS() {
- // Test for method void java.util.Arrays.fill(short [], short)
-
- short d[] = new short[1000];
- Arrays.fill(d, Short.MAX_VALUE);
- for (int i = 0; i < d.length; i++)
- assertTrue("Failed to fill short array correctly",
- d[i] == Short.MAX_VALUE);
- }
-
- /**
- * @tests java.util.Arrays#fill(short[], int, int, short)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fill",
- args = {short[].class, int.class, int.class, short.class}
- )
- public void test_fill$SIIS() {
- // Test for method void java.util.Arrays.fill(short [], int, int, short)
- short val = Short.MAX_VALUE;
- short d[] = new short[1000];
- Arrays.fill(d, 400, d.length, val);
- for (int i = 0; i < 400; i++)
- assertTrue("Filled elements not in range", !(d[i] == val));
- for (int i = 400; i < d.length; i++)
- assertTrue("Failed to fill short array correctly", d[i] == val);
-
- try {
- Arrays.fill(d, 10, 0, val);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, -10, 0, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, 10, d.length+1, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Arrays#fill(char[], char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fill",
- args = {char[].class, char.class}
- )
- public void test_fill$CC() {
- // Test for method void java.util.Arrays.fill(char [], char)
-
- char d[] = new char[1000];
- Arrays.fill(d, 'V');
- for (int i = 0; i < d.length; i++)
- assertEquals("Failed to fill char array correctly", 'V', d[i]);
- }
-
- /**
- * @tests java.util.Arrays#fill(char[], int, int, char)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fill",
- args = {char[].class, int.class, int.class, char.class}
- )
- public void test_fill$CIIC() {
- // Test for method void java.util.Arrays.fill(char [], int, int, char)
- char val = 'T';
- char d[] = new char[1000];
- Arrays.fill(d, 400, d.length, val);
- for (int i = 0; i < 400; i++)
- assertTrue("Filled elements not in range", !(d[i] == val));
- for (int i = 400; i < d.length; i++)
- assertTrue("Failed to fill char array correctly", d[i] == val);
-
- try {
- Arrays.fill(d, 10, 0, val);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, -10, 0, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, 10, d.length+1, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Arrays#fill(int[], int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fill",
- args = {int[].class, int.class}
- )
- public void test_fill$II() {
- // Test for method void java.util.Arrays.fill(int [], int)
-
- int d[] = new int[1000];
- Arrays.fill(d, Integer.MAX_VALUE);
- for (int i = 0; i < d.length; i++)
- assertTrue("Failed to fill int array correctly",
- d[i] == Integer.MAX_VALUE);
- }
-
- /**
- * @tests java.util.Arrays#fill(int[], int, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fill",
- args = {int[].class, int.class, int.class, int.class}
- )
- public void test_fill$IIII() {
- // Test for method void java.util.Arrays.fill(int [], int, int, int)
- int val = Integer.MAX_VALUE;
- int d[] = new int[1000];
- Arrays.fill(d, 400, d.length, val);
- for (int i = 0; i < 400; i++)
- assertTrue("Filled elements not in range", !(d[i] == val));
- for (int i = 400; i < d.length; i++)
- assertTrue("Failed to fill int array correctly", d[i] == val);
-
- try {
- Arrays.fill(d, 10, 0, val);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, -10, 0, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, 10, d.length+1, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Arrays#fill(long[], long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fill",
- args = {long[].class, long.class}
- )
- public void test_fill$JJ() {
- // Test for method void java.util.Arrays.fill(long [], long)
-
- long d[] = new long[1000];
- Arrays.fill(d, Long.MAX_VALUE);
- for (int i = 0; i < d.length; i++)
- assertTrue("Failed to fill long array correctly",
- d[i] == Long.MAX_VALUE);
- }
-
- /**
- * @tests java.util.Arrays#fill(long[], int, int, long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fill",
- args = {long[].class, int.class, int.class, long.class}
- )
- public void test_fill$JIIJ() {
- // Test for method void java.util.Arrays.fill(long [], int, int, long)
- long d[] = new long[1000];
- Arrays.fill(d, 400, d.length, Long.MAX_VALUE);
- for (int i = 0; i < 400; i++)
- assertTrue("Filled elements not in range", !(d[i] == Long.MAX_VALUE));
- for (int i = 400; i < d.length; i++)
- assertTrue("Failed to fill long array correctly",
- d[i] == Long.MAX_VALUE);
-
- try {
- Arrays.fill(d, 10, 0, Long.MIN_VALUE);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, -10, 0, Long.MAX_VALUE);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, 10, d.length+1, Long.MAX_VALUE);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Arrays#fill(float[], float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fill",
- args = {float[].class, float.class}
- )
- public void test_fill$FF() {
- // Test for method void java.util.Arrays.fill(float [], float)
- float d[] = new float[1000];
- Arrays.fill(d, Float.MAX_VALUE);
- for (int i = 0; i < d.length; i++)
- assertTrue("Failed to fill float array correctly",
- d[i] == Float.MAX_VALUE);
- }
-
- /**
- * @tests java.util.Arrays#fill(float[], int, int, float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fill",
- args = {float[].class, int.class, int.class, float.class}
- )
- public void test_fill$FIIF() {
- // Test for method void java.util.Arrays.fill(float [], int, int, float)
- float val = Float.MAX_VALUE;
- float d[] = new float[1000];
- Arrays.fill(d, 400, d.length, val);
- for (int i = 0; i < 400; i++)
- assertTrue("Filled elements not in range", !(d[i] == val));
- for (int i = 400; i < d.length; i++)
- assertTrue("Failed to fill float array correctly", d[i] == val);
-
- try {
- Arrays.fill(d, 10, 0, val);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, -10, 0, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, 10, d.length+1, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Arrays#fill(double[], double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fill",
- args = {double[].class, double.class}
- )
- public void test_fill$DD() {
- // Test for method void java.util.Arrays.fill(double [], double)
-
- double d[] = new double[1000];
- Arrays.fill(d, Double.MAX_VALUE);
- for (int i = 0; i < d.length; i++)
- assertTrue("Failed to fill double array correctly",
- d[i] == Double.MAX_VALUE);
- }
-
- /**
- * @tests java.util.Arrays#fill(double[], int, int, double)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fill",
- args = {double[].class, int.class, int.class, double.class}
- )
- public void test_fill$DIID() {
- // Test for method void java.util.Arrays.fill(double [], int, int,
- // double)
- double val = Double.MAX_VALUE;
- double d[] = new double[1000];
- Arrays.fill(d, 400, d.length, val);
- for (int i = 0; i < 400; i++)
- assertTrue("Filled elements not in range", !(d[i] == val));
- for (int i = 400; i < d.length; i++)
- assertTrue("Failed to fill double array correctly", d[i] == val);
-
- try {
- Arrays.fill(d, 10, 0, val);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, -10, 0, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, 10, d.length+1, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Arrays#fill(boolean[], boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fill",
- args = {boolean[].class, boolean.class}
- )
- public void test_fill$ZZ() {
- // Test for method void java.util.Arrays.fill(boolean [], boolean)
-
- boolean d[] = new boolean[1000];
- Arrays.fill(d, true);
- for (int i = 0; i < d.length; i++)
- assertTrue("Failed to fill boolean array correctly", d[i]);
- }
-
- /**
- * @tests java.util.Arrays#fill(boolean[], int, int, boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fill",
- args = {boolean[].class, int.class, int.class, boolean.class}
- )
- public void test_fill$ZIIZ() {
- // Test for method void java.util.Arrays.fill(boolean [], int, int,
- // boolean)
- boolean val = true;
- boolean d[] = new boolean[1000];
- Arrays.fill(d, 400, d.length, val);
- for (int i = 0; i < 400; i++)
- assertTrue("Filled elements not in range", !(d[i] == val));
- for (int i = 400; i < d.length; i++)
- assertTrue("Failed to fill boolean array correctly", d[i] == val);
-
- try {
- Arrays.fill(d, 10, 0, val);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, -10, 0, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, 10, d.length+1, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Arrays#fill(java.lang.Object[], java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fill",
- args = {java.lang.Object[].class, java.lang.Object.class}
- )
- public void test_fill$Ljava_lang_ObjectLjava_lang_Object() {
- // Test for method void java.util.Arrays.fill(java.lang.Object [],
- // java.lang.Object)
- Object val = new Object();
- Object d[] = new Object[1000];
- Arrays.fill(d, 0, d.length, val);
- for (int i = 0; i < d.length; i++)
- assertTrue("Failed to fill Object array correctly", d[i] == val);
- }
-
- /**
- * @tests java.util.Arrays#fill(java.lang.Object[], int, int,
- * java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fill",
- args = {java.lang.Object[].class, int.class, int.class, java.lang.Object.class}
- )
- public void test_fill$Ljava_lang_ObjectIILjava_lang_Object() {
- // Test for method void java.util.Arrays.fill(java.lang.Object [], int,
- // int, java.lang.Object)
- Object val = new Object();
- Object d[] = new Object[1000];
- Arrays.fill(d, 400, d.length, val);
- for (int i = 0; i < 400; i++)
- assertTrue("Filled elements not in range", !(d[i] == val));
- for (int i = 400; i < d.length; i++)
- assertTrue("Failed to fill Object array correctly", d[i] == val);
-
- Arrays.fill(d, 400, d.length, null);
- for (int i = 400; i < d.length; i++)
- assertNull("Failed to fill Object array correctly with nulls",
- d[i]);
-
- try {
- Arrays.fill(d, 10, 0, val);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, -10, 0, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.fill(d, 10, d.length+1, val);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Arrays#equals(byte[], byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {byte[].class, byte[].class}
- )
- public void test_equals$B$B() {
- // Test for method boolean java.util.Arrays.equals(byte [], byte [])
- byte d[] = new byte[1000];
- byte x[] = new byte[1000];
- Arrays.fill(d, Byte.MAX_VALUE);
- Arrays.fill(x, Byte.MIN_VALUE);
- assertTrue("Inequal arrays returned true", !Arrays.equals(d, x));
- Arrays.fill(x, Byte.MAX_VALUE);
- assertTrue("equal arrays returned false", Arrays.equals(d, x));
- }
-
- /**
- * @tests java.util.Arrays#equals(short[], short[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {short[].class, short[].class}
- )
- public void test_equals$S$S() {
- // Test for method boolean java.util.Arrays.equals(short [], short [])
- short d[] = new short[1000];
- short x[] = new short[1000];
- Arrays.fill(d, Short.MAX_VALUE);
- Arrays.fill(x, Short.MIN_VALUE);
- assertTrue("Inequal arrays returned true", !Arrays.equals(d, x));
- Arrays.fill(x, Short.MAX_VALUE);
- assertTrue("equal arrays returned false", Arrays.equals(d, x));
- }
-
- /**
- * @tests java.util.Arrays#equals(char[], char[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {char[].class, char[].class}
- )
- public void test_equals$C$C() {
- // Test for method boolean java.util.Arrays.equals(char [], char [])
- char d[] = new char[1000];
- char x[] = new char[1000];
- char c = 'T';
- Arrays.fill(d, c);
- Arrays.fill(x, 'L');
- assertTrue("Inequal arrays returned true", !Arrays.equals(d, x));
- Arrays.fill(x, c);
- assertTrue("equal arrays returned false", Arrays.equals(d, x));
- }
-
- /**
- * @tests java.util.Arrays#equals(int[], int[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {int[].class, int[].class}
- )
- public void test_equals$I$I() {
- // Test for method boolean java.util.Arrays.equals(int [], int [])
- int d[] = new int[1000];
- int x[] = new int[1000];
- Arrays.fill(d, Integer.MAX_VALUE);
- Arrays.fill(x, Integer.MIN_VALUE);
- assertTrue("Inequal arrays returned true", !Arrays.equals(d, x));
- Arrays.fill(x, Integer.MAX_VALUE);
- assertTrue("equal arrays returned false", Arrays.equals(d, x));
-
- assertTrue("wrong result for null array1", !Arrays.equals(new int[2],
- null));
- assertTrue("wrong result for null array2", !Arrays.equals(null,
- new int[2]));
- }
-
- /**
- * @tests java.util.Arrays#equals(long[], long[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {long[].class, long[].class}
- )
- public void test_equals$J$J() {
- // Test for method boolean java.util.Arrays.equals(long [], long [])
- long d[] = new long[1000];
- long x[] = new long[1000];
- Arrays.fill(d, Long.MAX_VALUE);
- Arrays.fill(x, Long.MIN_VALUE);
- assertTrue("Inequal arrays returned true", !Arrays.equals(d, x));
- Arrays.fill(x, Long.MAX_VALUE);
- assertTrue("equal arrays returned false", Arrays.equals(d, x));
-
- assertTrue("should be false", !Arrays.equals(
- new long[] { 0x100000000L }, new long[] { 0x200000000L }));
-
- }
-
- /**
- * @tests java.util.Arrays#equals(float[], float[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {float[].class, float[].class}
- )
- public void test_equals$F$F() {
- // Test for method boolean java.util.Arrays.equals(float [], float [])
- float d[] = new float[1000];
- float x[] = new float[1000];
- Arrays.fill(d, Float.MAX_VALUE);
- Arrays.fill(x, Float.MIN_VALUE);
- assertTrue("Inequal arrays returned true", !Arrays.equals(d, x));
- Arrays.fill(x, Float.MAX_VALUE);
- assertTrue("equal arrays returned false", Arrays.equals(d, x));
-
- assertTrue("NaN not equals", Arrays.equals(new float[] { Float.NaN },
- new float[] { Float.NaN }));
- assertTrue("0f equals -0f", !Arrays.equals(new float[] { 0f },
- new float[] { -0f }));
- }
-
- /**
- * @tests java.util.Arrays#equals(double[], double[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {double[].class, double[].class}
- )
- public void test_equals$D$D() {
- // Test for method boolean java.util.Arrays.equals(double [], double [])
- double d[] = new double[1000];
- double x[] = new double[1000];
- Arrays.fill(d, Double.MAX_VALUE);
- Arrays.fill(x, Double.MIN_VALUE);
- assertTrue("Inequal arrays returned true", !Arrays.equals(d, x));
- Arrays.fill(x, Double.MAX_VALUE);
- assertTrue("equal arrays returned false", Arrays.equals(d, x));
-
- assertTrue("should be false", !Arrays.equals(new double[] { 1.0 },
- new double[] { 2.0 }));
-
- assertTrue("NaN not equals", Arrays.equals(new double[] { Double.NaN },
- new double[] { Double.NaN }));
- assertTrue("0d equals -0d", !Arrays.equals(new double[] { 0d },
- new double[] { -0d }));
- }
-
- /**
- * @tests java.util.Arrays#equals(boolean[], boolean[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {boolean[].class, boolean[].class}
- )
- public void test_equals$Z$Z() {
- // Test for method boolean java.util.Arrays.equals(boolean [], boolean
- // [])
- boolean d[] = new boolean[1000];
- boolean x[] = new boolean[1000];
- Arrays.fill(d, true);
- Arrays.fill(x, false);
- assertTrue("Inequal arrays returned true", !Arrays.equals(d, x));
- Arrays.fill(x, true);
- assertTrue("equal arrays returned false", Arrays.equals(d, x));
- }
-
- /**
- * @tests java.util.Arrays#equals(java.lang.Object[], java.lang.Object[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object[].class, java.lang.Object[].class}
- )
- public void test_equals$Ljava_lang_Object$Ljava_lang_Object() {
- // Test for method boolean java.util.Arrays.equals(java.lang.Object [],
- // java.lang.Object [])
- Object d[] = new Object[1000];
- Object x[] = new Object[1000];
- Object o = new Object();
- Arrays.fill(d, o);
- Arrays.fill(x, new Object());
- assertTrue("Inequal arrays returned true", !Arrays.equals(d, x));
- Arrays.fill(x, o);
- d[50] = null;
- x[50] = null;
- assertTrue("equal arrays returned false", Arrays.equals(d, x));
- }
-
- /**
- * @tests java.util.Arrays#sort(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {byte[].class}
- )
- public void test_sort$B() {
- // Test for method void java.util.Arrays.sort(byte [])
- byte[] reversedArray = new byte[arraySize];
- for (int counter = 0; counter < arraySize; counter++)
- reversedArray[counter] = (byte) (arraySize - counter - 1);
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue("Resulting array not sorted",
- reversedArray[counter] == (byte) counter);
- }
-
- /**
- * @tests java.util.Arrays#sort(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {byte[].class, int.class, int.class}
- )
- public void test_sort$BII() {
- // Test for method void java.util.Arrays.sort(byte [], int, int)
- int startIndex = arraySize / 4;
- int endIndex = 3 * arraySize / 4;
- byte[] reversedArray = new byte[arraySize];
- byte[] originalReversedArray = new byte[arraySize];
- for (int counter = 0; counter < arraySize; counter++) {
- reversedArray[counter] = (byte) (arraySize - counter - 1);
- originalReversedArray[counter] = reversedArray[counter];
- }
- Arrays.sort(reversedArray, startIndex, endIndex);
- for (int counter = 0; counter < startIndex; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
- for (int counter = startIndex; counter < endIndex - 1; counter++)
- assertTrue("Array not sorted within bounds",
- reversedArray[counter] <= reversedArray[counter + 1]);
- for (int counter = endIndex; counter < arraySize; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
-
- //exception testing
- try {
- Arrays.sort(reversedArray, startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, -1, startIndex);
- fail("ArrayIndexOutOfBoundsException expected (1)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, startIndex, reversedArray.length + 1);
- fail("ArrayIndexOutOfBoundsException expected (2)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- //exception order testing
- try {
- Arrays.sort(new byte[1], startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
- }
-
- /**
- * @tests java.util.Arrays#sort(char[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {char[].class}
- )
- public void test_sort$C() {
- // Test for method void java.util.Arrays.sort(char [])
- char[] reversedArray = new char[arraySize];
- for (int counter = 0; counter < arraySize; counter++)
- reversedArray[counter] = (char) (arraySize - counter - 1);
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue("Resulting array not sorted",
- reversedArray[counter] == (char) counter);
-
- }
-
- /**
- * @tests java.util.Arrays#sort(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {char[].class, int.class, int.class}
- )
- public void test_sort$CII() {
- // Test for method void java.util.Arrays.sort(char [], int, int)
- int startIndex = arraySize / 4;
- int endIndex = 3 * arraySize / 4;
- char[] reversedArray = new char[arraySize];
- char[] originalReversedArray = new char[arraySize];
- for (int counter = 0; counter < arraySize; counter++) {
- reversedArray[counter] = (char) (arraySize - counter - 1);
- originalReversedArray[counter] = reversedArray[counter];
- }
- Arrays.sort(reversedArray, startIndex, endIndex);
- for (int counter = 0; counter < startIndex; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
- for (int counter = startIndex; counter < endIndex - 1; counter++)
- assertTrue("Array not sorted within bounds",
- reversedArray[counter] <= reversedArray[counter + 1]);
- for (int counter = endIndex; counter < arraySize; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
-
- //exception testing
- try {
- Arrays.sort(reversedArray, startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, -1, startIndex);
- fail("ArrayIndexOutOfBoundsException expected (1)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, startIndex, reversedArray.length + 1);
- fail("ArrayIndexOutOfBoundsException expected (2)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- //exception order testing
- try {
- Arrays.sort(new char[1], startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
- }
-
- /**
- * @tests java.util.Arrays#sort(double[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {double[].class}
- )
- public void test_sort$D() {
- // Test for method void java.util.Arrays.sort(double [])
- double[] reversedArray = new double[arraySize];
- for (int counter = 0; counter < arraySize; counter++)
- reversedArray[counter] = (double) (arraySize - counter - 1);
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue("Resulting array not sorted",
- reversedArray[counter] == (double) counter);
-
- double[] specials1 = new double[] { Double.NaN, Double.MAX_VALUE,
- Double.MIN_VALUE, 0d, -0d, Double.POSITIVE_INFINITY,
- Double.NEGATIVE_INFINITY };
- double[] specials2 = new double[] { 0d, Double.POSITIVE_INFINITY, -0d,
- Double.NEGATIVE_INFINITY, Double.MIN_VALUE, Double.NaN,
- Double.MAX_VALUE };
- double[] answer = new double[] { Double.NEGATIVE_INFINITY, -0d, 0d,
- Double.MIN_VALUE, Double.MAX_VALUE, Double.POSITIVE_INFINITY,
- Double.NaN };
-
- Arrays.sort(specials1);
- Object[] print1 = new Object[specials1.length];
- for (int i = 0; i < specials1.length; i++)
- print1[i] = new Double(specials1[i]);
- assertTrue("specials sort incorrectly 1: " + Arrays.asList(print1),
- Arrays.equals(specials1, answer));
-
- Arrays.sort(specials2);
- Object[] print2 = new Object[specials2.length];
- for (int i = 0; i < specials2.length; i++)
- print2[i] = new Double(specials2[i]);
- assertTrue("specials sort incorrectly 2: " + Arrays.asList(print2),
- Arrays.equals(specials2, answer));
- }
-
- /**
- * @tests java.util.Arrays#sort(double[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {double[].class, int.class, int.class}
- )
- public void test_sort$DII() {
- // Test for method void java.util.Arrays.sort(double [], int, int)
- int startIndex = arraySize / 4;
- int endIndex = 3 * arraySize / 4;
- double[] reversedArray = new double[arraySize];
- double[] originalReversedArray = new double[arraySize];
- for (int counter = 0; counter < arraySize; counter++) {
- reversedArray[counter] = (double) (arraySize - counter - 1);
- originalReversedArray[counter] = reversedArray[counter];
- }
- Arrays.sort(reversedArray, startIndex, endIndex);
- for (int counter = 0; counter < startIndex; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
- for (int counter = startIndex; counter < endIndex - 1; counter++)
- assertTrue("Array not sorted within bounds",
- reversedArray[counter] <= reversedArray[counter + 1]);
- for (int counter = endIndex; counter < arraySize; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
-
- //exception testing
- try {
- Arrays.sort(reversedArray, startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, -1, startIndex);
- fail("ArrayIndexOutOfBoundsException expected (1)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, startIndex, reversedArray.length + 1);
- fail("ArrayIndexOutOfBoundsException expected (2)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- //exception order testing
- try {
- Arrays.sort(new double[1], startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
- }
-
- /**
- * @tests java.util.Arrays#sort(float[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {float[].class}
- )
- public void test_sort$F() {
- // Test for method void java.util.Arrays.sort(float [])
- float[] reversedArray = new float[arraySize];
- for (int counter = 0; counter < arraySize; counter++)
- reversedArray[counter] = (float) (arraySize - counter - 1);
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue("Resulting array not sorted",
- reversedArray[counter] == (float) counter);
-
- float[] specials1 = new float[] { Float.NaN, Float.MAX_VALUE,
- Float.MIN_VALUE, 0f, -0f, Float.POSITIVE_INFINITY,
- Float.NEGATIVE_INFINITY };
- float[] specials2 = new float[] { 0f, Float.POSITIVE_INFINITY, -0f,
- Float.NEGATIVE_INFINITY, Float.MIN_VALUE, Float.NaN,
- Float.MAX_VALUE };
- float[] answer = new float[] { Float.NEGATIVE_INFINITY, -0f, 0f,
- Float.MIN_VALUE, Float.MAX_VALUE, Float.POSITIVE_INFINITY,
- Float.NaN };
-
- Arrays.sort(specials1);
- Object[] print1 = new Object[specials1.length];
- for (int i = 0; i < specials1.length; i++)
- print1[i] = new Float(specials1[i]);
- assertTrue("specials sort incorrectly 1: " + Arrays.asList(print1),
- Arrays.equals(specials1, answer));
-
- Arrays.sort(specials2);
- Object[] print2 = new Object[specials2.length];
- for (int i = 0; i < specials2.length; i++)
- print2[i] = new Float(specials2[i]);
- assertTrue("specials sort incorrectly 2: " + Arrays.asList(print2),
- Arrays.equals(specials2, answer));
- }
-
- /**
- * @tests java.util.Arrays#sort(float[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {float[].class, int.class, int.class}
- )
- public void test_sort$FII() {
- // Test for method void java.util.Arrays.sort(float [], int, int)
- int startIndex = arraySize / 4;
- int endIndex = 3 * arraySize / 4;
- float[] reversedArray = new float[arraySize];
- float[] originalReversedArray = new float[arraySize];
- for (int counter = 0; counter < arraySize; counter++) {
- reversedArray[counter] = (float) (arraySize - counter - 1);
- originalReversedArray[counter] = reversedArray[counter];
- }
- Arrays.sort(reversedArray, startIndex, endIndex);
- for (int counter = 0; counter < startIndex; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
- for (int counter = startIndex; counter < endIndex - 1; counter++)
- assertTrue("Array not sorted within bounds",
- reversedArray[counter] <= reversedArray[counter + 1]);
- for (int counter = endIndex; counter < arraySize; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
-
- //exception testing
- try {
- Arrays.sort(reversedArray, startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, -1, startIndex);
- fail("ArrayIndexOutOfBoundsException expected (1)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, startIndex, reversedArray.length + 1);
- fail("ArrayIndexOutOfBoundsException expected (2)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- //exception order testing
- try {
- Arrays.sort(new float[1], startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
- }
-
- /**
- * @tests java.util.Arrays#sort(int[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {int[].class}
- )
- public void test_sort$I() {
- // Test for method void java.util.Arrays.sort(int [])
- int[] reversedArray = new int[arraySize];
- for (int counter = 0; counter < arraySize; counter++)
- reversedArray[counter] = arraySize - counter - 1;
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue("Resulting array not sorted",
- reversedArray[counter] == counter);
- }
-
- /**
- * @tests java.util.Arrays#sort(int[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {int[].class, int.class, int.class}
- )
- public void test_sort$III() {
- // Test for method void java.util.Arrays.sort(int [], int, int)
- int startIndex = arraySize / 4;
- int endIndex = 3 * arraySize / 4;
- int[] reversedArray = new int[arraySize];
- int[] originalReversedArray = new int[arraySize];
- for (int counter = 0; counter < arraySize; counter++) {
- reversedArray[counter] = arraySize - counter - 1;
- originalReversedArray[counter] = reversedArray[counter];
- }
- Arrays.sort(reversedArray, startIndex, endIndex);
- for (int counter = 0; counter < startIndex; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
- for (int counter = startIndex; counter < endIndex - 1; counter++)
- assertTrue("Array not sorted within bounds",
- reversedArray[counter] <= reversedArray[counter + 1]);
- for (int counter = endIndex; counter < arraySize; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
-
- //exception testing
- try {
- Arrays.sort(reversedArray, startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, -1, startIndex);
- fail("ArrayIndexOutOfBoundsException expected (1)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, startIndex, reversedArray.length + 1);
- fail("ArrayIndexOutOfBoundsException expected (2)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- //exception order testing
- try {
- Arrays.sort(new int[1], startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
- }
-
- /**
- * @tests java.util.Arrays#sort(long[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {long[].class}
- )
- public void test_sort$J() {
- // Test for method void java.util.Arrays.sort(long [])
- long[] reversedArray = new long[arraySize];
- for (int counter = 0; counter < arraySize; counter++)
- reversedArray[counter] = (long) (arraySize - counter - 1);
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue("Resulting array not sorted",
- reversedArray[counter] == (long) counter);
-
- }
-
- /**
- * @tests java.util.Arrays#sort(long[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {long[].class, int.class, int.class}
- )
- public void test_sort$JII() {
- // Test for method void java.util.Arrays.sort(long [], int, int)
- int startIndex = arraySize / 4;
- int endIndex = 3 * arraySize / 4;
- long[] reversedArray = new long[arraySize];
- long[] originalReversedArray = new long[arraySize];
- for (int counter = 0; counter < arraySize; counter++) {
- reversedArray[counter] = (long) (arraySize - counter - 1);
- originalReversedArray[counter] = reversedArray[counter];
- }
- Arrays.sort(reversedArray, startIndex, endIndex);
- for (int counter = 0; counter < startIndex; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
- for (int counter = startIndex; counter < endIndex - 1; counter++)
- assertTrue("Array not sorted within bounds",
- reversedArray[counter] <= reversedArray[counter + 1]);
- for (int counter = endIndex; counter < arraySize; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
-
- //exception testing
- try {
- Arrays.sort(reversedArray, startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, -1, startIndex);
- fail("ArrayIndexOutOfBoundsException expected (1)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, startIndex, reversedArray.length + 1);
- fail("ArrayIndexOutOfBoundsException expected (2)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- //exception order testing
- try {
- Arrays.sort(new long[1], startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
- }
-
- /**
- * @tests java.util.Arrays#sort(java.lang.Object[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {java.lang.Object[].class}
- )
- public void test_sort$Ljava_lang_Object() {
- // Test for method void java.util.Arrays.sort(java.lang.Object [])
- Object[] reversedArray = new Object[arraySize];
- for (int counter = 0; counter < arraySize; counter++)
- reversedArray[counter] = objectArray[arraySize - counter - 1];
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue("Resulting array not sorted",
- reversedArray[counter] == objectArray[counter]);
-
- Arrays.fill(reversedArray, 0, reversedArray.length/2, "String");
- Arrays.fill(reversedArray, reversedArray.length/2, reversedArray.length, new Integer(1));
-
- try {
- Arrays.sort(reversedArray);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Arrays#sort(java.lang.Object[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {java.lang.Object[].class, int.class, int.class}
- )
- public void test_sort$Ljava_lang_ObjectII() {
- // Test for method void java.util.Arrays.sort(java.lang.Object [], int,
- // int)
- int startIndex = arraySize / 4;
- int endIndex = 3 * arraySize / 4;
- Object[] reversedArray = new Object[arraySize];
- Object[] originalReversedArray = new Object[arraySize];
- for (int counter = 0; counter < arraySize; counter++) {
- reversedArray[counter] = objectArray[arraySize - counter - 1];
- originalReversedArray[counter] = reversedArray[counter];
- }
- Arrays.sort(reversedArray, startIndex, endIndex);
- for (int counter = 0; counter < startIndex; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
- for (int counter = startIndex; counter < endIndex - 1; counter++)
- assertTrue("Array not sorted within bounds",
- ((Comparable) reversedArray[counter])
- .compareTo(reversedArray[counter + 1]) <= 0);
- for (int counter = endIndex; counter < arraySize; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
-
- //exception testing
- try {
- Arrays.sort(reversedArray, startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, -1, startIndex);
- fail("ArrayIndexOutOfBoundsException expected (1)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, startIndex, reversedArray.length + 1);
- fail("ArrayIndexOutOfBoundsException expected (2)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- //exception order testing
- try {
- Arrays.sort(new Object[1], startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
-
- Arrays.fill(reversedArray, 0, reversedArray.length/2, "String");
- Arrays.fill(reversedArray, reversedArray.length/2, reversedArray.length, new Integer(1));
-
- try {
- Arrays.sort(reversedArray, reversedArray.length/4, 3*reversedArray.length/4);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- Arrays.sort(reversedArray, 0, reversedArray.length/4);
- Arrays.sort(reversedArray, 3*reversedArray.length/4, reversedArray.length);
- }
-
- /**
- * @tests java.util.Arrays#sort(java.lang.Object[], int, int,
- * java.util.Comparator)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {java.lang.Object[].class, int.class, int.class, java.util.Comparator.class}
- )
- public void test_sort$Ljava_lang_ObjectIILjava_util_Comparator() {
- // Test for method void java.util.Arrays.sort(java.lang.Object [], int,
- // int, java.util.Comparator)
- int startIndex = arraySize / 4;
- int endIndex = 3 * arraySize / 4;
- ReversedIntegerComparator comp = new ReversedIntegerComparator();
- Object[] originalArray = new Object[arraySize];
- for (int counter = 0; counter < arraySize; counter++)
- originalArray[counter] = objectArray[counter];
- Arrays.sort(objectArray, startIndex, endIndex, comp);
- for (int counter = 0; counter < startIndex; counter++)
- assertTrue("Array modified outside of bounds",
- objectArray[counter] == originalArray[counter]);
- for (int counter = startIndex; counter < endIndex - 1; counter++)
- assertTrue("Array not sorted within bounds", comp.compare(
- objectArray[counter], objectArray[counter + 1]) <= 0);
- for (int counter = endIndex; counter < arraySize; counter++)
- assertTrue("Array modified outside of bounds",
- objectArray[counter] == originalArray[counter]);
-
- Arrays.fill(originalArray, 0, originalArray.length/2, "String");
- Arrays.fill(originalArray, originalArray.length/2, originalArray.length, new Integer(1));
-
- try {
- Arrays.sort(originalArray, startIndex, endIndex, comp);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- Arrays.sort(originalArray, endIndex, originalArray.length, comp);
-
- try {
- Arrays.sort(originalArray, endIndex, originalArray.length + 1, comp);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.sort(originalArray, -1, startIndex, comp);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- Arrays.sort(originalArray, originalArray.length, endIndex, comp);
- fail("IllegalArgumentException expected");
- } catch(IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Arrays#sort(java.lang.Object[], java.util.Comparator)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {java.lang.Object[].class, java.util.Comparator.class}
- )
- public void test_sort$Ljava_lang_ObjectLjava_util_Comparator() {
- // Test for method void java.util.Arrays.sort(java.lang.Object [],
- // java.util.Comparator)
- ReversedIntegerComparator comp = new ReversedIntegerComparator();
- Arrays.sort(objectArray, comp);
- for (int counter = 0; counter < arraySize - 1; counter++)
- assertTrue("Array not sorted correctly with custom comparator",
- comp
- .compare(objectArray[counter],
- objectArray[counter + 1]) <= 0);
-
- Arrays.fill(objectArray, 0, objectArray.length/2, "String");
- Arrays.fill(objectArray, objectArray.length/2, objectArray.length, new Integer(1));
-
- try {
- Arrays.sort(objectArray, comp);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Arrays#sort(short[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {short[].class}
- )
- public void test_sort$S() {
- // Test for method void java.util.Arrays.sort(short [])
- short[] reversedArray = new short[arraySize];
- for (int counter = 0; counter < arraySize; counter++)
- reversedArray[counter] = (short) (arraySize - counter - 1);
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < arraySize; counter++)
- assertTrue("Resulting array not sorted",
- reversedArray[counter] == (short) counter);
- }
-
- /**
- * @tests java.util.Arrays#sort(short[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {short[].class, int.class, int.class}
- )
- public void test_sort$SII() {
- // Test for method void java.util.Arrays.sort(short [], int, int)
- int startIndex = arraySize / 4;
- int endIndex = 3 * arraySize / 4;
- short[] reversedArray = new short[arraySize];
- short[] originalReversedArray = new short[arraySize];
- for (int counter = 0; counter < arraySize; counter++) {
- reversedArray[counter] = (short) (arraySize - counter - 1);
- originalReversedArray[counter] = reversedArray[counter];
- }
- Arrays.sort(reversedArray, startIndex, endIndex);
- for (int counter = 0; counter < startIndex; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
- for (int counter = startIndex; counter < endIndex - 1; counter++)
- assertTrue("Array not sorted within bounds",
- reversedArray[counter] <= reversedArray[counter + 1]);
- for (int counter = endIndex; counter < arraySize; counter++)
- assertTrue("Array modified outside of bounds",
- reversedArray[counter] == originalReversedArray[counter]);
-
- //exception testing
- try {
- Arrays.sort(reversedArray, startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, -1, startIndex);
- fail("ArrayIndexOutOfBoundsException expected (1)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- try {
- Arrays.sort(reversedArray, startIndex, reversedArray.length + 1);
- fail("ArrayIndexOutOfBoundsException expected (2)");
- } catch (ArrayIndexOutOfBoundsException ignore) {
- }
-
- //exception order testing
- try {
- Arrays.sort(new short[1], startIndex + 1, startIndex);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ignore) {
- }
- }
-
- /**
- * @tests java.util.Arrays#sort(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "sort",
- args = {byte[].class, int.class, int.class}
- )
- public void test_java_util_Arrays_sort_byte_array_NPE() {
- byte[] byte_array_null = null;
- try {
- java.util.Arrays.sort(byte_array_null);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- // Regression for HARMONY-378
- java.util.Arrays.sort(byte_array_null, (int) -1, (int) 1);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.util.Arrays#sort(char[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "sort",
- args = {char[].class, int.class, int.class}
- )
- public void test_java_util_Arrays_sort_char_array_NPE() {
- char[] char_array_null = null;
- try {
- java.util.Arrays.sort(char_array_null);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- // Regression for HARMONY-378
- java.util.Arrays.sort(char_array_null, (int) -1, (int) 1);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.util.Arrays#sort(double[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "sort",
- args = {double[].class, int.class, int.class}
- )
- public void test_java_util_Arrays_sort_double_array_NPE() {
- double[] double_array_null = null;
- try {
- java.util.Arrays.sort(double_array_null);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- // Regression for HARMONY-378
- java.util.Arrays.sort(double_array_null, (int) -1, (int) 1);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.util.Arrays#sort(float[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "sort",
- args = {float[].class, int.class, int.class}
- )
- public void test_java_util_Arrays_sort_float_array_NPE() {
- float[] float_array_null = null;
- try {
- java.util.Arrays.sort(float_array_null);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- // Regression for HARMONY-378
- java.util.Arrays.sort(float_array_null, (int) -1, (int) 1);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.util.Arrays#sort(int[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "sort",
- args = {int[].class, int.class, int.class}
- )
- public void test_java_util_Arrays_sort_int_array_NPE() {
- int[] int_array_null = null;
- try {
- java.util.Arrays.sort(int_array_null);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- // Regression for HARMONY-378
- java.util.Arrays.sort(int_array_null, (int) -1, (int) 1);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.util.Arrays#sort(Object[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "sort",
- args = {java.lang.Object[].class, int.class, int.class}
- )
- public void test_java_util_Arrays_sort_object_array_NPE() {
- Object[] object_array_null = null;
- try {
- java.util.Arrays.sort(object_array_null);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- // Regression for HARMONY-378
- java.util.Arrays.sort(object_array_null, (int) -1, (int) 1);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- // Regression for HARMONY-378
- java.util.Arrays.sort(object_array_null, (int) -1, (int) 1, null);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.util.Arrays#sort(long[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "sort",
- args = {long[].class, int.class, int.class}
- )
- public void test_java_util_Arrays_sort_long_array_NPE() {
- long[] long_array_null = null;
- try {
- java.util.Arrays.sort(long_array_null);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- // Regression for HARMONY-378
- java.util.Arrays.sort(long_array_null, (int) -1, (int) 1);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.util.Arrays#sort(short[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "sort",
- args = {short[].class, int.class, int.class}
- )
- public void test_java_util_Arrays_sort_short_array_NPE() {
- short[] short_array_null = null;
- try {
- java.util.Arrays.sort(short_array_null);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- try {
- // Regression for HARMONY-378
- java.util.Arrays.sort(short_array_null, (int) -1, (int) 1);
- fail("Should throw java.lang.NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.util.Arrays#deepEquals(Object[], Object[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "deepEquals",
- args = {java.lang.Object[].class, java.lang.Object[].class}
- )
- public void test_deepEquals$Ljava_lang_ObjectLjava_lang_Object() {
- int [] a1 = {1, 2, 3};
- short [] a2 = {0, 1};
- Object [] a3 = {new Integer(1), a2};
- int [] a4 = {6, 5, 4};
-
- int [] b1 = {1, 2, 3};
- short [] b2 = {0, 1};
- Object [] b3 = {new Integer(1), b2};
-
- Object a [] = {a1, a2, a3};
- Object b [] = {b1, b2, b3};
-
- assertFalse(Arrays.equals(a, b));
- assertTrue(Arrays.deepEquals(a,b));
-
- a[2] = a4;
-
- assertFalse(Arrays.deepEquals(a, b));
- }
-
- /**
- * @tests java.util.Arrays#deepHashCode(Object[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "deepHashCode",
- args = {java.lang.Object[].class}
- )
- public void test_deepHashCode$Ljava_lang_Object() {
- int [] a1 = {1, 2, 3};
- short [] a2 = {0, 1};
- Object [] a3 = {new Integer(1), a2};
-
- int [] b1 = {1, 2, 3};
- short [] b2 = {0, 1};
- Object [] b3 = {new Integer(1), b2};
-
- Object a [] = {a1, a2, a3};
- Object b [] = {b1, b2, b3};
-
- int deep_hash_a = Arrays.deepHashCode(a);
- int deep_hash_b = Arrays.deepHashCode(b);
-
- assertEquals(deep_hash_a, deep_hash_b);
- }
-
- /**
- * @tests java.util.Arrays#hashCode(boolean[] a)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {boolean[].class}
- )
- public void test_hashCode$LZ() {
- int listHashCode;
- int arrayHashCode;
-
- boolean [] boolArr = {true, false, false, true, false};
- List listOfBoolean = new LinkedList();
- for (int i = 0; i < boolArr.length; i++) {
- listOfBoolean.add(new Boolean(boolArr[i]));
- }
- listHashCode = listOfBoolean.hashCode();
- arrayHashCode = Arrays.hashCode(boolArr);
- assertEquals(listHashCode, arrayHashCode);
- }
-
- /**
- * @tests java.util.Arrays#hashCode(int[] a)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {int[].class}
- )
- public void test_hashCode$LI() {
- int listHashCode;
- int arrayHashCode;
-
- int [] intArr = {10, 5, 134, 7, 19};
- List listOfInteger = new LinkedList();
-
- for (int i = 0; i < intArr.length; i++) {
- listOfInteger.add(new Integer(intArr[i]));
- }
- listHashCode = listOfInteger.hashCode();
- arrayHashCode = Arrays.hashCode(intArr);
- assertEquals(listHashCode, arrayHashCode);
-
- int [] intArr2 = {10, 5, 134, 7, 19};
- assertEquals(Arrays.hashCode(intArr2), Arrays.hashCode(intArr));
- }
-
- /**
- * @tests java.util.Arrays#hashCode(char[] a)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {char[].class}
- )
- public void test_hashCode$LC() {
- int listHashCode;
- int arrayHashCode;
-
- char [] charArr = {'a', 'g', 'x', 'c', 'm'};
- List listOfCharacter = new LinkedList();
- for (int i = 0; i < charArr.length; i++) {
- listOfCharacter.add(new Character(charArr[i]));
- }
- listHashCode = listOfCharacter.hashCode();
- arrayHashCode = Arrays.hashCode(charArr);
- assertEquals(listHashCode, arrayHashCode);
- }
-
- /**
- * @tests java.util.Arrays#hashCode(byte[] a)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {byte[].class}
- )
- public void test_hashCode$LB() {
- int listHashCode;
- int arrayHashCode;
-
- byte [] byteArr = {5, 9, 7, 6, 17};
- List listOfByte = new LinkedList();
- for (int i = 0; i < byteArr.length; i++) {
- listOfByte.add(new Byte(byteArr[i]));
- }
- listHashCode = listOfByte.hashCode();
- arrayHashCode = Arrays.hashCode(byteArr);
- assertEquals(listHashCode, arrayHashCode);
- }
-
- /**
- * @tests java.util.Arrays#hashCode(long[] a)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {long[].class}
- )
- public void test_hashCode$LJ() {
- int listHashCode;
- int arrayHashCode;
-
- long [] longArr = {67890234512l, 97587236923425l, 257421912912l,
- 6754268100l, 5};
- List listOfLong = new LinkedList();
- for (int i = 0; i < longArr.length; i++) {
- listOfLong.add(new Long(longArr[i]));
- }
- listHashCode = listOfLong.hashCode();
- arrayHashCode = Arrays.hashCode(longArr);
- assertEquals(listHashCode, arrayHashCode);
- }
-
- /**
- * @tests java.util.Arrays#hashCode(float[] a)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {float[].class}
- )
- public void test_hashCode$LF() {
- int listHashCode;
- int arrayHashCode;
-
- float [] floatArr = {0.13497f, 0.268934f, 12e-5f, -3e+2f, 10e-4f};
- List listOfFloat = new LinkedList();
- for (int i = 0; i < floatArr.length; i++) {
- listOfFloat.add(new Float(floatArr[i]));
- }
- listHashCode = listOfFloat.hashCode();
- arrayHashCode = Arrays.hashCode(floatArr);
- assertEquals(listHashCode, arrayHashCode);
-
- float [] floatArr2 = {0.13497f, 0.268934f, 12e-5f, -3e+2f, 10e-4f};
- assertEquals(Arrays.hashCode(floatArr2), Arrays.hashCode(floatArr));
- }
-
- /**
- * @tests java.util.Arrays#hashCode(double[] a)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {double[].class}
- )
- public void test_hashCode$LD() {
- int listHashCode;
- int arrayHashCode;
-
- double [] doubleArr = {0.134945657, 0.0038754, 11e-150, -30e-300, 10e-4};
- List listOfDouble = new LinkedList();
- for (int i = 0; i < doubleArr.length; i++) {
- listOfDouble.add(new Double(doubleArr[i]));
- }
- listHashCode = listOfDouble.hashCode();
- arrayHashCode = Arrays.hashCode(doubleArr);
- assertEquals(listHashCode, arrayHashCode);
- }
-
- /**
- * @tests java.util.Arrays#hashCode(short[] a)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {short[].class}
- )
- public void test_hashCode$LS() {
- int listHashCode;
- int arrayHashCode;
-
- short [] shortArr = {35, 13, 45, 2, 91};
- List listOfShort = new LinkedList();
- for (int i = 0; i < shortArr.length; i++) {
- listOfShort.add(new Short(shortArr[i]));
- }
- listHashCode = listOfShort.hashCode();
- arrayHashCode = Arrays.hashCode(shortArr);
- assertEquals(listHashCode, arrayHashCode);
- }
-
- /**
- * @tests java.util.Arrays#hashCode(Object[] a)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {java.lang.Object[].class}
- )
- public void test_hashCode$Ljava_lang_Object() {
- int listHashCode;
- int arrayHashCode;
-
- Object[] objectArr = {new Integer(1), new Float(10e-12f), null};
- List listOfObject= new LinkedList();
- for (int i = 0; i < objectArr.length; i++) {
- listOfObject.add(objectArr[i]);
- }
- listHashCode = listOfObject.hashCode();
- arrayHashCode = Arrays.hashCode(objectArr);
- assertEquals(listHashCode, arrayHashCode);
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- booleanArray = new boolean[arraySize];
- byteArray = new byte[arraySize];
- charArray = new char[arraySize];
- doubleArray = new double[arraySize];
- floatArray = new float[arraySize];
- intArray = new int[arraySize];
- longArray = new long[arraySize];
- objectArray = new Object[arraySize];
- shortArray = new short[arraySize];
-
- for (int counter = 0; counter < arraySize; counter++) {
- byteArray[counter] = (byte) counter;
- charArray[counter] = (char) (counter + 1);
- doubleArray[counter] = counter;
- floatArray[counter] = counter;
- intArray[counter] = counter;
- longArray[counter] = counter;
- objectArray[counter] = objArray[counter];
- shortArray[counter] = (short) counter;
- }
- for (int counter = 0; counter < arraySize; counter += 2) {
- booleanArray[counter] = false;
- booleanArray[counter + 1] = true;
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/BitSetTest.java b/luni/src/test/java/tests/api/java/util/BitSetTest.java
deleted file mode 100644
index c0e6f2a..0000000
--- a/luni/src/test/java/tests/api/java/util/BitSetTest.java
+++ /dev/null
@@ -1,1564 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.BitSet;
-
-@TestTargetClass(BitSet.class)
-public class BitSetTest extends junit.framework.TestCase {
-
- BitSet eightbs;
-
- /**
- * @tests java.util.BitSet#BitSet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "BitSet",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.BitSet()
- BitSet bs = new BitSet();
- // Default size for a BitSet should be 64 elements;
-
- assertEquals("Created BitSet of incorrect size", 64, bs.size());
- assertEquals("New BitSet had invalid string representation", "{}", bs
- .toString());
- }
-
- /**
- * @tests java.util.BitSet#BitSet(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "BitSet",
- args = {int.class}
- )
- public void test_ConstructorI() {
- // Test for method java.util.BitSet(int)
- BitSet bs = new BitSet(128);
- // Default size for a BitSet should be 64 elements;
-
- assertEquals("Created BitSet of incorrect size", 128, bs.size());
- assertTrue("New BitSet had invalid string representation: "
- + bs.toString(), bs.toString().equals("{}"));
-
- // All BitSets are created with elements of multiples of 64
-
- bs = new BitSet(89);
- assertEquals("Failed to round BitSet element size", 128, bs.size());
-
- try {
- bs = new BitSet(-9);
- fail(
- "Failed to throw exception when creating a new BitSet with negative elements value");
- } catch (NegativeArraySizeException e) {
- // Correct behaviour
- }
- }
-
- /**
- * @tests java.util.BitSet#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- // Test for method java.lang.Object java.util.BitSet.clone()
- BitSet bs;
- bs = (BitSet) eightbs.clone();
- assertTrue("Clone failed to return equal BitSet", eightbs.equals(bs));
-
- }
-
- /**
- * @tests java.util.BitSet#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean java.util.BitSet.equals(java.lang.Object)
- BitSet bs;
-
- bs = (BitSet) eightbs.clone();
- assertTrue("Same BitSet returned false", eightbs.equals(eightbs));
- assertTrue("Identical BitSets returned false", eightbs.equals(bs));
- bs.clear(6);
- assertTrue("Different BitSets returned true", !eightbs.equals(bs));
- // Grow the BitSet
- bs = (BitSet) eightbs.clone();
- bs.set(128);
- assertTrue("Different sized BitSet with higher bit set returned true",
- !eightbs.equals(bs));
- bs.clear(128);
- assertTrue(
- "Different sized BitSet with higher bits not set returned false",
- eightbs.equals(bs));
- }
-
- /**
- * @tests java.util.BitSet#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- // Test for method int java.util.BitSet.hashCode()
- BitSet bs = (BitSet) eightbs.clone();
- bs.clear(2);
- bs.clear(6);
- assertTrue("BitSet returns wrong hash value: " + bs.hashCode(), bs
- .hashCode() == 1129);
- bs.set(10);
- bs.clear(3);
- assertTrue("BitSet returns wrong hash value: " + bs.hashCode(), bs
- .hashCode() == 97);
- }
-
- /**
- * @tests java.util.BitSet#clear()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- eightbs.clear();
- for (int i = 0; i < 8; i++)
- assertTrue("Clear didn't clear bit " + i, !eightbs.get(i));
- assertEquals("Test1: Wrong length", 0, eightbs.length());
-
- BitSet bs = new BitSet(3400);
- bs.set(0, bs.size() - 1); // ensure all bits are 1's
- bs.set(bs.size() - 1);
- bs.clear();
- assertEquals("Test2: Wrong length", 0, bs.length());
- assertTrue("Test2: isEmpty() returned incorrect value", bs
- .isEmpty());
- assertEquals("Test2: cardinality() returned incorrect value", 0, bs
- .cardinality());
- }
-
- /**
- * @tests java.util.BitSet#clear(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {int.class}
- )
- public void test_clearI() {
- // Test for method void java.util.BitSet.clear(int)
-
- eightbs.clear(7);
- assertTrue("Failed to clear bit", !eightbs.get(7));
-
- // Check to see all other bits are still set
- for (int i = 0; i < 7; i++)
- assertTrue("Clear cleared incorrect bits", eightbs.get(i));
-
- eightbs.clear(165);
- assertTrue("Failed to clear bit", !eightbs.get(165));
- // Try out of range
- try {
- eightbs.clear(-1);
- fail("Failed to throw expected out of bounds exception");
- } catch (IndexOutOfBoundsException e) {
- // Correct behaviour
- }
-
- BitSet bs = new BitSet(0);
- assertTrue("Test1: Wrong length, " + bs.size(), bs.length() == 0);
- bs.clear(0);
- assertTrue("Test2: Wrong length" + bs.size(), bs.length() == 0);
- }
-
- /**
- * @tests java.util.BitSet#clear(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {int.class, int.class}
- )
- public void test_clearII() {
- // Test for method void java.util.BitSet.clear(int, int)
- // pos1 and pos2 are in the same bitset element
- BitSet bs = new BitSet(16);
- int initialSize = bs.size();
- bs.set(0, initialSize);
- bs.clear(5);
- bs.clear(15);
- bs.clear(7, 11);
- for (int i = 0; i < 7; i++) {
- if (i == 5)
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- else
- assertTrue("Shouldn't have cleared bit " + i, bs.get(i));
- }
- for (int i = 7; i < 11; i++)
- assertTrue("Failed to clear bit " + i, !bs.get(i));
-
- for (int i = 11; i < initialSize; i++) {
- if (i == 15)
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- else
- assertTrue("Shouldn't have cleared bit " + i, bs.get(i));
- }
-
- for (int i = initialSize; i < bs.size(); i++) {
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- }
-
- // pos1 and pos2 is in the same bitset element, boundary testing
- bs = new BitSet(16);
- initialSize = bs.size();
- bs.set(0, initialSize);
- bs.clear(7, 64);
- assertEquals("Failed to grow BitSet", 128, bs.size());
- for (int i = 0; i < 7; i++)
- assertTrue("Shouldn't have cleared bit " + i, bs.get(i));
- for (int i = 7; i < 64; i++)
- assertTrue("Failed to clear bit " + i, !bs.get(i));
- for (int i = 64; i < bs.size(); i++) {
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- }
- // more boundary testing
- bs = new BitSet(32);
- initialSize = bs.size();
- bs.set(0, initialSize);
- bs.clear(0, 64);
- for (int i = 0; i < 64; i++)
- assertTrue("Failed to clear bit " + i, !bs.get(i));
- for (int i = 64; i < bs.size(); i++) {
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- }
-
- bs = new BitSet(32);
- initialSize = bs.size();
- bs.set(0, initialSize);
- bs.clear(0, 65);
- for (int i = 0; i < 65; i++)
- assertTrue("Failed to clear bit " + i, !bs.get(i));
- for (int i = 65; i < bs.size(); i++) {
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- }
-
- // pos1 and pos2 are in two sequential bitset elements
- bs = new BitSet(128);
- initialSize = bs.size();
- bs.set(0, initialSize);
- bs.clear(7);
- bs.clear(110);
- bs.clear(9, 74);
- for (int i = 0; i < 9; i++) {
- if (i == 7)
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- else
- assertTrue("Shouldn't have cleared bit " + i, bs.get(i));
- }
- for (int i = 9; i < 74; i++)
- assertTrue("Failed to clear bit " + i, !bs.get(i));
- for (int i = 74; i < initialSize; i++) {
- if (i == 110)
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- else
- assertTrue("Shouldn't have cleared bit " + i, bs.get(i));
- }
- for (int i = initialSize; i < bs.size(); i++) {
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- }
-
- // pos1 and pos2 are in two non-sequential bitset elements
- bs = new BitSet(256);
- bs.set(0, 256);
- bs.clear(7);
- bs.clear(255);
- bs.clear(9, 219);
- for (int i = 0; i < 9; i++) {
- if (i == 7)
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- else
- assertTrue("Shouldn't have cleared bit " + i, bs.get(i));
- }
-
- for (int i = 9; i < 219; i++)
- assertTrue("failed to clear bit " + i, !bs.get(i));
-
- for (int i = 219; i < 255; i++)
- assertTrue("Shouldn't have cleared bit " + i, bs.get(i));
-
- for (int i = 255; i < bs.size(); i++)
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
-
- // test illegal args
- bs = new BitSet(10);
- try {
- bs.clear(-1, 3);
- fail(
- "Test1: Attempt to flip with negative index failed to generate exception");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- bs.clear(2, -1);
- fail(
- "Test2: Attempt to flip with negative index failed to generate exception");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- bs.clear(4, 2);
- fail(
- "Test4: Attempt to flip with illegal args failed to generate exception");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * @tests java.util.BitSet#get(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {int.class}
- )
- public void test_getI() {
- // Test for method boolean java.util.BitSet.get(int)
-
- BitSet bs = new BitSet();
- bs.set(8);
- assertTrue("Get returned true for index out of range", !eightbs.get(99));
- assertTrue("Get returned false for set value", eightbs.get(3));
- assertTrue("Get returned true for a non set value", !bs.get(0));
-
- try {
- bs.get(-1);
- fail(
- "Attempt to get at negative index failed to generate exception");
- } catch (IndexOutOfBoundsException e) {
- // Correct behaviour
- }
-
- bs = new BitSet(1);
- assertTrue("Access greater than size", !bs.get(64));
-
- bs = new BitSet();
- bs.set(63);
- assertTrue("Test highest bit", bs.get(63));
- }
-
- /**
- * @tests java.util.BitSet#get(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {int.class, int.class}
- )
- public void test_getII() {
- // Test for method boolean java.util.BitSet.get(int, int)
- BitSet bs, resultbs, correctbs;
- bs = new BitSet(512);
- bs.set(3, 9);
- bs.set(10, 20);
- bs.set(60, 75);
- bs.set(121);
- bs.set(130, 140);
-
- // pos1 and pos2 are in the same bitset element, at index0
- resultbs = bs.get(3, 6);
- correctbs = new BitSet(3);
- correctbs.set(0, 3);
- assertTrue("Test1: Returned incorrect BitSet", resultbs
- .equals(correctbs));
-
- // pos1 and pos2 are in the same bitset element, at index 1
- resultbs = bs.get(100, 125);
- correctbs = new BitSet(25);
- correctbs.set(21);
- assertTrue("Test2: Returned incorrect BitSet", resultbs
- .equals(correctbs));
-
- // pos1 in bitset element at index 0, and pos2 in bitset element at
- // index 1
- resultbs = bs.get(15, 125);
- correctbs = new BitSet(25);
- correctbs.set(0, 5);
- correctbs.set(45, 60);
- correctbs.set(121 - 15);
- assertTrue("Test3: Returned incorrect BitSet", resultbs
- .equals(correctbs));
-
- // pos1 in bitset element at index 1, and pos2 in bitset element at
- // index 2
- resultbs = bs.get(70, 145);
- correctbs = new BitSet(75);
- correctbs.set(0, 5);
- correctbs.set(51);
- correctbs.set(60, 70);
- assertTrue("Test4: Returned incorrect BitSet", resultbs
- .equals(correctbs));
-
- // pos1 in bitset element at index 0, and pos2 in bitset element at
- // index 2
- resultbs = bs.get(5, 145);
- correctbs = new BitSet(140);
- correctbs.set(0, 4);
- correctbs.set(5, 15);
- correctbs.set(55, 70);
- correctbs.set(116);
- correctbs.set(125, 135);
- assertTrue("Test5: Returned incorrect BitSet", resultbs
- .equals(correctbs));
-
- // pos1 in bitset element at index 0, and pos2 in bitset element at
- // index 3
- resultbs = bs.get(5, 250);
- correctbs = new BitSet(200);
- correctbs.set(0, 4);
- correctbs.set(5, 15);
- correctbs.set(55, 70);
- correctbs.set(116);
- correctbs.set(125, 135);
- assertTrue("Test6: Returned incorrect BitSet", resultbs
- .equals(correctbs));
-
- assertTrue("equality principle", bs.equals(bs.get(0, bs.size())));
-
- // more tests
- BitSet bs2 = new BitSet(129);
- bs2.set(0, 20);
- bs2.set(62, 65);
- bs2.set(121, 123);
- resultbs = bs2.get(1, 124);
- correctbs = new BitSet(129);
- correctbs.set(0, 19);
- correctbs.set(61, 64);
- correctbs.set(120, 122);
- assertTrue("Test6: Returned incorrect BitSet", resultbs
- .equals(correctbs));
-
- // equality principle with some boundary conditions
- bs2 = new BitSet(128);
- bs2.set(2, 20);
- bs2.set(62);
- bs2.set(121, 123);
- bs2.set(127);
- resultbs = bs2.get(0, bs2.size());
- assertTrue("equality principle", bs2.equals(resultbs));
-
- bs2 = new BitSet(128);
- bs2.set(2, 20);
- bs2.set(62);
- bs2.set(121, 123);
- bs2.set(127);
- bs2.flip(0, 128);
- resultbs = bs2.get(0, bs.size());
- assertTrue("equality principle", bs2.equals(resultbs));
-
- try {
- bs2.get(-1, 0);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- bs2.get(bs2.size()/2, 0);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- bs2.get(bs2.size()/2, -1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.BitSet#set(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "set",
- args = {int.class}
- )
- public void test_setI() {
- // Test for method void java.util.BitSet.set(int)
-
- BitSet bs = new BitSet();
- bs.set(8);
- assertTrue("Failed to set bit", bs.get(8));
-
- try {
- bs.set(-1);
- fail(
- "Attempt to set at negative index failed to generate exception");
- } catch (IndexOutOfBoundsException e) {
- // Correct behaviour
- }
-
- // Try setting a bit on a 64 boundary
- bs.set(128);
- assertEquals("Failed to grow BitSet", 192, bs.size());
- assertTrue("Failed to set bit", bs.get(128));
-
- bs = new BitSet(64);
- for (int i = bs.size(); --i >= 0;) {
- bs.set(i);
- assertTrue("Incorrectly set", bs.get(i));
- assertTrue("Incorrect length", bs.length() == (i + 1));
- for (int j = bs.size(); --j > i;)
- assertTrue("Incorrectly set bit " + j, !bs.get(j));
- for (int j = i; --j >= 0;)
- assertTrue("Incorrectly set bit " + j, !bs.get(j));
- bs.clear(i);
- }
-
- bs = new BitSet(0);
- assertTrue("Test1: Wrong length, " + bs.size(), bs.length() == 0);
- bs.set(0);
- assertTrue("Test2: Wrong length" + bs.size(), bs.length() == 1);
- }
-
- /**
- * @tests java.util.BitSet#set(int, boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "set",
- args = {int.class, boolean.class}
- )
- public void test_setIZ() {
- // Test for method void java.util.BitSet.set(int, boolean)
- eightbs.set(5, false);
- assertTrue("Should have set bit 5 to true", !eightbs.get(5));
-
- eightbs.set(5, true);
- assertTrue("Should have set bit 5 to false", eightbs.get(5));
-
- try {
- eightbs.set(-5, false);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.BitSet#set(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "set",
- args = {int.class, int.class}
- )
- public void test_setII() {
- // Test for method void java.util.BitSet.set(int, int)
- // pos1 and pos2 are in the same bitset element
- BitSet bs = new BitSet(16);
- bs.set(5);
- bs.set(15);
- bs.set(7, 11);
- for (int i = 0; i < 7; i++) {
- if (i == 5)
- assertTrue("Shouldn't have flipped bit " + i, bs.get(i));
- else
- assertTrue("Shouldn't have set bit " + i, !bs.get(i));
- }
- for (int i = 7; i < 11; i++)
- assertTrue("Failed to set bit " + i, bs.get(i));
- for (int i = 11; i < bs.size(); i++) {
- if (i == 15)
- assertTrue("Shouldn't have flipped bit " + i, bs.get(i));
- else
- assertTrue("Shouldn't have set bit " + i, !bs.get(i));
- }
-
- // pos1 and pos2 is in the same bitset element, boundary testing
- bs = new BitSet(16);
- bs.set(7, 64);
- assertEquals("Failed to grow BitSet", 128, bs.size());
- for (int i = 0; i < 7; i++)
- assertTrue("Shouldn't have set bit " + i, !bs.get(i));
- for (int i = 7; i < 64; i++)
- assertTrue("Failed to set bit " + i, bs.get(i));
- assertTrue("Shouldn't have set bit 64", !bs.get(64));
-
- // more boundary testing
- bs = new BitSet(32);
- bs.set(0, 64);
- for (int i = 0; i < 64; i++)
- assertTrue("Failed to set bit " + i, bs.get(i));
- assertTrue("Shouldn't have set bit 64", !bs.get(64));
-
- bs = new BitSet(32);
- bs.set(0, 65);
- for (int i = 0; i < 65; i++)
- assertTrue("Failed to set bit " + i, bs.get(i));
- assertTrue("Shouldn't have set bit 65", !bs.get(65));
-
- // pos1 and pos2 are in two sequential bitset elements
- bs = new BitSet(128);
- bs.set(7);
- bs.set(110);
- bs.set(9, 74);
- for (int i = 0; i < 9; i++) {
- if (i == 7)
- assertTrue("Shouldn't have flipped bit " + i, bs.get(i));
- else
- assertTrue("Shouldn't have set bit " + i, !bs.get(i));
- }
- for (int i = 9; i < 74; i++)
- assertTrue("Failed to set bit " + i, bs.get(i));
- for (int i = 74; i < bs.size(); i++) {
- if (i == 110)
- assertTrue("Shouldn't have flipped bit " + i, bs.get(i));
- else
- assertTrue("Shouldn't have set bit " + i, !bs.get(i));
- }
-
- // pos1 and pos2 are in two non-sequential bitset elements
- bs = new BitSet(256);
- bs.set(7);
- bs.set(255);
- bs.set(9, 219);
- for (int i = 0; i < 9; i++) {
- if (i == 7)
- assertTrue("Shouldn't have set flipped " + i, bs.get(i));
- else
- assertTrue("Shouldn't have set bit " + i, !bs.get(i));
- }
-
- for (int i = 9; i < 219; i++)
- assertTrue("failed to set bit " + i, bs.get(i));
-
- for (int i = 219; i < 255; i++)
- assertTrue("Shouldn't have set bit " + i, !bs.get(i));
-
- assertTrue("Shouldn't have flipped bit 255", bs.get(255));
-
- // test illegal args
- bs = new BitSet(10);
- try {
- bs.set(-1, 3);
- fail(
- "Test1: Attempt to flip with negative index failed to generate exception");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- bs.set(2, -1);
- fail(
- "Test2: Attempt to flip with negative index failed to generate exception");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- bs.set(4, 2);
- fail(
- "Test4: Attempt to flip with illegal args failed to generate exception");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * @tests java.util.BitSet#set(int, int, boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "set",
- args = {int.class, int.class, boolean.class}
- )
- public void test_setIIZ() {
- // Test for method void java.util.BitSet.set(int, int, boolean)
- eightbs.set(3, 6, false);
- assertTrue("Should have set bits 3, 4, and 5 to false", !eightbs.get(3)
- && !eightbs.get(4) && !eightbs.get(5));
-
- eightbs.set(3, 6, true);
- assertTrue("Should have set bits 3, 4, and 5 to true", eightbs.get(3)
- && eightbs.get(4) && eightbs.get(5));
-
- try {
- eightbs.set(-3, 6, false);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- eightbs.set(3, -6, false);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- eightbs.set(6, 3, false);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.BitSet#flip(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "flip",
- args = {int.class}
- )
- public void test_flipI() {
- // Test for method void java.util.BitSet.flip(int)
- BitSet bs = new BitSet();
- bs.clear(8);
- bs.clear(9);
- bs.set(10);
- bs.flip(9);
- assertTrue("Failed to flip bit", !bs.get(8));
- assertTrue("Failed to flip bit", bs.get(9));
- assertTrue("Failed to flip bit", bs.get(10));
-
- bs.set(8);
- bs.set(9);
- bs.clear(10);
- bs.flip(9);
- assertTrue("Failed to flip bit", bs.get(8));
- assertTrue("Failed to flip bit", !bs.get(9));
- assertTrue("Failed to flip bit", !bs.get(10));
-
- try {
- bs.flip(-1);
- fail(
- "Attempt to flip at negative index failed to generate exception");
- } catch (IndexOutOfBoundsException e) {
- // Correct behaviour
- }
-
- // Try setting a bit on a 64 boundary
- bs.flip(128);
- assertEquals("Failed to grow BitSet", 192, bs.size());
- assertTrue("Failed to flip bit", bs.get(128));
-
- bs = new BitSet(64);
- for (int i = bs.size(); --i >= 0;) {
- bs.flip(i);
- assertTrue("Test1: Incorrectly flipped bit" + i, bs.get(i));
- assertTrue("Incorrect length", bs.length() == (i + 1));
- for (int j = bs.size(); --j > i;)
- assertTrue("Test2: Incorrectly flipped bit" + j, !bs.get(j));
- for (int j = i; --j >= 0;)
- assertTrue("Test3: Incorrectly flipped bit" + j, !bs.get(j));
- bs.flip(i);
- }
-
- BitSet bs0 = new BitSet(0);
- assertEquals("Test1: Wrong size", 0, bs0.size());
- assertEquals("Test1: Wrong length", 0, bs0.length());
-
- bs0.flip(0);
- assertEquals("Test2: Wrong size", 64, bs0.size());
- assertEquals("Test2: Wrong length", 1, bs0.length());
-
- bs0.flip(63);
- assertEquals("Test3: Wrong size", 64, bs0.size());
- assertEquals("Test3: Wrong length", 64, bs0.length());
-
- eightbs.flip(7);
- assertTrue("Failed to flip bit 7", !eightbs.get(7));
-
- // Check to see all other bits are still set
- for (int i = 0; i < 7; i++)
- assertTrue("Flip flipped incorrect bits", eightbs.get(i));
-
- eightbs.flip(127);
- assertTrue("Failed to flip bit 127", eightbs.get(127));
-
- eightbs.flip(127);
- assertTrue("Failed to flip bit 127", !eightbs.get(127));
- }
-
- /**
- * @tests java.util.BitSet#flip(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "flip",
- args = {int.class, int.class}
- )
- public void test_flipII() {
- // Test for method void java.util.BitSet.flip(int, int)
- // pos1 and pos2 are in the same bitset element
- BitSet bs = new BitSet(16);
- bs.set(7);
- bs.set(10);
- bs.flip(7, 11);
- for (int i = 0; i < 7; i++)
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- assertTrue("Failed to flip bit 7", !bs.get(7));
- assertTrue("Failed to flip bit 8", bs.get(8));
- assertTrue("Failed to flip bit 9", bs.get(9));
- assertTrue("Failed to flip bit 10", !bs.get(10));
- for (int i = 11; i < bs.size(); i++)
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
-
- // pos1 and pos2 is in the same bitset element, boundary testing
- bs = new BitSet(16);
- bs.set(7);
- bs.set(10);
- bs.flip(7, 64);
- assertEquals("Failed to grow BitSet", 128, bs.size());
- for (int i = 0; i < 7; i++)
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- assertTrue("Failed to flip bit 7", !bs.get(7));
- assertTrue("Failed to flip bit 8", bs.get(8));
- assertTrue("Failed to flip bit 9", bs.get(9));
- assertTrue("Failed to flip bit 10", !bs.get(10));
- for (int i = 11; i < 64; i++)
- assertTrue("failed to flip bit " + i, bs.get(i));
- assertTrue("Shouldn't have flipped bit 64", !bs.get(64));
-
- // more boundary testing
- bs = new BitSet(32);
- bs.flip(0, 64);
- for (int i = 0; i < 64; i++)
- assertTrue("Failed to flip bit " + i, bs.get(i));
- assertTrue("Shouldn't have flipped bit 64", !bs.get(64));
-
- bs = new BitSet(32);
- bs.flip(0, 65);
- for (int i = 0; i < 65; i++)
- assertTrue("Failed to flip bit " + i, bs.get(i));
- assertTrue("Shouldn't have flipped bit 65", !bs.get(65));
-
- // pos1 and pos2 are in two sequential bitset elements
- bs = new BitSet(128);
- bs.set(7);
- bs.set(10);
- bs.set(72);
- bs.set(110);
- bs.flip(9, 74);
- for (int i = 0; i < 7; i++)
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- assertTrue("Shouldn't have flipped bit 7", bs.get(7));
- assertTrue("Shouldn't have flipped bit 8", !bs.get(8));
- assertTrue("Failed to flip bit 9", bs.get(9));
- assertTrue("Failed to flip bit 10", !bs.get(10));
- for (int i = 11; i < 72; i++)
- assertTrue("failed to flip bit " + i, bs.get(i));
- assertTrue("Failed to flip bit 72", !bs.get(72));
- assertTrue("Failed to flip bit 73", bs.get(73));
- for (int i = 74; i < 110; i++)
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- assertTrue("Shouldn't have flipped bit 110", bs.get(110));
- for (int i = 111; i < bs.size(); i++)
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
-
- // pos1 and pos2 are in two non-sequential bitset elements
- bs = new BitSet(256);
- bs.set(7);
- bs.set(10);
- bs.set(72);
- bs.set(110);
- bs.set(181);
- bs.set(220);
- bs.flip(9, 219);
- for (int i = 0; i < 7; i++)
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
- assertTrue("Shouldn't have flipped bit 7", bs.get(7));
- assertTrue("Shouldn't have flipped bit 8", !bs.get(8));
- assertTrue("Failed to flip bit 9", bs.get(9));
- assertTrue("Failed to flip bit 10", !bs.get(10));
- for (int i = 11; i < 72; i++)
- assertTrue("failed to flip bit " + i, bs.get(i));
- assertTrue("Failed to flip bit 72", !bs.get(72));
- for (int i = 73; i < 110; i++)
- assertTrue("failed to flip bit " + i, bs.get(i));
- assertTrue("Failed to flip bit 110", !bs.get(110));
- for (int i = 111; i < 181; i++)
- assertTrue("failed to flip bit " + i, bs.get(i));
- assertTrue("Failed to flip bit 181", !bs.get(181));
- for (int i = 182; i < 219; i++)
- assertTrue("failed to flip bit " + i, bs.get(i));
- assertTrue("Shouldn't have flipped bit 219", !bs.get(219));
- assertTrue("Shouldn't have flipped bit 220", bs.get(220));
- for (int i = 221; i < bs.size(); i++)
- assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
-
- // test illegal args
- bs = new BitSet(10);
- try {
- bs.flip(-1, 3);
- fail(
- "Test1: Attempt to flip with negative index failed to generate exception");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- bs.flip(2, -1);
- fail(
- "Test2: Attempt to flip with negative index failed to generate exception");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- bs.flip(4, 2);
- fail(
- "Test4: Attempt to flip with illegal args failed to generate exception");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * @tests java.util.BitSet#set(int, int)
- * @tests java.util.BitSet#cardinality()
- * @tests java.util.BitSet#get(int)
- * @tests java.util.BitSet#flip(int, int)
- * @tests java.util.BitSet#clear(int,int)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "flip",
- args = {int.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "get",
- args = {int.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "set",
- args = {int.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "clear",
- args = {int.class, int.class}
- )
- })
- public void test_111478() {
- // BitSet shouldn't be modified by any of the operations below,
- // since the affected bits for these methods are defined as inclusive of
- // pos1, exclusive of pos2.
- try {
- eightbs.flip(0, 0);
- assertTrue("Bit got flipped incorrectly ", eightbs.get(0));
-
- BitSet bsnew = eightbs.get(2, 2);
- assertEquals("BitSet retrieved incorrectly ",
- 0, bsnew.cardinality());
-
- eightbs.set(10, 10);
- assertTrue("Bit got set incorrectly ", !eightbs.get(10));
-
- eightbs.clear(3, 3);
- assertTrue("Bit cleared incorrectly ", eightbs.get(3));
- } catch (IndexOutOfBoundsException e) {
- fail("Unexpected IndexOutOfBoundsException when pos1 ==pos2");
- }
- }
-
- /**
- * @tests java.util.BitSet#intersects(java.util.BitSet)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "intersects",
- args = {java.util.BitSet.class}
- )
- public void test_intersectsLjava_util_BitSet() {
- // Test for method boolean java.util.BitSet.intersects(java.util.BitSet)
- BitSet bs = new BitSet(500);
- bs.set(5);
- bs.set(63);
- bs.set(64);
- bs.set(71, 110);
- bs.set(127, 130);
- bs.set(192);
- bs.set(450);
-
- BitSet bs2 = new BitSet(8);
- assertFalse("Test1: intersects() returned incorrect value", bs
- .intersects(bs2));
- assertFalse("Test1: intersects() returned incorrect value", bs2
- .intersects(bs));
-
- bs2.set(4);
- assertFalse("Test2: intersects() returned incorrect value", bs
- .intersects(bs2));
- assertFalse("Test2: intersects() returned incorrect value", bs2
- .intersects(bs));
-
- bs2.clear();
- bs2.set(5);
- assertTrue("Test3: intersects() returned incorrect value", bs
- .intersects(bs2));
- assertTrue("Test3: intersects() returned incorrect value", bs2
- .intersects(bs));
-
- bs2.clear();
- bs2.set(63);
- assertTrue("Test4: intersects() returned incorrect value", bs
- .intersects(bs2));
- assertTrue("Test4: intersects() returned incorrect value", bs2
- .intersects(bs));
-
- bs2.clear();
- bs2.set(80);
- assertTrue("Test5: intersects() returned incorrect value", bs
- .intersects(bs2));
- assertTrue("Test5: intersects() returned incorrect value", bs2
- .intersects(bs));
-
- bs2.clear();
- bs2.set(127);
- assertTrue("Test6: intersects() returned incorrect value", bs
- .intersects(bs2));
- assertTrue("Test6: intersects() returned incorrect value", bs2
- .intersects(bs));
-
- bs2.clear();
- bs2.set(192);
- assertTrue("Test7: intersects() returned incorrect value", bs
- .intersects(bs2));
- assertTrue("Test7: intersects() returned incorrect value", bs2
- .intersects(bs));
-
- bs2.clear();
- bs2.set(450);
- assertTrue("Test8: intersects() returned incorrect value", bs
- .intersects(bs2));
- assertTrue("Test8: intersects() returned incorrect value", bs2
- .intersects(bs));
-
- bs2.clear();
- bs2.set(500);
- assertFalse("Test9: intersects() returned incorrect value", bs
- .intersects(bs2));
- assertFalse("Test9: intersects() returned incorrect value", bs2
- .intersects(bs));
- }
-
- /**
- * @tests java.util.BitSet#and(java.util.BitSet)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "and",
- args = {java.util.BitSet.class}
- )
- public void test_andLjava_util_BitSet() {
- // Test for method void java.util.BitSet.and(java.util.BitSet)
- BitSet bs = new BitSet(128);
- // Initialize the bottom half of the BitSet
-
- for (int i = 64; i < 128; i++)
- bs.set(i);
- eightbs.and(bs);
- assertTrue("AND failed to clear bits", !eightbs.equals(bs));
- eightbs.set(3);
- bs.set(3);
- eightbs.and(bs);
- assertTrue("AND failed to maintain set bits", bs.get(3));
- bs.and(eightbs);
- for (int i = 64; i < 128; i++)
- assertTrue("Failed to clear extra bits in the receiver BitSet", !bs
- .get(i));
- }
-
- /**
- * @tests java.util.BitSet#andNot(java.util.BitSet)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "andNot",
- args = {java.util.BitSet.class}
- )
- public void test_andNotLjava_util_BitSet() {
- BitSet bs = (BitSet) eightbs.clone();
- bs.clear(5);
- BitSet bs2 = new BitSet();
- bs2.set(2);
- bs2.set(3);
- bs.andNot(bs2);
- assertEquals("Incorrect bitset after andNot",
- "{0, 1, 4, 6, 7}", bs.toString());
-
- bs = new BitSet(0);
- bs.andNot(bs2);
- assertEquals("Incorrect size", 0, bs.size());
- }
-
- /**
- * @tests java.util.BitSet#or(java.util.BitSet)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "or",
- args = {java.util.BitSet.class}
- )
- public void test_orLjava_util_BitSet() {
- // Test for method void java.util.BitSet.or(java.util.BitSet)
- BitSet bs = new BitSet(128);
- bs.or(eightbs);
- for (int i = 0; i < 8; i++)
- assertTrue("OR failed to set bits", bs.get(i));
-
- bs = new BitSet(0);
- bs.or(eightbs);
- for (int i = 0; i < 8; i++)
- assertTrue("OR(0) failed to set bits", bs.get(i));
-
- eightbs.clear(5);
- bs = new BitSet(128);
- bs.or(eightbs);
- assertTrue("OR set a bit which should be off", !bs.get(5));
- }
-
- /**
- * @tests java.util.BitSet#xor(java.util.BitSet)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "xor",
- args = {java.util.BitSet.class}
- )
- public void test_xorLjava_util_BitSet() {
- // Test for method void java.util.BitSet.xor(java.util.BitSet)
-
- BitSet bs = (BitSet) eightbs.clone();
- bs.xor(eightbs);
- for (int i = 0; i < 8; i++)
- assertTrue("XOR failed to clear bits", !bs.get(i));
-
- bs.xor(eightbs);
- for (int i = 0; i < 8; i++)
- assertTrue("XOR failed to set bits", bs.get(i));
-
- bs = new BitSet(0);
- bs.xor(eightbs);
- for (int i = 0; i < 8; i++)
- assertTrue("XOR(0) failed to set bits", bs.get(i));
-
- bs = new BitSet();
- bs.set(63);
- assertEquals("Test highest bit", "{63}", bs.toString());
- }
-
- /**
- * @tests java.util.BitSet#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- public void test_size() {
- // Test for method int java.util.BitSet.size()
- assertEquals("Returned incorrect size", 64, eightbs.size());
- eightbs.set(129);
- assertTrue("Returned incorrect size", eightbs.size() >= 129);
-
- }
-
- /**
- * @tests java.util.BitSet#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.util.BitSet.toString()
- assertEquals("Returned incorrect string representation", "{0, 1, 2, 3, 4, 5, 6, 7}", eightbs
- .toString());
- eightbs.clear(2);
- assertEquals("Returned incorrect string representation", "{0, 1, 3, 4, 5, 6, 7}", eightbs
- .toString());
- }
-
- /**
- * @tests java.util.BitSet#length()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "length",
- args = {}
- )
- public void test_length() {
- BitSet bs = new BitSet();
- assertTrue("BitSet returned wrong length--wanted 0, got: "
- + bs.length(), bs.length() == 0);
- bs.set(5);
- assertTrue("BitSet returned wrong length--wanted 6, got: "
- + bs.length(), bs.length() == 6);
- bs.set(10);
- assertTrue("BitSet returned wrong length--wanted 11, got: "
- + bs.length(), bs.length() == 11);
- bs.set(432);
- assertTrue("BitSet returned wrong length--wanted 433, got: "
- + bs.length(), bs.length() == 433);
- bs.set(300);
- assertTrue("BitSet returned wrong length--wanted 433 (again), got: "
- + bs.length(), bs.length() == 433);
- }
-
- /**
- * @tests java.util.BitSet#nextSetBit(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextSetBit",
- args = {int.class}
- )
- public void test_nextSetBitI() {
- // Test for method int java.util.BitSet.nextSetBit()
- BitSet bs = new BitSet(500);
- bs.set(5);
- bs.set(32);
- bs.set(63);
- bs.set(64);
- bs.set(71, 110);
- bs.set(127, 130);
- bs.set(193);
- bs.set(450);
- try {
- bs.nextSetBit(-1);
- fail("Expected IndexOutOfBoundsException for negative index");
- } catch (IndexOutOfBoundsException e) {
- }
- assertEquals("nextSetBit() returned the wrong value", 5, bs
- .nextSetBit(0));
- assertEquals("nextSetBit() returned the wrong value", 5, bs
- .nextSetBit(5));
- assertEquals("nextSetBit() returned the wrong value", 32, bs
- .nextSetBit(6));
- assertEquals("nextSetBit() returned the wrong value", 32, bs
- .nextSetBit(32));
- assertEquals("nextSetBit() returned the wrong value", 63, bs
- .nextSetBit(33));
-
- // boundary tests
- assertEquals("nextSetBit() returned the wrong value", 63, bs
- .nextSetBit(63));
- assertEquals("nextSetBit() returned the wrong value", 64, bs
- .nextSetBit(64));
-
- // at bitset element 1
- assertEquals("nextSetBit() returned the wrong value", 71, bs
- .nextSetBit(65));
- assertEquals("nextSetBit() returned the wrong value", 71, bs
- .nextSetBit(71));
- assertEquals("nextSetBit() returned the wrong value", 72, bs
- .nextSetBit(72));
- assertEquals("nextSetBit() returned the wrong value", 127, bs
- .nextSetBit(110));
-
- // boundary tests
- assertEquals("nextSetBit() returned the wrong value", 127, bs
- .nextSetBit(127));
- assertEquals("nextSetBit() returned the wrong value", 128, bs
- .nextSetBit(128));
-
- // at bitset element 2
- assertEquals("nextSetBit() returned the wrong value", 193, bs
- .nextSetBit(130));
-
- assertEquals("nextSetBit() returned the wrong value", 193, bs
- .nextSetBit(191));
- assertEquals("nextSetBit() returned the wrong value", 193, bs
- .nextSetBit(192));
- assertEquals("nextSetBit() returned the wrong value", 193, bs
- .nextSetBit(193));
- assertEquals("nextSetBit() returned the wrong value", 450, bs
- .nextSetBit(194));
- assertEquals("nextSetBit() returned the wrong value", 450, bs
- .nextSetBit(255));
- assertEquals("nextSetBit() returned the wrong value", 450, bs
- .nextSetBit(256));
- assertEquals("nextSetBit() returned the wrong value", 450, bs
- .nextSetBit(450));
-
- assertEquals("nextSetBit() returned the wrong value", -1, bs
- .nextSetBit(451));
- assertEquals("nextSetBit() returned the wrong value", -1, bs
- .nextSetBit(511));
- assertEquals("nextSetBit() returned the wrong value", -1, bs
- .nextSetBit(512));
- assertEquals("nextSetBit() returned the wrong value", -1, bs
- .nextSetBit(800));
- }
-
- /**
- * @tests java.util.BitSet#nextClearBit(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextClearBit",
- args = {int.class}
- )
- public void test_nextClearBitI() {
- // Test for method int java.util.BitSet.nextSetBit()
- BitSet bs = new BitSet(500);
- // ensure all the bits from 0 to bs.size() - 1 are set to true
- bs.set(0, bs.size() - 1);
- bs.set(bs.size() - 1);
- bs.clear(5);
- bs.clear(32);
- bs.clear(63);
- bs.clear(64);
- bs.clear(71, 110);
- bs.clear(127, 130);
- bs.clear(193);
- bs.clear(450);
- try {
- bs.nextClearBit(-1);
- fail("Expected IndexOutOfBoundsException for negative index");
- } catch (IndexOutOfBoundsException e) {
- }
- assertEquals("nextClearBit() returned the wrong value", 5, bs
- .nextClearBit(0));
- assertEquals("nextClearBit() returned the wrong value", 5, bs
- .nextClearBit(5));
- assertEquals("nextClearBit() returned the wrong value", 32, bs
- .nextClearBit(6));
- assertEquals("nextClearBit() returned the wrong value", 32, bs
- .nextClearBit(32));
- assertEquals("nextClearBit() returned the wrong value", 63, bs
- .nextClearBit(33));
-
- // boundary tests
- assertEquals("nextClearBit() returned the wrong value", 63, bs
- .nextClearBit(63));
- assertEquals("nextClearBit() returned the wrong value", 64, bs
- .nextClearBit(64));
-
- // at bitset element 1
- assertEquals("nextClearBit() returned the wrong value", 71, bs
- .nextClearBit(65));
- assertEquals("nextClearBit() returned the wrong value", 71, bs
- .nextClearBit(71));
- assertEquals("nextClearBit() returned the wrong value", 72, bs
- .nextClearBit(72));
- assertEquals("nextClearBit() returned the wrong value", 127, bs
- .nextClearBit(110));
-
- // boundary tests
- assertEquals("nextClearBit() returned the wrong value", 127, bs
- .nextClearBit(127));
- assertEquals("nextClearBit() returned the wrong value", 128, bs
- .nextClearBit(128));
-
- // at bitset element 2
- assertEquals("nextClearBit() returned the wrong value", 193, bs
- .nextClearBit(130));
- assertEquals("nextClearBit() returned the wrong value", 193, bs
- .nextClearBit(191));
-
- assertEquals("nextClearBit() returned the wrong value", 193, bs
- .nextClearBit(192));
- assertEquals("nextClearBit() returned the wrong value", 193, bs
- .nextClearBit(193));
- assertEquals("nextClearBit() returned the wrong value", 450, bs
- .nextClearBit(194));
- assertEquals("nextClearBit() returned the wrong value", 450, bs
- .nextClearBit(255));
- assertEquals("nextClearBit() returned the wrong value", 450, bs
- .nextClearBit(256));
- assertEquals("nextClearBit() returned the wrong value", 450, bs
- .nextClearBit(450));
-
- // bitset has 1 still the end of bs.size() -1, but calling nextClearBit
- // with any index value after the last true bit should return bs.size()
- assertEquals("nextClearBit() returned the wrong value", 512, bs
- .nextClearBit(451));
- assertEquals("nextClearBit() returned the wrong value", 512, bs
- .nextClearBit(511));
- assertEquals("nextClearBit() returned the wrong value", 512, bs
- .nextClearBit(512));
-
- // if the index is larger than bs.size(), nextClearBit should return
- // index
- assertEquals("nextClearBit() returned the wrong value", 513, bs
- .nextClearBit(513));
- assertEquals("nextClearBit() returned the wrong value", 800, bs
- .nextClearBit(800));
- }
-
- /**
- * @tests java.util.BitSet#isEmpty()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isEmpty",
- args = {}
- )
- public void test_isEmpty() {
- BitSet bs = new BitSet(500);
- assertTrue("Test: isEmpty() returned wrong value", bs.isEmpty());
-
- // at bitset element 0
- bs.set(3);
- assertFalse("Test0: isEmpty() returned wrong value", bs
- .isEmpty());
-
- // at bitset element 1
- bs.clear();
- bs.set(12);
- assertFalse("Test1: isEmpty() returned wrong value", bs
- .isEmpty());
-
- // at bitset element 2
- bs.clear();
- bs.set(128);
- assertFalse("Test2: isEmpty() returned wrong value", bs
- .isEmpty());
-
- // boundary testing
- bs.clear();
- bs.set(459);
- assertFalse("Test3: isEmpty() returned wrong value", bs
- .isEmpty());
-
- bs.clear();
- bs.set(511);
- assertFalse("Test4: isEmpty() returned wrong value", bs
- .isEmpty());
- }
-
- /**
- * @tests java.util.BitSet#cardinality()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "cardinality",
- args = {}
- )
- public void test_cardinality() {
- // test for method int java.util.BitSet.cardinality()
- BitSet bs = new BitSet(500);
- bs.set(5);
- bs.set(32);
- bs.set(63);
- bs.set(64);
- bs.set(71, 110);
- bs.set(127, 130);
- bs.set(193);
- bs.set(450);
- assertEquals("cardinality() returned wrong value", 48, bs.cardinality());
-
- bs.flip(0, 500);
- assertEquals("cardinality() returned wrong value", 452, bs
- .cardinality());
-
- bs.clear();
- assertEquals("cardinality() returned wrong value", 0, bs.cardinality());
-
- bs.set(0, 500);
- assertEquals("cardinality() returned wrong value", 500, bs
- .cardinality());
- }
-
- /**
- * helper method to display the contents of a bitset
- *
- */
- private static void printBitset(BitSet bs) {
- System.out.println();
- for (int i = bs.size() - 1; i >= 0; i--) {
- if (bs.get(i))
- System.out.print(1);
- else
- System.out.print(0);
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
-
- eightbs = new BitSet();
-
- for (int i = 0; i < 8; i++)
- eightbs.set(i);
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/CalendarTest.java b/luni/src/test/java/tests/api/java/util/CalendarTest.java
deleted file mode 100644
index a9ee4c6..0000000
--- a/luni/src/test/java/tests/api/java/util/CalendarTest.java
+++ /dev/null
@@ -1,1282 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.Calendar;
-import java.util.Date;
-import java.util.Locale;
-import java.util.TimeZone;
-
-@TestTargetClass(Calendar.class)
-public class CalendarTest extends junit.framework.TestCase {
-
- Locale defaultLocale;
-
- /**
- * @tests java.util.Calendar#set(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "set",
- args = {int.class, int.class}
- )
- public void test_setII() {
- // Test for correct result defined by the last set field
- Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- assertTrue("Incorrect result 0: " + cal.getTime().getTime(), cal
- .getTime().getTime() == 1009861200000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- assertTrue("Incorrect result 0a: " + cal.getTime(), cal.getTime()
- .getTime() == 1014958800000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DATE, 24);
- assertTrue("Incorrect result 0b: " + cal.getTime(), cal.getTime()
- .getTime() == 1011848400000L);
-
- cal.set(Calendar.MONTH, Calendar.OCTOBER);
- cal.set(Calendar.DATE, 31);
- cal.set(Calendar.MONTH, Calendar.NOVEMBER);
- cal.set(Calendar.DATE, 26);
- assertTrue("Incorrect month: " + cal.get(Calendar.MONTH), cal
- .get(Calendar.MONTH) == Calendar.NOVEMBER);
-
- int dow = cal.get(Calendar.DAY_OF_WEEK);
- cal.set(Calendar.DATE, 27);
- assertTrue("Incorrect DAY_OF_WEEK: " + cal.get(Calendar.DAY_OF_WEEK)
- + " expected: " + dow, cal.get(Calendar.DAY_OF_WEEK) != dow);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- assertTrue("Incorrect result 0c1: " + cal.getTime().getTime(), cal
- .getTime().getTime() == 1010379600000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
- assertTrue("Incorrect result 0c2: " + cal.getTime().getTime(), cal
- .getTime().getTime() == 1009861200000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
- assertTrue("Incorrect result 0c3: " + cal.getTime(), cal.getTime()
- .getTime() == 1010034000000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_MONTH, 2);
- assertTrue("Incorrect result 0d: " + cal.getTime(), cal.getTime()
- .getTime() == 1010293200000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 2);
- assertTrue("Incorrect result 0e: " + cal.getTime(), cal.getTime()
- .getTime() == 1010898000000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 11);
- assertTrue("Incorrect result 0f: " + cal.getTime(), cal.getTime()
- .getTime() == 1015736400000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DATE, 24);
- cal.set(Calendar.WEEK_OF_YEAR, 11);
- assertTrue("Incorrect result 0g: " + cal.getTime(), cal.getTime()
- .getTime() == 1011848400000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.get(Calendar.WEEK_OF_YEAR); // Force fields to compute
- cal.set(Calendar.WEEK_OF_YEAR, 11);
- assertTrue("Incorrect result 0h: " + cal.getTime(), cal.getTime()
- .getTime() == 1015909200000L);
-
- // WEEK_OF_YEAR has priority over MONTH/DATE
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_YEAR, 170);
- cal.set(Calendar.WEEK_OF_YEAR, 11);
- cal.set(Calendar.MONTH, Calendar.JANUARY);
- cal.set(Calendar.DATE, 5);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- assertTrue("Incorrect result 1: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // WEEK_OF_YEAR has priority over MONTH/DATE
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 11);
- cal.set(Calendar.MONTH, Calendar.JANUARY);
- cal.set(Calendar.DATE, 5);
- cal.set(Calendar.DAY_OF_YEAR, 170);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- assertTrue("Incorrect result 1a: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // DAY_OF_WEEK has no effect when other fields not set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- cal.set(Calendar.DATE, 11);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
- assertTrue("Incorrect result 1b: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // WEEK_OF_MONTH has priority
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 12);
- cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
- cal.set(Calendar.WEEK_OF_MONTH, 3);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- cal.set(Calendar.DATE, 5);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- assertTrue("Incorrect result 2: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // DAY_OF_WEEK_IN_MONTH has priority over WEEK_OF_YEAR
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 12);
- cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 2);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- cal.set(Calendar.DATE, 5);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- assertTrue("Incorrect result 3: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // WEEK_OF_MONTH has priority, MONTH not set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 12);
- cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
- cal.set(Calendar.WEEK_OF_MONTH, 3);
- cal.set(Calendar.DATE, 25);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- assertTrue("Incorrect result 4: " + cal.getTime(), cal.getTime()
- .getTime() == 1010984400000L);
-
- // WEEK_OF_YEAR has priority when MONTH set last and DAY_OF_WEEK set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 11);
- cal.set(Calendar.DATE, 25);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- cal.set(Calendar.MONTH, Calendar.JANUARY);
- assertTrue("Incorrect result 5: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // Use MONTH/DATE when WEEK_OF_YEAR set but not DAY_OF_WEEK
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 12);
- cal.set(Calendar.DATE, 11);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- assertTrue("Incorrect result 5a: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // Use MONTH/DATE when DAY_OF_WEEK is not set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 12);
- cal.set(Calendar.DATE, 11);
- cal.set(Calendar.WEEK_OF_MONTH, 1);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- assertTrue("Incorrect result 5b: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // WEEK_OF_MONTH has priority
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 12);
- cal.set(Calendar.DATE, 5);
- cal.set(Calendar.WEEK_OF_MONTH, 3);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- assertTrue("Incorrect result 5c: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // DATE has priority when set last
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 12);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- cal.set(Calendar.DATE, 11);
- assertTrue("Incorrect result 6: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // DATE has priority when set last, MONTH not set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 12);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- cal.set(Calendar.DATE, 14);
- assertTrue("Incorrect result 7: " + cal.getTime(), cal.getTime()
- .getTime() == 1010984400000L);
-
- // DAY_OF_YEAR has priority when MONTH set last and DATE not set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_YEAR, 70);
- cal.set(Calendar.MONTH, Calendar.JANUARY);
- assertTrue("Incorrect result 8: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // DAY/MONTH has priority when DATE set after DAY_OF_YEAR
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_YEAR, 170);
- cal.set(Calendar.DATE, 11);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- assertTrue("Incorrect result 8a: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // DAY_OF_YEAR has priority when set after DATE
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DATE, 15);
- cal.set(Calendar.DAY_OF_YEAR, 70);
- cal.set(Calendar.MONTH, Calendar.JANUARY);
- assertTrue("Incorrect result 8b: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // DATE has priority when set last
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_YEAR, 70);
- cal.set(Calendar.DATE, 14);
- assertTrue("Incorrect result 9: " + cal.getTime(), cal.getTime()
- .getTime() == 1010984400000L);
-
- // DATE has priority when set last
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_YEAR, 15);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
- cal.set(Calendar.DATE, 14);
- assertTrue("Incorrect result 9a: " + cal.getTime(), cal.getTime()
- .getTime() == 1010984400000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
- cal.set(Calendar.DATE, 14);
- cal.set(Calendar.WEEK_OF_YEAR, 11);
- assertTrue("Incorrect result 9b: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DATE, 14);
- cal.set(Calendar.WEEK_OF_YEAR, 11);
- assertTrue("Incorrect result 9c: " + cal.getTime(), cal.getTime()
- .getTime() == 1010984400000L);
-
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.WEEK_OF_MONTH, 1);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- cal.set(Calendar.DATE, 11);
- assertTrue("Incorrect result 9d: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // DAY_OF_YEAR has priority when DAY_OF_MONTH set last and other fields
- // not set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_YEAR, 70);
- cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
- assertTrue("Incorrect result 10: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // MONTH/DATE has priority when DAY_OF_WEEK_IN_MONTH set last but
- // DAY_OF_WEEK not set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DATE, 11);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
- assertTrue("Incorrect result 11: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // MONTH/DATE has priority when WEEK_OF_YEAR set last but DAY_OF_WEEK
- // not set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DATE, 11);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- cal.set(Calendar.WEEK_OF_YEAR, 15);
- assertTrue("Incorrect result 12: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // MONTH/DATE has priority when WEEK_OF_MONTH set last but DAY_OF_WEEK
- // not set
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DATE, 11);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- cal.set(Calendar.WEEK_OF_MONTH, 1);
- assertTrue("Incorrect result 13: " + cal.getTime(), cal.getTime()
- .getTime() == 1015822800000L);
-
- // Ensure last date field set is reset after computing
- cal.clear();
- cal.set(Calendar.YEAR, 2002);
- cal.set(Calendar.DAY_OF_YEAR, 111);
- cal.get(Calendar.YEAR);
- cal.set(Calendar.MONTH, Calendar.MARCH);
- cal.set(Calendar.AM_PM, Calendar.AM);
- assertTrue("Incorrect result 14: " + cal.getTime(), cal.getTime()
- .getTime() == 1016686800000L);
-
- int hour = cal.get(Calendar.HOUR);
- cal.set(Calendar.HOUR, hour);
- cal.set(Calendar.AM_PM, Calendar.PM);
- assertEquals("AM_PM not changed", Calendar.PM, cal.get(Calendar.AM_PM));
- // setting AM_PM without HOUR should not have any affect
- cal.set(Calendar.AM_PM, Calendar.AM);
- assertEquals("AM_PM was changed 1",
- Calendar.AM, cal.get(Calendar.AM_PM));
- int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
- hour = cal.get(Calendar.HOUR);
- cal.set(Calendar.AM_PM, Calendar.PM);
- assertEquals("AM_PM was changed 2",
- Calendar.PM, cal.get(Calendar.AM_PM));
- assertEquals(hour, cal.get(Calendar.HOUR));
- assertEquals(hourOfDay + 12, cal.get(Calendar.HOUR_OF_DAY));
-
- // regression test for Harmony-2122
- cal = Calendar.getInstance();
- int oldValue = cal.get(Calendar.AM_PM);
- int newValue = (oldValue == Calendar.AM) ? Calendar.PM : Calendar.AM;
- cal.set(Calendar.AM_PM, newValue);
- newValue = cal.get(Calendar.AM_PM);
- assertTrue(newValue != oldValue);
-
- cal.setLenient(false);
-
- try {
- cal.set(-1, 3);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- cal.set(Calendar.FIELD_COUNT + 1, 3);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Calendar#setTime(java.util.Date)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setTime",
- args = {java.util.Date.class}
- )
- public void test_setTimeLjava_util_Date() {
- Calendar cal = Calendar.getInstance();
- // Use millisecond time for testing in Core
- cal.setTime(new Date(884581200000L)); // (98, Calendar.JANUARY, 12)
- assertEquals("incorrect millis", 884581200000L, cal.getTime().getTime());
- cal.setTimeZone(TimeZone.getTimeZone("EST"));
- cal.setTime(new Date(943506000000L)); // (99, Calendar.NOVEMBER, 25)
- assertTrue("incorrect fields", cal.get(Calendar.YEAR) == 1999
- && cal.get(Calendar.MONTH) == Calendar.NOVEMBER
- && cal.get(Calendar.DATE) == 25);
- }
-
- /**
- * @tests java.util.Calendar#compareTo(Calendar)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "compareTo",
- args = {java.util.Calendar.class}
- )
- public void test_compareToLjava_util_Calendar_null() {
- Calendar cal = Calendar.getInstance();
- try {
- cal.compareTo(null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Calendar#compareTo(Calendar)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.util.Calendar.class}
- )
- public void test_compareToLjava_util_Calendar() {
- Calendar cal = Calendar.getInstance();
- cal.clear();
- cal.set(1997, 12, 13, 23, 57);
-
- Calendar anotherCal = Calendar.getInstance();
- anotherCal.clear();
- anotherCal.set(1997, 12, 13, 23, 57);
- assertEquals(0, cal.compareTo(anotherCal));
-
- anotherCal = Calendar.getInstance();
- anotherCal.clear();
- anotherCal.set(1997, 11, 13, 24, 57);
- assertEquals(1, cal.compareTo(anotherCal));
-
- anotherCal = Calendar.getInstance();
- anotherCal.clear();
- anotherCal.set(1997, 12, 13, 23, 58);
- assertEquals(-1, cal.compareTo(anotherCal));
-
- try {
- cal.compareTo(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- MockCalendar mc = new MockCalendar();
-
- try {
- cal.compareTo(mc);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Calendar#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- // Regression for HARMONY-475
- Calendar cal = Calendar.getInstance();
- cal.set(2006, 5, 6, 11, 35);
- Calendar anotherCal = (Calendar) cal.clone();
- // should be deep clone
- assertNotSame("getTimeZone", cal.getTimeZone(), anotherCal
- .getTimeZone());
- }
-
- /**
- * @tests java.util.Calendar#getTimeInMillis()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTimeInMillis",
- args = {}
- )
- public void test_getTimeInMillis() {
- Calendar cal = Calendar.getInstance();
-
- int year = Integer.MIN_VALUE + 71;
- cal.setTimeZone(TimeZone.getTimeZone("GMT"));;
- cal.set(Calendar.YEAR, year + 1900);
- cal.set(Calendar.MONTH, Calendar.JANUARY);
- cal.set(Calendar.DATE, 1);
- cal.set(Calendar.HOUR_OF_DAY, 0);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- cal.set(Calendar.MILLISECOND, 0);
-
- assertEquals(6017546357372606464L, cal.getTimeInMillis());
- }
-
- /**
- * @tests {@link java.util.Calendar#getActualMaximum(int)}
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getActualMaximum",
- args = {int.class}
- )
- public void test_getActualMaximum_I() {
- Calendar c = new MockCalendar();
- assertEquals("should be equal to 0", 0, c.getActualMaximum(0));
- }
-
- /**
- * @tests {@link java.util.Calendar#getActualMinimum(int)}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getActualMinimum",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Calendar",
- args = {}
- )
- })
- public void test_getActualMinimum_I() {
- Calendar c = new MockCalendar();
- assertEquals("should be equal to 0", 0, c.getActualMinimum(0));
- }
-
- private class MockCalendar extends Calendar {
-
- public MockCalendar() {
- super();
- }
-
- public MockCalendar(TimeZone default1, Locale germany) {
- super(default1, germany);
- }
-
- @Override
- public void add(int field, int value) {
- }
-
- @Override
- protected void computeFields() {
- }
-
- @Override
- protected void computeTime() {
- throw new IllegalArgumentException();
- }
-
- @Override
- public int getGreatestMinimum(int field) {
- return 0;
- }
-
- @Override
- public int getLeastMaximum(int field) {
- return 0;
- }
-
- @Override
- public int getMaximum(int field) {
- return 0;
- }
-
- @Override
- public int getMinimum(int field) {
- return 0;
- }
-
- @Override
- public void roll(int field, boolean increment) {
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Calendar",
- args = {java.util.TimeZone.class, java.util.Locale.class}
- )
- public void test_ConstructorLjava_utilTimeZoneLjava_util_Locale() {
- assertNotNull(new MockCalendar(TimeZone.getDefault(), Locale.GERMANY));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Test calls dummy implementation of abstract method.",
- method = "add",
- args = {int.class, int.class}
- )
- public void test_addII() {
- MockCalendar mc = new MockCalendar();
-
- mc.add(Calendar.DAY_OF_YEAR, 7);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "after",
- args = {java.lang.Object.class}
- )
- public void test_afterLjava_lang_Object() {
- MockCalendar mcBefore = new MockCalendar();
- MockCalendar mc = new MockCalendar();
- MockCalendar mcAfter = new MockCalendar();
- MockCalendar mcSame = new MockCalendar();
-
- mcBefore.setTimeInMillis(1000);
- mc.setTimeInMillis(10000);
- mcAfter.setTimeInMillis(100000);
- mcSame.setTimeInMillis(10000);
-
- assertTrue(mc.after(mcBefore));
- assertFalse(mc.after(mcAfter));
- assertFalse(mc.after(mcSame));
- assertFalse(mc.after(mc));
- assertFalse(mc.after(new String()));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "before",
- args = {java.lang.Object.class}
- )
- public void test_beforeLjava_lang_Object() {
- MockCalendar mcBefore = new MockCalendar();
- MockCalendar mc = new MockCalendar();
- MockCalendar mcAfter = new MockCalendar();
- MockCalendar mcSame = new MockCalendar();
-
- mcBefore.setTimeInMillis(1000);
- mc.setTimeInMillis(10000);
- mcAfter.setTimeInMillis(100000);
- mcSame.setTimeInMillis(10000);
-
- assertFalse(mc.before(mcBefore));
- assertTrue(mc.before(mcAfter));
- assertFalse(mc.before(mcSame));
- assertFalse(mc.before(mc));
- assertFalse(mc.before(new String()));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- MockCalendar mc1 = new MockCalendar();
- MockCalendar mc2 = new MockCalendar();
-
- assertTrue(mc1.toString().equals(mc2.toString()));
- mc1.set(2008, Calendar.SEPTEMBER, 23, 18, 0, 0);
- assertFalse(mc1.toString().equals(mc2.toString()));
- mc1.clear();
- assertTrue(mc1.toString().equals(mc2.toString()));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {int.class}
- )
- public void test_clearI() {
- MockCalendar mc1 = new MockCalendar();
- MockCalendar mc2 = new MockCalendar();
-
- assertTrue(mc1.toString().equals(mc2.toString()));
- mc1.set(2008, Calendar.SEPTEMBER, 23, 18, 0, 0);
- assertFalse(mc1.toString().equals(mc2.toString()));
- mc1.clear(Calendar.YEAR);
- mc1.clear(Calendar.MONTH);
- mc1.clear(Calendar.DAY_OF_MONTH);
- mc1.clear(Calendar.HOUR_OF_DAY);
- mc1.clear(Calendar.MINUTE);
- mc1.clear(Calendar.SECOND);
- mc1.clear(Calendar.MILLISECOND);
- assertTrue(mc1.toString().equals(mc2.toString()));
- }
-
- class Mock_Calendar extends Calendar {
- boolean flagComplete = false;
- @Override
- public void add(int field, int amount) {
-
- }
-
- @Override
- protected void computeFields() {
- this.set(MONTH, this.internalGet(MONTH)%12);
- }
-
- @Override
- protected void computeTime() {
- }
-
- @Override
- public int getGreatestMinimum(int field) {
- return 0;
- }
-
- @Override
- public int getLeastMaximum(int field) {
- return 0;
- }
-
- @Override
- public int getMaximum(int field) {
- return 0;
- }
-
- @Override
- public int getMinimum(int field) {
- return 0;
- }
-
- @Override
- public void roll(int field, boolean up) {
- }
-
- @Override
- public void complete() {
- computeTime();
- computeFields();
- flagComplete = true;
- }
-
- public boolean isCompleted () {
- return flagComplete;
- }
-
- public int internalGetField(int field) {
- return super.internalGet(field);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "complete",
- args = {}
- )
- public void test_complete() {
- Mock_Calendar cal = new Mock_Calendar();
-
- assertFalse(cal.isCompleted());
- cal.setTimeInMillis(1000);
- cal.get(Calendar.MONTH);
- assertTrue(cal.isCompleted());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "computeFields",
- args = {}
- )
- public void test_computeFields() {
- Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("GMT+2"), defaultLocale);
- Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("GMT+2"), defaultLocale);
-
- cal1.setTimeInMillis(1222185600225L);
- cal2.set(2008, Calendar.SEPTEMBER, 23, 18, 0, 0);
- assertFalse(cal1.toString().equals(cal2.toString()));
- cal1.get(Calendar.YEAR);
- cal2.getTimeInMillis();
- cal1.set(Calendar.MILLISECOND, 0);
- cal2.set(Calendar.MILLISECOND, 0);
- // tests fails in this line.
- assertTrue(cal1.toString().equals(cal2.toString()));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equals() {
- Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("GMT+2"), defaultLocale);
- Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("GMT+2"), defaultLocale);
-
- cal1.setTimeInMillis(1222185600225L);
- cal2.set(2008, Calendar.SEPTEMBER, 23, 18, 0, 0);
- assertFalse(cal1.equals(cal2));
- cal1.get(Calendar.YEAR);
- cal2.getTimeInMillis();
- cal1.set(Calendar.MILLISECOND, 0);
- cal2.set(Calendar.MILLISECOND, 0);
- // tests fails on following line.
- assertTrue(cal1.equals(cal2));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {int.class}
- )
- public void test_getI() {
- Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+2"), defaultLocale);
-
- cal.setTimeInMillis(1222185600225L);
- assertEquals(cal.get(Calendar.ERA), 1);
- assertEquals(cal.get(Calendar.YEAR), 2008);
- assertEquals(cal.get(Calendar.MONTH), Calendar.SEPTEMBER);
- assertEquals(cal.get(Calendar.DAY_OF_MONTH), 23);
- // Following line returns wrong value. Behavior uncompatible with RI.
- assertEquals(cal.get(Calendar.HOUR_OF_DAY), 18);
- assertEquals(cal.get(Calendar.MINUTE), 0);
-
- try {
- cal.get(-1);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- cal.get(Calendar.FIELD_COUNT + 1);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch (ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAvailableLocales",
- args = {}
- )
- public void test_getAvailableLocales() {
- assertNotNull(Calendar.getAvailableLocales());
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFirstDayOfWeek",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstance",
- args = {}
- )
- })
- public void test_getFirstDayOfWeek() {
- Calendar cal = Calendar.getInstance();
-
- assertEquals(Calendar.SUNDAY, cal.getFirstDayOfWeek());
- Locale.setDefault(Locale.FRANCE);
- cal = Calendar.getInstance();
- assertEquals(Calendar.MONDAY, cal.getFirstDayOfWeek());
- Locale.setDefault(Locale.US);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.util.Locale.class}
- )
- public void test_getInstanceLjava_util_Locale() {
- Calendar cal1 = Calendar.getInstance(Locale.FRANCE);
- Locale.setDefault(Locale.FRANCE);
- Calendar cal2 = Calendar.getInstance();
- assertSame(cal1.getFirstDayOfWeek(), cal2.getFirstDayOfWeek());
- Locale.setDefault(Locale.US);
- cal2 = Calendar.getInstance();
- assertNotSame(cal1.getFirstDayOfWeek(), cal2.getFirstDayOfWeek());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.util.TimeZone.class}
- )
- public void testget_InstanceLjava_util_TimeZone() {
- Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("GMT-6"));
- Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("GMT+1"));
- assertNotSame(cal1.getTimeZone().getRawOffset(), cal2.getTimeZone().getRawOffset());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.util.TimeZone.class, java.util.Locale.class}
- )
- public void test_getInstanceLjava_util_TimeZoneLjava_util_Locale() {
- Calendar cal1 = Calendar.getInstance(TimeZone.getTimeZone("GMT-6"), Locale.FRANCE);
- Locale.setDefault(Locale.FRANCE);
- Calendar cal2 = Calendar.getInstance(TimeZone.getTimeZone("GMT+1"));
- assertSame(cal1.getFirstDayOfWeek(), cal2.getFirstDayOfWeek());
- assertNotSame(cal1.getTimeZone().getRawOffset(), cal2.getTimeZone().getRawOffset());
- Locale.setDefault(Locale.US);
- cal2 = Calendar.getInstance(TimeZone.getTimeZone("GMT+1"));
- assertNotSame(cal1.getFirstDayOfWeek(), cal2.getFirstDayOfWeek());
- assertNotSame(cal1.getTimeZone().getRawOffset(), cal2.getTimeZone().getRawOffset());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMinimalDaysInFirstWeek",
- args = {}
- )
- public void test_getMinimalDaysInFirstWeek() {
- Calendar cal = Calendar.getInstance();
- assertTrue(cal.getMinimalDaysInFirstWeek()==1);
- Locale.setDefault(Locale.FRANCE);
- cal = Calendar.getInstance();
- assertTrue(cal.getMinimalDaysInFirstWeek()==4);
- Locale.setDefault(Locale.US);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTime",
- args = {}
- )
- public void test_getTime() {
- Calendar cal = Calendar.getInstance();
- Date d = new Date(1222185600225L);
-
- cal.setTimeInMillis(1222185600225L);
- assertEquals(d.getTime(), cal.getTimeInMillis());
- assertEquals(d, cal.getTime());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTimeZone",
- args = {}
- )
- public void test_getTimeZone() {
- Calendar cal = Calendar.getInstance();
- cal.setTimeZone(TimeZone.getTimeZone("GMT-6"));
-
- assertEquals(TimeZone.getTimeZone("GMT-6"), cal.getTimeZone());
- cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-8"));
- assertEquals(TimeZone.getTimeZone("GMT-8"), cal.getTimeZone());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- Calendar cal1 = Calendar.getInstance();
- Locale.setDefault(Locale.FRANCE);
- Calendar cal2 = Calendar.getInstance();
- Locale.setDefault(Locale.US);
- assertTrue(cal1.hashCode() != cal2.hashCode());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "internalGet",
- args = {int.class}
- )
- public void test_internalGet() {
- Mock_Calendar mc = new Mock_Calendar();
- assertEquals(0, mc.internalGetField(Calendar.MONTH));
- mc.set(Calendar.MONTH, 35);
- assertEquals(35, mc.internalGetField(Calendar.MONTH));
- assertEquals(11, mc.get(Calendar.MONTH));
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isLenient",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setLenient",
- args = {boolean.class}
- )
- })
- public void test_isLenient() {
- Calendar cal = Calendar.getInstance();
- assertTrue(cal.isLenient());
- cal.set(Calendar.MONTH, 35);
- cal.get(Calendar.MONTH);
- cal.setLenient(false);
- cal.set(Calendar.MONTH, 35);
- try {
- cal.get(Calendar.MONTH);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- assertFalse(cal.isLenient());
- cal.setLenient(true);
- cal.set(Calendar.MONTH, 35);
- cal.get(Calendar.MONTH);
- assertTrue(cal.isLenient());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isSet",
- args = {int.class}
- )
- public void test_isSet() {
- Calendar cal = Calendar.getInstance();
- cal.clear();
- assertFalse(cal.isSet(Calendar.MONTH));
- cal.set(Calendar.MONTH, 35);
- assertTrue(cal.isSet(Calendar.MONTH));
- assertFalse(cal.isSet(Calendar.YEAR));
- cal.get(Calendar.MONTH);
- assertTrue(cal.isSet(Calendar.YEAR));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "roll",
- args = {int.class, int.class}
- )
- public void test_rollII() {
- Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+2"), defaultLocale);
-
- cal.setTimeInMillis(1222185600225L);
- cal.roll(Calendar.DAY_OF_MONTH, 200);
- assertEquals(cal.get(Calendar.ERA), 1);
- assertEquals(cal.get(Calendar.YEAR), 2008);
- assertEquals(cal.get(Calendar.MONTH), Calendar.SEPTEMBER);
- assertEquals(cal.get(Calendar.DAY_OF_MONTH), 13);
- // Following line returns wrong value. Behavior uncompatible with RI.
- assertEquals(cal.get(Calendar.HOUR_OF_DAY), 18);
- assertEquals(cal.get(Calendar.MINUTE), 0);
- cal.roll(Calendar.DAY_OF_MONTH, -200);
- assertEquals(cal.get(Calendar.ERA), 1);
- assertEquals(cal.get(Calendar.YEAR), 2008);
- assertEquals(cal.get(Calendar.MONTH), Calendar.SEPTEMBER);
- assertEquals(cal.get(Calendar.DAY_OF_MONTH), 23);
- assertEquals(cal.get(Calendar.HOUR_OF_DAY), 18);
- assertEquals(cal.get(Calendar.MINUTE), 0);
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "set",
- args = {int.class, int.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setTimeInMillis",
- args = {long.class}
- )
- })
- public void test_setIII() {
- Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+2"), defaultLocale);
-
- cal.setTimeInMillis(1222185600225L);
- assertEquals(1222185600225L, cal.getTimeInMillis());
- assertEquals(cal.get(Calendar.YEAR), 2008);
- assertEquals(cal.get(Calendar.MONTH), Calendar.SEPTEMBER);
- assertEquals(cal.get(Calendar.DAY_OF_MONTH), 23);
- assertEquals(cal.get(Calendar.SECOND), 0);
-
- cal.set(1970, Calendar.JANUARY, 1);
- assertEquals(cal.get(Calendar.ERA), 1);
- // Following line returns wrong value. Behavior uncompatible with RI.
- assertEquals(cal.get(Calendar.HOUR_OF_DAY), 18);
- assertEquals(cal.get(Calendar.MINUTE), 0);
- assertEquals(cal.get(Calendar.SECOND), 0);
-
- assertEquals(cal.get(Calendar.YEAR), 1970);
- assertEquals(cal.get(Calendar.MONTH), 0);
- assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "set",
- args = {int.class, int.class, int.class, int.class, int.class}
- )
- public void test_setIIIII() {
- Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+2"), defaultLocale);
-
- cal.setTimeInMillis(1222185600225L);
- assertEquals(cal.get(Calendar.YEAR), 2008);
- assertEquals(cal.get(Calendar.MONTH), Calendar.SEPTEMBER);
- assertEquals(cal.get(Calendar.DAY_OF_MONTH), 23);
- // Following line returns wrong value. Behavior uncompatible with RI.
- assertEquals(cal.get(Calendar.HOUR_OF_DAY), 18);
- assertEquals(cal.get(Calendar.MINUTE), 0);
- assertEquals(cal.get(Calendar.SECOND), 0);
-
- cal.set(1970, Calendar.JANUARY, 1, 0, 10);
- assertEquals(cal.get(Calendar.ERA), 1);
- assertEquals(cal.get(Calendar.SECOND), 0);
-
- assertEquals(cal.get(Calendar.YEAR), 1970);
- assertEquals(cal.get(Calendar.MONTH), 0);
- assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
- assertEquals(cal.get(Calendar.HOUR_OF_DAY), 0);
- assertEquals(cal.get(Calendar.MINUTE), 10);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "set",
- args = {int.class, int.class, int.class, int.class, int.class, int.class}
- )
- public void test_setIIIIII() {
- Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+2"), defaultLocale);
-
- cal.setTimeInMillis(1222185600225L);
- assertEquals(cal.get(Calendar.YEAR), 2008);
- assertEquals(cal.get(Calendar.MONTH), Calendar.SEPTEMBER);
- assertEquals(cal.get(Calendar.DAY_OF_MONTH), 23);
- // Following line returns wrong value. Behavior uncompatible with RI.
- assertEquals(cal.get(Calendar.HOUR_OF_DAY), 18);
- assertEquals(cal.get(Calendar.MINUTE), 0);
- assertEquals(cal.get(Calendar.SECOND), 0);
-
- cal.set(1970, Calendar.JANUARY, 1, 0, 10, 33);
- assertEquals(cal.get(Calendar.ERA), 1);
-
- assertEquals(cal.get(Calendar.YEAR), 1970);
- assertEquals(cal.get(Calendar.MONTH), 0);
- assertEquals(cal.get(Calendar.DAY_OF_MONTH), 1);
- assertEquals(cal.get(Calendar.HOUR_OF_DAY), 0);
- assertEquals(cal.get(Calendar.MINUTE), 10);
- assertEquals(cal.get(Calendar.SECOND), 33);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setFirstDayOfWeek",
- args = {int.class}
- )
- public void test_setFirstDayOfWeekI() {
- Calendar cal = Calendar.getInstance();
-
- for (int i = 0; i < 10; i++) {
- cal.setFirstDayOfWeek(i);
- assertEquals(i, cal.getFirstDayOfWeek());
- }
- cal.setLenient(false);
- cal.setFirstDayOfWeek(10);
- cal.setFirstDayOfWeek(-10);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setMinimalDaysInFirstWeek",
- args = {int.class}
- )
- public void test_setMinimalDaysInFirstWeekI() {
- Calendar cal = Calendar.getInstance();
-
- for (int i = 0; i < 10; i++) {
- cal.setMinimalDaysInFirstWeek(i);
- assertEquals(i, cal.getMinimalDaysInFirstWeek());
- }
- cal.setLenient(false);
- cal.setMinimalDaysInFirstWeek(10);
- cal.setMinimalDaysInFirstWeek(-10);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setTimeZone",
- args = {java.util.TimeZone.class}
- )
- public void test_setTimeZoneLjava_util_TimeZone() {
- Calendar cal = Calendar.getInstance();
- cal.setTimeZone(TimeZone.getTimeZone("GMT-6"));
- assertEquals(TimeZone.getTimeZone("GMT-6"), cal.getTimeZone());
- cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-8"));
- cal.setTimeZone(TimeZone.getTimeZone("GMT-6"));
- assertEquals(TimeZone.getTimeZone("GMT-6"), cal.getTimeZone());
-
- cal.setTimeZone(null);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- Calendar cal1 = Calendar.getInstance();
- Calendar cal2 = Calendar.getInstance();
- cal1.setTimeZone(TimeZone.getTimeZone("GMT-6"));
- cal2.setTimeZone(TimeZone.getTimeZone("GMT-8"));
- cal1.set(Calendar.MILLISECOND, 0);
- cal2.set(Calendar.MILLISECOND, 0);
- assertFalse(cal1.toString().equals(cal2.toString()));
- cal1.setTimeZone(TimeZone.getTimeZone("GMT-8"));
- assertTrue(cal1.toString().equals(cal2.toString()));
- }
-
- protected void setUp() {
- defaultLocale = Locale.getDefault();
- Locale.setDefault(Locale.US);
- }
-
- protected void tearDown() {
- Locale.setDefault(defaultLocale);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/CollectionsTest.java b/luni/src/test/java/tests/api/java/util/CollectionsTest.java
deleted file mode 100644
index d6760f1..0000000
--- a/luni/src/test/java/tests/api/java/util/CollectionsTest.java
+++ /dev/null
@@ -1,2491 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.Random;
-import java.util.RandomAccess;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeMap;
-import java.util.TreeSet;
-
-import org.apache.harmony.luni.internal.nls.Messages;
-
-import tests.support.Support_CollectionTest;
-import tests.support.Support_ListTest;
-import tests.support.Support_SetTest;
-import tests.support.Support_UnmodifiableCollectionTest;
-import tests.support.Support_UnmodifiableMapTest;
-
-@TestTargetClass(Collections.class)
-public class CollectionsTest extends junit.framework.TestCase {
-
- LinkedList ll;
-
- LinkedList myll;
-
- LinkedList reversedLinkedList;
-
- LinkedList myReversedLinkedList;
-
- Set s;
-
- Set mys;
-
- HashMap hm;
-
- static Object[] objArray;
-
- static Object[] myobjArray;
- {
- objArray = new Object[1000];
- myobjArray = new Object[1000];
- for (int i = 0; i < objArray.length; i++) {
- objArray[i] = new Integer(i);
- myobjArray[i] = new MyInt(i);
- }
- }
-
- public static class ReversedMyIntComparator implements Comparator {
- public int compare(Object o1, Object o2) {
- return -((MyInt) o1).compareTo((MyInt) o2);
- }
-
- public int equals(Object o1, Object o2) {
- return ((MyInt) o1).compareTo((MyInt) o2);
- }
- }
-
- public static class SynchCollectionChecker implements Runnable {
- Collection col;
-
- int colSize;
-
- int totalToRun;
-
- boolean offset;
-
- volatile int numberOfChecks = 0;
-
- boolean result = true;
-
- ArrayList normalCountingList;
-
- ArrayList offsetCountingList;
-
- public void run() {
- // ensure the list either contains the numbers from 0 to size-1 or
- // the numbers from size to 2*size -1
- while (numberOfChecks < totalToRun) {
- synchronized (col) {
- if (!(col.isEmpty() || col.containsAll(normalCountingList) || col
- .containsAll(offsetCountingList)))
- result = false;
- col.clear();
- }
- if (offset)
- col.addAll(offsetCountingList);
- else
- col.addAll(normalCountingList);
- numberOfChecks++;
- }
- }
-
- public SynchCollectionChecker(Collection c, boolean offset,
- int totalChecks) {
- // The collection to test, whether to offset the filler values by
- // size or not, and the min number of iterations to run
- totalToRun = totalChecks;
- col = c;
- colSize = c.size();
- normalCountingList = new ArrayList(colSize);
- offsetCountingList = new ArrayList(colSize);
- for (int counter = 0; counter < colSize; counter++)
- normalCountingList.add(new Integer(counter));
- for (int counter = 0; counter < colSize; counter++)
- offsetCountingList.add(new Integer(counter + colSize));
- col.clear();
- if (offset)
- col.addAll(offsetCountingList);
- else
- col.addAll(normalCountingList);
- }
-
- public boolean offset() {
- // answer true iff the list is filled with a counting sequence
- // starting at the value size to 2*size - 1
- // else the list with be filled starting at 0 to size - 1
- return offset;
- }
-
- public boolean getResult() {
- // answer true iff no corruption has been found in the collection
- return result;
- }
-
- public int getNumberOfChecks() {
- // answer the number of checks that have been performed on the list
- return numberOfChecks;
- }
- }
-
- public static class SynchMapChecker implements Runnable {
- Map map;
-
- int mapSize;
-
- int totalToRun;
-
- boolean offset;
-
- volatile int numberOfChecks = 0;
-
- boolean result = true;
-
- Map normalCountingMap;
-
- Map offsetCountingMap;
-
- public void run() {
- Object firstNormalValue = normalCountingMap.get(new Integer(0));
- Object lastNormalValue = normalCountingMap.get(new Integer(
- mapSize - 1));
- Object firstOffsetValue = offsetCountingMap
- .get(new Integer(mapSize));
- Object lastOffsetValue = offsetCountingMap.get(new Integer(
- 2 * mapSize - 1));
- // ensure the list either contains the numbers from 0 to size-1 or
- // the numbers from size to 2*size -1
- while (numberOfChecks < totalToRun) {
- synchronized (map) {
- if (!(map.isEmpty()
- || (map.containsValue(firstNormalValue) && map
- .containsValue(lastNormalValue)) || (map
- .containsValue(firstOffsetValue) && map
- .containsValue(lastOffsetValue))))
- result = false;
- map.clear();
- }
- if (offset)
- map.putAll(offsetCountingMap);
- else
- map.putAll(normalCountingMap);
- numberOfChecks++;
- }
- }
-
- public SynchMapChecker(Map m, boolean offset, int totalChecks) {
- // The collection to test, whether to offset the filler values by
- // size or not, and the min number of iterations to run
- Integer myInt;
- totalToRun = totalChecks;
- map = m;
- mapSize = m.size();
- normalCountingMap = new HashMap(mapSize);
- offsetCountingMap = new HashMap(mapSize);
- for (int counter = 0; counter < mapSize; counter++) {
- myInt = new Integer(counter);
- normalCountingMap.put(myInt, myInt);
- }
- for (int counter = 0; counter < mapSize; counter++) {
- myInt = new Integer(counter + mapSize);
- offsetCountingMap.put(myInt, myInt);
- }
- map.clear();
- if (offset)
- map.putAll(offsetCountingMap);
- else
- map.putAll(normalCountingMap);
- }
-
- public boolean offset() {
- // answer true iff the list is filled with a counting sequence
- // starting at the value size to 2*size - 1
- // else the list with be filled starting at 0 to size - 1
- return offset;
- }
-
- public boolean getResult() {
- // answer true iff no corruption has been found in the collection
- return result;
- }
-
- public int getNumberOfChecks() {
- // answer the number of checks that have been performed on the list
- return numberOfChecks;
- }
- }
-
- public static class CollectionTest extends junit.framework.TestCase {
-
- Collection col; // must contain the Integers 0 to 99
-
- public CollectionTest(String p1) {
- super(p1);
- }
-
- public CollectionTest(String p1, Collection c) {
- super(p1);
- col = c;
- }
-
- }
-
- static class MyInt {
- int data;
-
- public MyInt(int value) {
- data = value;
- }
-
- public int compareTo(MyInt object) {
- return data > object.data ? 1 : (data < object.data ? -1 : 0);
- }
- }
-
- /**
- * @tests java.util.Collections#binarySearch(java.util.List,
- * java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ClassCastException.",
- method = "binarySearch",
- args = {java.util.List.class, java.lang.Object.class}
- )
- public void test_binarySearchLjava_util_ListLjava_lang_Object() {
- // Test for method int
- // java.util.Collections.binarySearch(java.util.List, java.lang.Object)
- // assumes ll is sorted and has no duplicate keys
- final int llSize = ll.size();
- // Ensure a NPE is thrown if the list is NULL
- try {
- Collections.binarySearch(null, new Object());
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
- for (int counter = 0; counter < llSize; counter++) {
- assertTrue("Returned incorrect binary search item position", ll
- .get(Collections.binarySearch(ll, ll.get(counter))) == ll
- .get(counter));
- }
- }
-
- /**
- * @tests java.util.Collections#binarySearch(java.util.List,
- * java.lang.Object, java.util.Comparator)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ClassCastException.",
- method = "binarySearch",
- args = {java.util.List.class, java.lang.Object.class, java.util.Comparator.class}
- )
- public void test_binarySearchLjava_util_ListLjava_lang_ObjectLjava_util_Comparator() {
- // Test for method int
- // java.util.Collections.binarySearch(java.util.List, java.lang.Object,
- // java.util.Comparator)
- // assumes reversedLinkedList is sorted in reversed order and has no
- // duplicate keys
- final int rSize = myReversedLinkedList.size();
- ReversedMyIntComparator comp = new ReversedMyIntComparator();
- // Ensure a NPE is thrown if the list is NULL
- try {
- Collections.binarySearch(null, new Object(), comp);
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
- for (int counter = 0; counter < rSize; counter++) {
- assertTrue(
- "Returned incorrect binary search item position using custom comparator",
- myReversedLinkedList.get(Collections.binarySearch(
- myReversedLinkedList, myReversedLinkedList
- .get(counter), comp)) == myReversedLinkedList
- .get(counter));
- }
- }
-
- class Mock_ArrayList extends ArrayList {
- @Override
- public
- Object set (int index, Object o){
- throw new UnsupportedOperationException();
- }
- }
-
- /**
- * @tests java.util.Collections#copy(java.util.List, java.util.List)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "copy",
- args = {java.util.List.class, java.util.List.class}
- )
- public void test_copyLjava_util_ListLjava_util_List() {
- // Test for method void java.util.Collections.copy(java.util.List,
- // java.util.List)
- // Ensure a NPE is thrown if the list is NULL
- try {
- Collections.copy(null, ll);
- fail("Expected NullPointerException for null list first parameter");
- } catch (NullPointerException e) {
- }
- try {
- Collections.copy(ll, null);
- fail("Expected NullPointerException for null list second parameter");
- } catch (NullPointerException e) {
- }
- final int llSize = ll.size();
- ll.set(25, null);
- ArrayList al = new ArrayList();
- Integer extraElement = new Integer(1);
- Integer extraElement2 = new Integer(2);
- al.addAll(myReversedLinkedList);
- al.add(extraElement);
- al.add(extraElement2);
- Collections.copy(al, ll);
- for (int counter = 0; counter < llSize; counter++) {
- assertTrue("Elements do not match after copying collection", al
- .get(counter) == ll.get(counter));
- }
- assertTrue("Elements after copied elements affected by copy",
- extraElement == al.get(llSize)
- && extraElement2 == al.get(llSize + 1));
-
- ArrayList ar1 = new ArrayList();
- ArrayList ar2 = new ArrayList();
-
- int i;
-
- for(i = 0; i < 5; i ++) {
- ar2.add(new Integer(i));
- }
-
- for(i = 0; i < 10; i ++) {
- ar1.add(new Integer(i));
- }
-
- try {
- Collections.copy(ar2, ar1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- Mock_ArrayList mal1 = new Mock_ArrayList();
- Mock_ArrayList mal2 = new Mock_ArrayList();
-
- for(i = 0; i < 10; i ++) {
- mal1.add(new Integer(i));
- mal2.add(new Integer(10 - i));
- }
-
- try {
- Collections.copy(mal1, mal2);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Collections#copy(java.util.List, java.util.List)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IndexOutOfBoundsException. Doesn't verify UnsupportedOperationException.",
- method = "copy",
- args = {java.util.List.class, java.util.List.class}
- )
- public void test_copy_check_index() {
- ArrayList a1 = new ArrayList();
- a1.add("one");
- a1.add("two");
-
- ArrayList a2 = new ArrayList();
- a2.add("aa");
-
- try {
- Collections.copy(a2, a1);
- fail("Expected IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- }
-
- assertEquals("aa", a2.get(0));
- }
-
- /**
- * @tests java.util.Collections#enumeration(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "enumeration",
- args = {java.util.Collection.class}
- )
- public void test_enumerationLjava_util_Collection() {
- // Test for method java.util.Enumeration
- // java.util.Collections.enumeration(java.util.Collection)
- TreeSet ts = new TreeSet();
- ts.addAll(s);
- Enumeration e = Collections.enumeration(ts);
- int count = 0;
- while (e.hasMoreElements())
- assertTrue("Returned incorrect enumeration",
- e.nextElement() == objArray[count++]);
- assertTrue("Enumeration missing elements: " + count,
- count == objArray.length);
- }
-
- /**
- * @tests java.util.Collections#fill(java.util.List, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "fill",
- args = {java.util.List.class, java.lang.Object.class}
- )
- public void test_fillLjava_util_ListLjava_lang_Object() {
- // Test for method void java.util.Collections.fill(java.util.List,
- // java.lang.Object)
- try {
- Collections.fill(null, new Object());
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
- final int size = ll.size();
- Collections.fill(ll, "k");
- assertTrue("Fill modified list size", size == ll.size());
- Iterator i = ll.iterator();
- while (i.hasNext())
- assertEquals("Failed to fill elements", "k", i.next());
-
- Collections.fill(ll, null);
- assertTrue("Fill with nulls modified list size", size == ll.size());
- i = ll.iterator();
- while (i.hasNext())
- assertNull("Failed to fill with nulls", i.next());
-
- Mock_ArrayList mal = new Mock_ArrayList();
-
- mal.add("one");
- mal.add("two");
-
- try {
- Collections.fill(mal, "value");
- fail("UnsupportedOperationException ecpected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Collections#max(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "max",
- args = {java.util.Collection.class}
- )
- public void test_maxLjava_util_Collection() {
- // Test for method java.lang.Object
- // java.util.Collections.max(java.util.Collection)
- // assumes s, objArray are sorted
- assertTrue("Returned incorrect max element",
- Collections.max(s) == objArray[objArray.length - 1]);
-
- ArrayList al = new ArrayList();
-
- try {
- Collections.max(al);
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
-
- al.add("String");
- al.add(new Integer(1));
- al.add(new Double(3.14));
-
- try {
- Collections.max(al);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Collections#max(java.util.Collection,
- * java.util.Comparator)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "max",
- args = {java.util.Collection.class, java.util.Comparator.class}
- )
- public void test_maxLjava_util_CollectionLjava_util_Comparator() {
- // Test for method java.lang.Object
- // java.util.Collections.max(java.util.Collection, java.util.Comparator)
- // assumes s, objArray are sorted
-
- // With this custom (backwards) comparator the 'max' element should be
- // the smallest in the list
- ReversedMyIntComparator rmic = new ReversedMyIntComparator();
- assertTrue(
- "Returned incorrect max element using custom comparator",
- Collections.max(mys, rmic) == myobjArray[0]);
-
- ArrayList al = new ArrayList();
-
- try {
- Collections.max(al, rmic);
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
-
- al.add("String");
- al.add(new Integer(1));
- al.add(new Double(3.14));
-
- try {
- Collections.max(al, rmic);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Collections#min(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "min",
- args = {java.util.Collection.class}
- )
- public void test_minLjava_util_Collection() {
- // Test for method java.lang.Object
- // java.util.Collections.min(java.util.Collection)
- // assumes s, objArray are sorted
- assertTrue("Returned incorrect min element",
- Collections.min(s) == objArray[0]);
- ArrayList al = new ArrayList();
-
- try {
- Collections.min(al);
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
-
- al.add("String");
- al.add(new Integer(1));
- al.add(new Double(3.14));
-
- try {
- Collections.min(al);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Collections#min(java.util.Collection,
- * java.util.Comparator)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "min",
- args = {java.util.Collection.class, java.util.Comparator.class}
- )
- public void test_minLjava_util_CollectionLjava_util_Comparator() {
- // Test for method java.lang.Object
- // java.util.Collections.min(java.util.Collection, java.util.Comparator)
- // assumes s, objArray are sorted
-
- // With this custom (backwards) comparator the 'min' element should be
- // the largest in the list
- ReversedMyIntComparator rmic = new ReversedMyIntComparator();
-
- assertTrue(
- "Returned incorrect min element using custom comparator",
- Collections.min(mys, rmic) == myobjArray[objArray.length - 1]);
-
- ArrayList al = new ArrayList();
-
- try {
- Collections.min(al, rmic);
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
-
- al.add("String");
- al.add(new Integer(1));
- al.add(new Double(3.14));
-
- try {
- Collections.min(al, rmic);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Collections#nCopies(int, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nCopies",
- args = {int.class, java.lang.Object.class}
- )
- public void test_nCopiesILjava_lang_Object() {
- // Test for method java.util.List java.util.Collections.nCopies(int,
- // java.lang.Object)
- Object o = new Object();
- List l = Collections.nCopies(100, o);
- Iterator i = l.iterator();
- Object first = i.next();
- assertTrue("Returned list consists of copies not refs", first == o);
- assertEquals("Returned list of incorrect size", 100, l.size());
- assertTrue("Contains", l.contains(o));
- assertTrue("Contains null", !l.contains(null));
- assertTrue("null nCopies contains", !Collections.nCopies(2, null)
- .contains(o));
- assertTrue("null nCopies contains null", Collections.nCopies(2, null)
- .contains(null));
- l = Collections.nCopies(20, null);
- i = l.iterator();
- for (int counter = 0; i.hasNext(); counter++) {
- assertTrue("List is too large", counter < 20);
- assertNull("Element should be null: " + counter, i.next());
- }
- try {
- l.add(o);
- fail("Returned list is not immutable");
- } catch (UnsupportedOperationException e) {
- // Correct
- return;
- }
- try {
- Collections.nCopies(-2, new HashSet());
- fail("nCopies with negative arg didn't throw IAE");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.util.Collections#reverse(java.util.List)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reverse",
- args = {java.util.List.class}
- )
- public void test_reverseLjava_util_List() {
- // Test for method void java.util.Collections.reverse(java.util.List)
- try {
- Collections.reverse(null);
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
- Collections.reverse(ll);
- Iterator i = ll.iterator();
- int count = objArray.length - 1;
- while (i.hasNext()) {
- assertTrue("Failed to reverse collection",
- i.next() == objArray[count]);
- --count;
- }
- ArrayList myList = new ArrayList();
- myList.add(null);
- myList.add(new Integer(20));
- Collections.reverse(myList);
- assertTrue("Did not reverse correctly--first element is: "
- + myList.get(0), myList.get(0).equals(new Integer(20)));
- assertNull("Did not reverse correctly--second element is: "
- + myList.get(1), myList.get(1));
-
- Mock_ArrayList mal = new Mock_ArrayList();
-
- mal.add("First");
- mal.add("Second");
-
- try {
- Collections.reverse(mal);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Collections#reverseOrder()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reverseOrder",
- args = {}
- )
- public void test_reverseOrder() {
- // Test for method java.util.Comparator
- // java.util.Collections.reverseOrder()
- // assumes no duplicates in ll
- Comparator comp = Collections.reverseOrder();
- LinkedList list2 = new LinkedList(ll);
- Collections.sort(list2, comp);
- final int llSize = ll.size();
- for (int counter = 0; counter < llSize; counter++)
- assertTrue("New comparator does not reverse sorting order", ll
- .get(counter) == list2.get(llSize - counter - 1));
- }
-
- /**
- * @tests java.util.Collections#shuffle(java.util.List)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "shuffle",
- args = {java.util.List.class}
- )
- public void test_shuffleLjava_util_List() {
- // Test for method void java.util.Collections.shuffle(java.util.List)
- // Assumes ll is sorted and has no duplicate keys and is large ( > 20
- // elements)
-
- // test shuffling a Sequential Access List
- try {
- Collections.shuffle(null);
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
- ArrayList al = new ArrayList();
- al.addAll(ll);
- testShuffle(al, "Sequential Access", false);
-
- // test shuffling a Random Access List
- LinkedList ll2 = new LinkedList();
- ll2.addAll(ll);
- testShuffle(ll2, "Random Access", false);
-
- Mock_ArrayList mal = new Mock_ArrayList();
-
- mal.add("First");
- mal.add("Second");
-
- try {
- Collections.shuffle(mal);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- private void testShuffle(List list, String type, boolean random) {
- boolean sorted = true;
- boolean allMatch = true;
- int index = 0;
- final int size = list.size();
-
- if (random)
- Collections.shuffle(list);
- else
- Collections.shuffle(list, new Random(200));
-
- for (int counter = 0; counter < size - 1; counter++) {
- if (((Integer) list.get(counter)).compareTo((Integer)list.get(counter + 1)) > 0) {
- sorted = false;
- }
- }
- assertTrue("Shuffling sorted " + type
- + " list resulted in sorted list (should be unlikely)", !sorted);
- for (int counter = 0; counter < 20; counter++) {
- index = 30031 * counter % (size + 1); // 30031 is a large prime
- if (list.get(index) != ll.get(index))
- allMatch = false;
- }
- assertTrue("Too many element positions match in shuffled " + type
- + " list", !allMatch);
- }
-
- /**
- * @tests java.util.Collections#shuffle(java.util.List, java.util.Random)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "shuffle",
- args = {java.util.List.class, java.util.Random.class}
- )
- public void test_shuffleLjava_util_ListLjava_util_Random() {
- // Test for method void java.util.Collections.shuffle(java.util.List,
- // java.util.Random)
- // Assumes ll is sorted and has no duplicate keys and is large ( > 20
- // elements)
-
- // test shuffling a Sequential Access List
- try {
- Collections.shuffle(null, new Random(200));
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
- ArrayList al = new ArrayList();
- al.addAll(ll);
- testShuffle(al, "Sequential Access", true);
-
- // test shuffling a Random Access List
- LinkedList ll2 = new LinkedList();
- ll2.addAll(ll);
- testShuffle(ll2, "Random Access", true);
-
-
- Mock_ArrayList mal = new Mock_ArrayList();
-
- mal.add("First");
- mal.add("Second");
-
- try {
- Collections.shuffle(mal, new Random(200));
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
-}
-
- /**
- * @tests java.util.Collections#singleton(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "singleton",
- args = {java.lang.Object.class}
- )
- public void test_singletonLjava_lang_Object() {
- // Test for method java.util.Set
- // java.util.Collections.singleton(java.lang.Object)
- Object o = new Object();
- Set single = Collections.singleton(o);
- assertEquals("Wrong size", 1, single.size());
- assertTrue("Contains", single.contains(o));
- assertTrue("Contains null", !single.contains(null));
- assertTrue("null nCopies contains", !Collections.singleton(null)
- .contains(o));
- assertTrue("null nCopies contains null", Collections.singleton(null)
- .contains(null));
- try {
- single.add("l");
- } catch (UnsupportedOperationException e) {
- // Correct
- return;
- }
- fail("Allowed modification of singleton");
- }
-
- /**
- * @tests java.util.Collections#sort(java.util.List)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {java.util.List.class}
- )
- public void test_sortLjava_util_List() {
- // Test for method void java.util.Collections.sort(java.util.List)
- // assumes no duplicate keys in ll
- final int llSize = ll.size();
- final int rllSize = reversedLinkedList.size();
- try {
- Collections.sort((List)null);
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
- Collections.shuffle(ll);
- Collections.sort(ll);
- Collections.sort(reversedLinkedList);
- for (int counter = 0; counter < llSize - 1; counter++) {
- assertTrue(
- "Sorting shuffled list resulted in unsorted list",
- ((Integer) ll.get(counter)).compareTo((Integer)ll.get(counter + 1)) < 0);
- }
-
- for (int counter = 0; counter < rllSize - 1; counter++) {
- assertTrue("Sorting reversed list resulted in unsorted list",
- ((Integer) reversedLinkedList.get(counter))
- .compareTo((Integer)reversedLinkedList.get(counter + 1)) < 0);
- }
-
- ArrayList al = new ArrayList();
-
- al.add("String");
- al.add(new Integer(1));
- al.add(new Double(3.14));
-
- try {
- Collections.sort(al);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- Mock_ArrayList mal = new Mock_ArrayList();
-
- mal.add("First");
- mal.add("Second");
-
- try {
- Collections.sort(mal);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Collections#sort(java.util.List, java.util.Comparator)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sort",
- args = {java.util.List.class, java.util.Comparator.class}
- )
- public void test_sortLjava_util_ListLjava_util_Comparator() {
- // Test for method void java.util.Collections.sort(java.util.List,
- // java.util.Comparator)
- Comparator comp = new ReversedMyIntComparator();
- try {
- Collections.sort(null, comp);
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
- Collections.shuffle(myll);
- Collections.sort(myll, comp);
- final int llSize = myll.size();
-
- for (int counter = 0; counter < llSize - 1; counter++) {
- assertTrue(
- "Sorting shuffled list with custom comparator resulted in unsorted list",
- ((MyInt) myll.get(counter)).compareTo((MyInt) myll
- .get(counter + 1)) >= 0);
- }
-
- ArrayList al = new ArrayList();
-
- al.add("String");
- al.add(new Integer(1));
- al.add(new Double(3.14));
-
- try {
- Collections.sort(al, comp);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- Mock_ArrayList mal = new Mock_ArrayList();
-
- mal.add(new MyInt(1));
- mal.add(new MyInt(2));
-
- try {
- Collections.sort(mal, comp);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Collections#swap(java.util.List, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "swap",
- args = {java.util.List.class, int.class, int.class}
- )
- public void test_swapLjava_util_ListII() {
- // Test for method swap(java.util.List, int, int)
-
- LinkedList smallList = new LinkedList();
- for (int i = 0; i < 10; i++) {
- smallList.add(objArray[i]);
- }
-
- // test exception cases
- try {
- Collections.swap(smallList, -1, 6);
- fail("Expected IndexOutOfBoundsException for -1");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Collections.swap(smallList, 6, -1);
- fail("Expected IndexOutOfBoundsException for -1");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Collections.swap(smallList, 6, 11);
- fail("Expected IndexOutOfBoundsException for 11");
- } catch (IndexOutOfBoundsException e) {
- }
-
- try {
- Collections.swap(smallList, 11, 6);
- fail("Expected IndexOutOfBoundsException for 11");
- } catch (IndexOutOfBoundsException e) {
- }
-
- // Ensure a NPE is thrown if the list is NULL
- try {
- Collections.swap(null, 1, 1);
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
-
- // test with valid parameters
- Collections.swap(smallList, 4, 7);
- assertEquals("Didn't Swap the element at position 4 ", new Integer(7),
- smallList.get(4));
- assertEquals("Didn't Swap the element at position 7 ", new Integer(4),
- smallList.get(7));
-
- // make sure other elements didn't get swapped by mistake
- for (int i = 0; i < 10; i++) {
- if (i != 4 && i != 7)
- assertEquals("shouldn't have swapped the element at position "
- + i, new Integer(i), smallList.get(i));
- }
- }
-
- /**
- * @tests java.util.Collections#replaceAll(java.util.List, java.lang.Object,
- * java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "replaceAll",
- args = {java.util.List.class, java.lang.Object.class, java.lang.Object.class}
- )
- public void test_replaceAllLjava_util_ListLjava_lang_ObjectLjava_lang_Object() {
- // Test for method replaceAll(java.util.List, java.lang.Object,
- // java.lang.Object)
-
- String string1 = "A-B-C-D-E-S-JF-SUB-G-H-I-J-SUBL-K-L-LIST-M-N--S-S-O-SUBLIS-P-Q-R-SUBLIST-S-T-U-V-W-X-Y-Z";
- char[] chars = string1.toCharArray();
- List list = new ArrayList();
- for (int i = 0; i < chars.length; i++) {
- list.add(new Character(chars[i]));
- }
-
- try {
- Collections.replaceAll(null, new Object(), new Object());
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
-
- // test replace for an element that is not in the list
- boolean result = Collections.replaceAll(list, new Character('1'),
- new Character('Z'));
- assertFalse("Test1: Collections.replaceAll() returned wrong result",
- result);
- assertEquals("Test2 : ReplaceAll modified the list incorrectly",
- string1, getString(list));
-
- // test replace for an element that is in the list
- result = Collections.replaceAll(list, new Character('S'),
- new Character('K'));
- assertTrue("Test3: Collections.replaceAll() returned wrong result",
- result);
- assertEquals("Test4: ReplaceAll modified the list incorrectly",
- (string1 = string1.replace('S', 'K')), getString(list));
-
- // test replace for the last element in the list
- result = Collections.replaceAll(list, new Character('Z'),
- new Character('N'));
- assertTrue("Test5: Collections.replaceAll() returned wrong result",
- result);
- assertEquals("Test6: ReplaceAll modified the list incorrectly",
- (string1 = string1.replace('Z', 'N')), getString(list));
-
- // test replace for the first element in the list
- result = Collections.replaceAll(list, new Character('A'),
- new Character('B'));
- assertTrue("Test7: Collections.replaceAll() returned wrong result",
- result);
- assertEquals("Test8: ReplaceAll modified the list incorrectly",
- (string1 = string1.replace('A', 'B')), getString(list));
-
- // test replacing elements with null
- LinkedList smallList = new LinkedList();
- for (int i = 0; i < 10; i++) {
- smallList.add(objArray[i]);
- }
- smallList.set(4, new Integer(5));
- result = Collections.replaceAll(smallList, new Integer(5), null);
- assertTrue("Test9: Collections.replaceAll() returned wrong result",
- result);
- for (int i = 0; i < smallList.size(); i++) {
- if (i == 4 || i == 5)
- assertSame("Test9: ReplaceAll didn't replace element at " + i,
- null, smallList.get(i));
- else
- assertEquals(
- "Test9: ReplaceAll shouldn't have replaced element at "
- + i, new Integer(i), smallList.get(i));
- }
-
- // test replacing null elements with another value
- result = Collections.replaceAll(smallList, null, new Integer(99));
- assertTrue("Test10: Collections.replaceAll() returned wrong result",
- result);
-
- for (int i = 0; i < smallList.size(); i++) {
- if (i == 4 || i == 5)
- assertEquals("Test10: ReplaceAll didn't replace element at "
- + i, new Integer(99), smallList.get(i));
- else
- assertEquals(
- "Test10: ReplaceAll shouldn't have replaced element at "
- + i, new Integer(i), smallList.get(i));
- }
-
- Mock_ArrayList mal = new Mock_ArrayList();
-
- mal.add("First");
- mal.add("Second");
-
- try {
- Collections.replaceAll(mal, "Second", null);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Collections#rotate(java.util.List, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies functionality, and UnsupportedOperationException.",
- method = "rotate",
- args = {java.util.List.class, int.class}
- )
- public void test_rotateLjava_util_ListI() {
- // Test for method rotate(java.util.List, int)
-
- try {
- Collections.rotate(null, 0);
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
-
- // Test rotating a Sequential Access List
- LinkedList list1 = new LinkedList();
- for (int i = 0; i < 10; i++) {
- list1.add(objArray[i]);
- }
- testRotate(list1, "Sequential Access");
-
- // Test rotating a Random Access List
- ArrayList list2 = new ArrayList();
- for (int i = 0; i < 10; i++) {
- list2.add(objArray[i]);
- }
- testRotate(list2, "Random Access");
- }
-
- private void testRotate(List list, String type) {
- // rotate with positive distance
- Collections.rotate(list, 7);
- assertEquals("Test1: rotate modified the " + type
- + " list incorrectly,", "3456789012", getString(list));
-
- // rotate with negative distance
- Collections.rotate(list, -2);
- assertEquals("Test2: rotate modified the " + type
- + " list incorrectly,", "5678901234", getString(list));
-
- // rotate sublist with negative distance
- List subList = list.subList(1, 5);
- Collections.rotate(subList, -1);
- assertEquals("Test3: rotate modified the " + type
- + " list incorrectly,", "5789601234", getString(list));
-
- // rotate sublist with positive distance
- Collections.rotate(subList, 2);
- assertEquals("Test4: rotate modified the " + type
- + " list incorrectly,", "5967801234", getString(list));
-
- // rotate with positive distance that is larger than list size
- Collections.rotate(list, 23);
- assertEquals("Test5: rotate modified the " + type
- + " list incorrectly,", "2345967801", getString(list));
-
- // rotate with negative distance that is larger than list size
- Collections.rotate(list, -23);
- assertEquals("Test6: rotate modified the " + type
- + " list incorrectly,", "5967801234", getString(list));
-
- // rotate with 0 and equivalent distances, this should make no
- // modifications to the list
- Collections.rotate(list, 0);
- assertEquals("Test7: rotate modified the " + type
- + " list incorrectly,", "5967801234", getString(list));
-
- Collections.rotate(list, -30);
- assertEquals("Test8: rotate modified the " + type
- + " list incorrectly,", "5967801234", getString(list));
-
- Collections.rotate(list, 30);
- assertEquals("Test9: rotate modified the " + type
- + " list incorrectly,", "5967801234", getString(list));
- }
-
- private String getString(List list) {
- StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < list.size(); i++) {
- buffer.append(list.get(i));
- }
- return buffer.toString();
- }
-
- /**
- * @tests java.util.Collections#rotate(java.util.List, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "rotate",
- args = {java.util.List.class, int.class}
- )
- public void test_rotate2() {
- List list = new ArrayList();
- try {
- Collections.rotate(list, 5);
- } catch (UnsupportedOperationException e) {
- fail("Unexpected UnsupportedOperationException for empty list, "
- + e);
- }
-
- list.add(0, "zero");
- list.add(1, "one");
- list.add(2, "two");
- list.add(3, "three");
- list.add(4, "four");
-
- Collections.rotate(list, Integer.MIN_VALUE);
- assertEquals("Rotated incorrectly at position 0, ", "three",
- (String) list.get(0));
- assertEquals("Rotated incorrectly at position 1, ", "four",
- (String) list.get(1));
- assertEquals("Rotated incorrectly at position 2, ", "zero",
- (String) list.get(2));
- assertEquals("Rotated incorrectly at position 3, ", "one",
- (String) list.get(3));
- assertEquals("Rotated incorrectly at position 4, ", "two",
- (String) list.get(4));
- }
-
- /**
- * @tests java.util.Collections#indexOfSubList(java.util.List,
- * java.util.List)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies boundary conditions, and NullPointerException.",
- method = "indexOfSubList",
- args = {java.util.List.class, java.util.List.class}
- )
- public void test_indexOfSubListLjava_util_ListLjava_util_List() {
- // Test for method int indexOfSubList(java.util.List, java.util.List)
- List list = new ArrayList();
- try {
- Collections.indexOfSubList(null, list);
- fail("Expected NullPointerException for null list first parameter");
- } catch (NullPointerException e) {
- }
- try {
- Collections.indexOfSubList(list, null);
- fail("Expected NullPointerException for null list second parameter");
- } catch (NullPointerException e) {
- }
-
- String string1 = "A-B-C-D-E-S-JF-SUB-G-H-I-J-SUBL-K-L-LIST-M-N--S-S-O-SUBLIS-P-Q-R-SUBLIST-S-T-U-V-W-X-Y-Z";
-
- testwithCharList(1, string1, "B", true);
- testwithCharList(2, string1, "LIST", true);
- testwithCharList(3, string1, "SUBLIST", true);
- testwithCharList(4, string1, "NONE", true);
- testwithCharList(5, string1, "END", true);
-
- // test boundary conditions:
- testwithCharList(6, "", "", true);
- testwithCharList(7, "LIST", "", true);
- testwithCharList(8, "", "SUBLIST", true);
- }
-
- /**
- * @tests java.util.Collections#indexOfSubList(java.util.List,
- * java.util.List)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "indexOfSubList",
- args = {java.util.List.class, java.util.List.class}
- )
- public void test_indexOfSubList2() {
- ArrayList sub = new ArrayList();
- sub.add(new Integer(1));
- sub.add(new Integer(2));
- sub.add(new Integer(3));
-
- ArrayList sub2 = new ArrayList();
- sub2.add(new Integer(7));
- sub2.add(new Integer(8));
-
- ArrayList src = new ArrayList();
- src.addAll(sub);
- src.addAll(sub);
- src.addAll(sub);
- src.add(new Integer(5));
- src.add(new Integer(6));
-
- // so src becomes a list like this:
- // [1, 2, 3, 1, 2, 3, 1, 2, 3, 5, 6]
-
- sub = new ArrayList(src.subList(3, 11));
- // [1, 2, 3, 1, 2, 3, 5, 6]
- assertEquals("TestA : Returned wrong indexOfSubList, ", 3, Collections
- .indexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(6, 11));
- // [1, 2, 3, 5, 6]
- assertEquals("TestB : Returned wrong indexOfSubList, ", 6, Collections
- .indexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(0, 3));
- // [1, 2, 3]
- assertEquals("TestCC : Returned wrong indexOfSubList, ", 0, Collections
- .indexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(9, 11));
- // [5, 6]
- assertEquals("TestD : Returned wrong indexOfSubList, ", 9, Collections
- .indexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(10, 11));
- // [6]
- assertEquals("TestE : Returned wrong indexOfSubList, ", 10, Collections
- .indexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(0, 11));
- // the whole list
- assertEquals("TestH : Returned wrong indexIndexOfSubList, ", 0,
- Collections.indexOfSubList(src, sub));
-
- // a non-matching list
- assertEquals("TestI : Returned wrong indexOfSubList, ", -1, Collections
- .indexOfSubList(src, sub2));
- }
-
- /**
- * @param string2
- * @param string1
- * @param index
- */
- private void testwithCharList(int count, String string1, String string2,
- boolean first) {
- char[] chars = string1.toCharArray();
- List list = new ArrayList();
- for (int i = 0; i < chars.length; i++) {
- list.add(new Character(chars[i]));
- }
- chars = string2.toCharArray();
- List sublist = new ArrayList();
- for (int i = 0; i < chars.length; i++) {
- sublist.add(new Character(chars[i]));
- }
-
- if (first)
- assertEquals("Test " + count + ": Returned wrong index:", string1
- .indexOf(string2), Collections
- .indexOfSubList(list, sublist));
- else
- assertEquals("Test " + count + ": Returned wrong index:", string1
- .lastIndexOf(string2), Collections.lastIndexOfSubList(list,
- sublist));
- }
-
- /**
- * @tests java.util.Collections#lastIndexOfSubList(java.util.List,
- * java.util.List)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException, and boundary conditions.",
- method = "lastIndexOfSubList",
- args = {java.util.List.class, java.util.List.class}
- )
- public void test_lastIndexOfSubListLjava_util_ListLjava_util_List() {
- // Test for method int lastIndexOfSubList(java.util.List,
- // java.util.List)
- String string1 = "A-B-C-D-E-S-JF-SUB-G-H-I-J-SUBL-K-L-LIST-M-N--S-S-O-SUBLIS-P-Q-R-SUBLIST-S-T-U-V-W-X-Y-Z-END";
-
- List list = new ArrayList();
- try {
- Collections.lastIndexOfSubList(null, list);
- fail("Expected NullPointerException for null list first parameter");
- } catch (NullPointerException e) {
- }
- try {
- Collections.lastIndexOfSubList(list, null);
- fail("Expected NullPointerException for null list second parameter");
- } catch (NullPointerException e) {
- }
-
- testwithCharList(1, string1, "B", false);
- testwithCharList(2, string1, "LIST", false);
- testwithCharList(3, string1, "SUBLIST", false);
- testwithCharList(4, string1, "END", false);
- testwithCharList(5, string1, "NONE", false);
-
- // test boundary conditions
- testwithCharList(6, "", "", false);
- testwithCharList(7, "LIST", "", false);
- testwithCharList(8, "", "SUBLIST", false);
- }
-
- /**
- * @tests java.util.Collections#lastIndexOfSubList(java.util.List,
- * java.util.List)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lastIndexOfSubList",
- args = {java.util.List.class, java.util.List.class}
- )
- public void test_lastIndexOfSubList2() {
- ArrayList sub = new ArrayList();
- sub.add(new Integer(1));
- sub.add(new Integer(2));
- sub.add(new Integer(3));
-
- ArrayList sub2 = new ArrayList();
- sub2.add(new Integer(7));
- sub2.add(new Integer(8));
-
- ArrayList src = new ArrayList();
- src.addAll(sub);
- src.addAll(sub);
- src.addAll(sub);
- src.add(new Integer(5));
- src.add(new Integer(6));
-
- // so src is a list like this:
- // [1, 2, 3, 1, 2, 3, 1, 2, 3, 5, 6]
-
- Collections.reverse(src);
- // it becomes like this :
- // [6, 5, 3, 2, 1, 3, 2, 1, 3, 2, 1]
-
- sub = new ArrayList(src.subList(0, 8));
- // [6, 5, 3, 2, 1, 3, 2, 1]
- assertEquals("TestA : Returned wrong lastIndexOfSubList, ", 0,
- Collections.lastIndexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(0, 5));
- // [6, 5, 3, 2, 1]
- assertEquals("TestB : Returned wrong lastIndexOfSubList, ", 0,
- Collections.lastIndexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(2, 5));
- // [3, 2, 1]
- assertEquals("TestC : Returned wrong lastIndexOfSubList, ", 8,
- Collections.lastIndexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(9, 11));
- // [2, 1]
- assertEquals("TestD : Returned wrong lastIndexOfSubList, ", 9,
- Collections.lastIndexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(10, 11));
- // [1]
- assertEquals("TestE : Returned wrong lastIndexOfSubList, ", 10,
- Collections.lastIndexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(0, 2));
- // [6, 5]
- assertEquals("TestF : Returned wrong lastIndexOfSubList, ", 0,
- Collections.lastIndexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(0, 1));
- // [6]
- assertEquals("TestG : Returned wrong lastIndexOfSubList, ", 0,
- Collections.lastIndexOfSubList(src, sub));
-
- sub = new ArrayList(src.subList(0, 11));
- // the whole list
- assertEquals("TestH : Returned wrong lastIndexOfSubList, ", 0,
- Collections.lastIndexOfSubList(src, sub));
-
- // a non-matching list
- assertEquals("TestI : Returned wrong lastIndexOfSubList, ", -1,
- Collections.lastIndexOfSubList(src, sub2));
- }
-
- /**
- * @tests java.util.Collections#list(java.util.Enumeration)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "list",
- args = {java.util.Enumeration.class}
- )
- public void test_listLjava_util_Enumeration() {
- // Test for method java.util.ArrayList list(java.util.Enumeration)
-
- Enumeration e = Collections.enumeration(ll);
- ArrayList al = Collections.list(e);
-
- int size = al.size();
- assertEquals("Wrong size", ll.size(), size);
-
- for (int i = 0; i < size; i++) {
- assertEquals("wrong element at position " + i + ",", ll.get(i), al
- .get(i));
- }
- }
-
- /**
- * @tests java.util.Collections#synchronizedCollection(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "synchronizedCollection",
- args = {java.util.Collection.class}
- )
- public void test_synchronizedCollectionLjava_util_Collection() {
- // Test for method java.util.Collection
- // java.util.Collections.synchronizedCollection(java.util.Collection)
-
- LinkedList smallList = new LinkedList();
- for (int i = 0; i < 50; i++) {
- smallList.add(objArray[i]);
- }
-
- final int numberOfLoops = 200;
- Collection synchCol = Collections.synchronizedCollection(smallList);
- // Replacing the previous line with the line below *should* cause the
- // test to fail--the collecion below isn't synchronized
- // Collection synchCol = smallList;
-
- SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker(
- synchCol, false, numberOfLoops);
- SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker(
- synchCol, true, numberOfLoops);
- Thread normalThread = new Thread(normalSynchChecker);
- Thread offsetThread = new Thread(offsetSynchChecker);
- normalThread.start();
- offsetThread.start();
- while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
- || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- }
- }
- assertTrue("Returned collection corrupted by multiple thread access",
- normalSynchChecker.getResult()
- && offsetSynchChecker.getResult());
- try {
- normalThread.join(5000);
- offsetThread.join(5000);
- } catch (InterruptedException e) {
- fail("join() interrupted");
- }
-
- synchCol.add(null);
- assertTrue("Trying to use nulls in collection failed", synchCol
- .contains(null));
-
- smallList = new LinkedList();
- for (int i = 0; i < 100; i++) {
- smallList.add(objArray[i]);
- }
- new Support_CollectionTest("", Collections
- .synchronizedCollection(smallList)).runTest();
- }
-
- /**
- * @tests java.util.Collections#synchronizedList(java.util.List)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "synchronizedList",
- args = {java.util.List.class}
- )
- public void test_synchronizedListLjava_util_List() {
- try {
- Collections.synchronizedList(null);
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
-
- // test with a Sequential Access List
- List smallList = new LinkedList();
- testSynchronizedList(smallList, "Sequential Access");
-
- smallList = new LinkedList();
- List myList;
- for (int i = 0; i < 100; i++) {
- smallList.add(objArray[i]);
- }
- myList = Collections.synchronizedList(smallList);
- new Support_ListTest("", myList).runTest();
-
- // test with a Random Access List
- smallList = new ArrayList();
- testSynchronizedList(smallList, "Random Access");
-
- smallList = new ArrayList();
- for (int i = 0; i < 100; i++) {
- smallList.add(objArray[i]);
- }
- myList = Collections.synchronizedList(smallList);
- new Support_ListTest("", myList).runTest();
- }
-
- private void testSynchronizedList(List smallList, String type) {
- for (int i = 0; i < 50; i++) {
- smallList.add(objArray[i]);
- }
- final int numberOfLoops = 200;
- List synchList = Collections.synchronizedList(smallList);
- if (type.equals("Random Access"))
- assertTrue(
- "Returned synchronized list should implement the Random Access interface",
- synchList instanceof RandomAccess);
- else
- assertTrue(
- "Returned synchronized list should not implement the Random Access interface",
- !(synchList instanceof RandomAccess));
-
- // Replacing the previous line with the line below *should* cause the
- // test to fail--the list below isn't synchronized
- // List synchList = smallList;
- SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker(
- synchList, false, numberOfLoops);
- SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker(
- synchList, true, numberOfLoops);
- Thread normalThread = new Thread(normalSynchChecker);
- Thread offsetThread = new Thread(offsetSynchChecker);
- normalThread.start();
- offsetThread.start();
- while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
- || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- }
- }
- assertTrue(
- type
- + " list tests: Returned list corrupted by multiple thread access",
- normalSynchChecker.getResult()
- && offsetSynchChecker.getResult());
- try {
- normalThread.join(5000);
- offsetThread.join(5000);
- } catch (InterruptedException e) {
- fail(type + " list tests: join() interrupted");
- }
- synchList.set(25, null);
- assertNull(type + " list tests: Trying to use nulls in list failed",
- synchList.get(25));
- }
-
- /**
- * @tests java.util.Collections#synchronizedMap(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "synchronizedMap",
- args = {java.util.Map.class}
- )
- public void test_synchronizedMapLjava_util_Map() {
- // Test for method java.util.Map
- // java.util.Collections.synchronizedMap(java.util.Map)
- HashMap smallMap = new HashMap();
- for (int i = 0; i < 50; i++) {
- smallMap.put(objArray[i], objArray[i]);
- }
-
- final int numberOfLoops = 200;
- Map synchMap = Collections.synchronizedMap(smallMap);
- // Replacing the previous line with the line below should cause the test
- // to fail--the list below isn't synchronized
- // Map synchMap = smallMap;
-
- SynchMapChecker normalSynchChecker = new SynchMapChecker(synchMap,
- false, numberOfLoops);
- SynchMapChecker offsetSynchChecker = new SynchMapChecker(synchMap,
- true, numberOfLoops);
- Thread normalThread = new Thread(normalSynchChecker);
- Thread offsetThread = new Thread(offsetSynchChecker);
- normalThread.start();
- offsetThread.start();
- while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
- || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- }
- }
- assertTrue("Returned map corrupted by multiple thread access",
- normalSynchChecker.getResult()
- && offsetSynchChecker.getResult());
- try {
- normalThread.join(5000);
- offsetThread.join(5000);
- } catch (InterruptedException e) {
- fail("join() interrupted");
- }
-
- // synchronized map does not have to permit null keys or values
- synchMap.put(new Long(25), null);
- synchMap.put(null, new Long(30));
- assertNull("Trying to use a null value in map failed", synchMap
- .get(new Long(25)));
- assertTrue("Trying to use a null key in map failed", synchMap.get(null)
- .equals(new Long(30)));
-
- smallMap = new HashMap();
- for (int i = 0; i < 100; i++) {
- smallMap.put(objArray[i].toString(), objArray[i]);
- }
- synchMap = Collections.synchronizedMap(smallMap);
- new Support_UnmodifiableMapTest("", synchMap).runTest();
- synchMap.keySet().remove(objArray[50].toString());
- assertNull(
- "Removing a key from the keySet of the synchronized map did not remove it from the synchronized map: ",
- synchMap.get(objArray[50].toString()));
- assertNull(
- "Removing a key from the keySet of the synchronized map did not remove it from the original map",
- smallMap.get(objArray[50].toString()));
- }
-
- /**
- * @tests java.util.Collections#synchronizedSet(java.util.Set)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "synchronizedSet",
- args = {java.util.Set.class}
- )
- public void test_synchronizedSetLjava_util_Set() {
- // Test for method java.util.Set
- // java.util.Collections.synchronizedSet(java.util.Set)
- HashSet smallSet = new HashSet();
- for (int i = 0; i < 50; i++) {
- smallSet.add(objArray[i]);
- }
-
- final int numberOfLoops = 200;
- Set synchSet = Collections.synchronizedSet(smallSet);
- // Replacing the previous line with the line below should cause the test
- // to fail--the set below isn't synchronized
- // Set synchSet = smallSet;
-
- SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker(
- synchSet, false, numberOfLoops);
- SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker(
- synchSet, true, numberOfLoops);
- Thread normalThread = new Thread(normalSynchChecker);
- Thread offsetThread = new Thread(offsetSynchChecker);
- normalThread.start();
- offsetThread.start();
- while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
- || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- }
- }
- assertTrue("Returned set corrupted by multiple thread access",
- normalSynchChecker.getResult()
- && offsetSynchChecker.getResult());
- try {
- normalThread.join(5000);
- offsetThread.join(5000);
- } catch (InterruptedException e) {
- fail("join() interrupted");
- }
-
- Set mySet = Collections.synchronizedSet(smallSet);
- mySet.add(null);
- assertTrue("Trying to use nulls in list failed", mySet.contains(null));
-
- smallSet = new HashSet();
- for (int i = 0; i < 100; i++) {
- smallSet.add(objArray[i]);
- }
- new Support_SetTest("", Collections.synchronizedSet(smallSet))
- .runTest();
- }
-
- /**
- * @tests java.util.Collections#synchronizedSortedMap(java.util.SortedMap)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "synchronizedSortedMap",
- args = {java.util.SortedMap.class}
- )
- public void test_synchronizedSortedMapLjava_util_SortedMap() {
- // Test for method java.util.SortedMap
- // java.util.Collections.synchronizedSortedMap(java.util.SortedMap)
- TreeMap smallMap = new TreeMap();
- for (int i = 0; i < 50; i++) {
- smallMap.put(objArray[i], objArray[i]);
- }
-
- final int numberOfLoops = 200;
- Map synchMap = Collections.synchronizedMap(smallMap);
- // Replacing the previous line with the line below should cause the test
- // to fail--the list below isn't synchronized
- // Map synchMap = smallMap;
-
- SynchMapChecker normalSynchChecker = new SynchMapChecker(synchMap,
- false, numberOfLoops);
- SynchMapChecker offsetSynchChecker = new SynchMapChecker(synchMap,
- true, numberOfLoops);
- Thread normalThread = new Thread(normalSynchChecker);
- Thread offsetThread = new Thread(offsetSynchChecker);
- normalThread.start();
- offsetThread.start();
- while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
- || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- }
- }
- assertTrue("Returned map corrupted by multiple thread access",
- normalSynchChecker.getResult()
- && offsetSynchChecker.getResult());
- try {
- normalThread.join(5000);
- offsetThread.join(5000);
- } catch (InterruptedException e) {
- fail("join() interrupted");
- }
-
- smallMap = new TreeMap();
- for (int i = 0; i < 100; i++) {
- smallMap.put(objArray[i].toString(), objArray[i]);
- }
- synchMap = Collections.synchronizedSortedMap(smallMap);
- new Support_UnmodifiableMapTest("", synchMap).runTest();
- synchMap.keySet().remove(objArray[50].toString());
- assertNull(
- "Removing a key from the keySet of the synchronized map did not remove it from the synchronized map",
- synchMap.get(objArray[50].toString()));
- assertNull(
- "Removing a key from the keySet of the synchronized map did not remove it from the original map",
- smallMap.get(objArray[50].toString()));
- }
-
- /**
- * @tests java.util.Collections#synchronizedSortedSet(java.util.SortedSet)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "synchronizedSortedSet",
- args = {java.util.SortedSet.class}
- )
- public void test_synchronizedSortedSetLjava_util_SortedSet() {
- // Test for method java.util.SortedSet
- // java.util.Collections.synchronizedSortedSet(java.util.SortedSet)
- TreeSet smallSet = new TreeSet();
- for (int i = 0; i < 50; i++) {
- smallSet.add(objArray[i]);
- }
-
- final int numberOfLoops = 200;
- Set synchSet = Collections.synchronizedSet(smallSet);
- // Replacing the previous line with the line below should cause the test
- // to fail--the list below isn't synchronized
- // Set synchSet = smallSet;
-
- SynchCollectionChecker normalSynchChecker = new SynchCollectionChecker(
- synchSet, false, numberOfLoops);
- SynchCollectionChecker offsetSynchChecker = new SynchCollectionChecker(
- synchSet, true, numberOfLoops);
- Thread normalThread = new Thread(normalSynchChecker);
- Thread offsetThread = new Thread(offsetSynchChecker);
- normalThread.start();
- offsetThread.start();
- while ((normalSynchChecker.getNumberOfChecks() < numberOfLoops)
- || (offsetSynchChecker.getNumberOfChecks() < numberOfLoops)) {
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- }
- }
- assertTrue("Returned set corrupted by multiple thread access",
- normalSynchChecker.getResult()
- && offsetSynchChecker.getResult());
- try {
- normalThread.join(5000);
- offsetThread.join(5000);
- } catch (InterruptedException e) {
- fail("join() interrupted");
- }
- }
-
- /**
- * @tests java.util.Collections#unmodifiableCollection(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "unmodifiableCollection",
- args = {java.util.Collection.class}
- )
- public void test_unmodifiableCollectionLjava_util_Collection() {
- // Test for method java.util.Collection
- // java.util.Collections.unmodifiableCollection(java.util.Collection)
- boolean exception = false;
- Collection c = Collections.unmodifiableCollection(ll);
- assertTrue("Returned collection is of incorrect size", c.size() == ll
- .size());
- Iterator i = ll.iterator();
- while (i.hasNext())
- assertTrue("Returned list missing elements", c.contains(i.next()));
- try {
- c.add(new Object());
- } catch (UnsupportedOperationException e) {
- exception = true;
- // Correct
- }
- if (!exception) {
- fail("Allowed modification of collection");
- }
-
- try {
- c.remove(new Object());
- fail("Allowed modification of collection");
- } catch (UnsupportedOperationException e) {
- // Correct
- }
-
- Collection myCollection = new ArrayList();
- myCollection.add(new Integer(20));
- myCollection.add(null);
- c = Collections.unmodifiableCollection(myCollection);
- assertTrue("Collection should contain null", c.contains(null));
- assertTrue("Collection should contain Integer(20)", c
- .contains(new Integer(20)));
-
- myCollection = new ArrayList();
- for (int counter = 0; counter < 100; counter++) {
- myCollection.add(objArray[counter]);
- }
- new Support_UnmodifiableCollectionTest("", Collections
- .unmodifiableCollection(myCollection)).runTest();
- }
-
- /**
- * @tests java.util.Collections#unmodifiableList(java.util.List)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "unmodifiableList",
- args = {java.util.List.class}
- )
- public void test_unmodifiableListLjava_util_List() {
- // Test for method java.util.List
- // java.util.Collections.unmodifiableList(java.util.List)
-
- // test with a Sequential Access List
- boolean exception = false;
- List c = Collections.unmodifiableList(ll);
- // Ensure a NPE is thrown if the list is NULL
- try {
- Collections.unmodifiableList(null);
- fail("Expected NullPointerException for null list parameter");
- } catch (NullPointerException e) {
- }
-
- assertTrue("Returned list is of incorrect size", c.size() == ll.size());
- assertTrue(
- "Returned List should not implement Random Access interface",
- !(c instanceof RandomAccess));
-
- Iterator i = ll.iterator();
- while (i.hasNext())
- assertTrue("Returned list missing elements", c.contains(i.next()));
- try {
- c.add(new Object());
- } catch (UnsupportedOperationException e) {
- exception = true;
- // Correct
- }
- if (!exception) {
- fail("Allowed modification of list");
- }
-
- try {
- c.remove(new Object());
- fail("Allowed modification of list");
- } catch (UnsupportedOperationException e) {
- // Correct
- }
-
- // test with a Random Access List
- List smallList = new ArrayList();
- smallList.add(null);
- smallList.add("yoink");
- c = Collections.unmodifiableList(smallList);
- assertNull("First element should be null", c.get(0));
- assertTrue("List should contain null", c.contains(null));
- assertTrue(
- "T1. Returned List should implement Random Access interface",
- c instanceof RandomAccess);
-
- smallList = new ArrayList();
- for (int counter = 0; counter < 100; counter++) {
- smallList.add(objArray[counter]);
- }
- List myList = Collections.unmodifiableList(smallList);
- assertTrue("List should not contain null", !myList.contains(null));
- assertTrue(
- "T2. Returned List should implement Random Access interface",
- myList instanceof RandomAccess);
-
- assertTrue("get failed on unmodifiable list", myList.get(50).equals(
- new Integer(50)));
- ListIterator listIterator = myList.listIterator();
- for (int counter = 0; listIterator.hasNext(); counter++) {
- assertTrue("List has wrong elements", ((Integer) listIterator
- .next()).intValue() == counter);
- }
- new Support_UnmodifiableCollectionTest("", smallList).runTest();
- }
-
- /**
- * @tests java.util.Collections#unmodifiableMap(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "unmodifiableMap",
- args = {java.util.Map.class}
- )
- public void test_unmodifiableMapLjava_util_Map() {
- // Test for method java.util.Map
- // java.util.Collections.unmodifiableMap(java.util.Map)
- boolean exception = false;
- Map c = Collections.unmodifiableMap(hm);
- assertTrue("Returned map is of incorrect size", c.size() == hm.size());
- Iterator i = hm.keySet().iterator();
- while (i.hasNext()) {
- Object x = i.next();
- assertTrue("Returned map missing elements", c.get(x).equals(
- hm.get(x)));
- }
- try {
- c.put(new Object(), "");
- } catch (UnsupportedOperationException e) {
- exception = true;
- // Correct
- }
- assertTrue("Allowed modification of map", exception);
-
- exception = false;
- try {
- c.remove(new Object());
- } catch (UnsupportedOperationException e) {
- // Correct
- exception = true;
- }
- assertTrue("Allowed modification of map", exception);
-
- exception = false;
- Iterator it = c.entrySet().iterator();
- Map.Entry entry = (Map.Entry) it.next();
- try {
- entry.setValue("modified");
- } catch (UnsupportedOperationException e) {
- // Correct
- exception = true;
- }
- assertTrue("Allowed modification of entry", exception);
-
- exception = false;
- Object[] array = c.entrySet().toArray();
- try {
- ((Map.Entry) array[0]).setValue("modified");
- } catch (UnsupportedOperationException e) {
- // Correct
- exception = true;
- }
- assertTrue("Allowed modification of array entry", exception);
-
- exception = false;
- Map.Entry[] array2 = (Map.Entry[]) c.entrySet().toArray(
- new Map.Entry[0]);
- try {
- array2[0].setValue("modified");
- } catch (UnsupportedOperationException e) {
- // Correct
- exception = true;
- }
- assertTrue("Allowed modification of array entry2", exception);
-
- HashMap smallMap = new HashMap();
- smallMap.put(null, new Long(30));
- smallMap.put(new Long(25), null);
- Map unmodMap = Collections.unmodifiableMap(smallMap);
-
- assertNull("Trying to use a null value in map failed", unmodMap
- .get(new Long(25)));
- assertTrue("Trying to use a null key in map failed", unmodMap.get(null)
- .equals(new Long(30)));
-
- smallMap = new HashMap();
- for (int counter = 0; counter < 100; counter++) {
- smallMap.put(objArray[counter].toString(), objArray[counter]);
- }
- unmodMap = Collections.unmodifiableMap(smallMap);
- new Support_UnmodifiableMapTest("", unmodMap).runTest();
-
- }
-
- /**
- * @tests java.util.Collections#unmodifiableSet(java.util.Set)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "unmodifiableSet",
- args = {java.util.Set.class}
- )
- public void test_unmodifiableSetLjava_util_Set() {
- // Test for method java.util.Set
- // java.util.Collections.unmodifiableSet(java.util.Set)
- boolean exception = false;
- Set c = Collections.unmodifiableSet(s);
- assertTrue("Returned set is of incorrect size", c.size() == s.size());
- Iterator i = ll.iterator();
- while (i.hasNext())
- assertTrue("Returned set missing elements", c.contains(i.next()));
- try {
- c.add(new Object());
- } catch (UnsupportedOperationException e) {
- exception = true;
- // Correct
- }
- if (!exception) {
- fail("Allowed modification of set");
- }
- try {
- c.remove(new Object());
- fail("Allowed modification of set");
- } catch (UnsupportedOperationException e) {
- // Correct
- }
-
- Set mySet = Collections.unmodifiableSet(new HashSet());
- assertTrue("Should not contain null", !mySet.contains(null));
- mySet = Collections.unmodifiableSet(Collections.singleton(null));
- assertTrue("Should contain null", mySet.contains(null));
-
- mySet = new TreeSet();
- for (int counter = 0; counter < 100; counter++) {
- mySet.add(objArray[counter]);
- }
- new Support_UnmodifiableCollectionTest("", Collections
- .unmodifiableSet(mySet)).runTest();
- }
-
- /**
- * @tests java.util.Collections#unmodifiableSortedMap(java.util.SortedMap)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "unmodifiableSortedMap",
- args = {java.util.SortedMap.class}
- )
- public void test_unmodifiableSortedMapLjava_util_SortedMap() {
- // Test for method java.util.SortedMap
- // java.util.Collections.unmodifiableSortedMap(java.util.SortedMap)
- boolean exception = false;
- TreeMap tm = new TreeMap();
- tm.putAll(hm);
- Map c = Collections.unmodifiableSortedMap(tm);
- assertTrue("Returned map is of incorrect size", c.size() == tm.size());
- Iterator i = hm.keySet().iterator();
- while (i.hasNext()) {
- Object x = i.next();
- assertTrue("Returned map missing elements", c.get(x).equals(
- tm.get(x)));
- }
- try {
- c.put(new Object(), "");
- } catch (UnsupportedOperationException e) {
- exception = true;
- // Correct
- }
-
- if (!exception) {
- fail("Allowed modification of map");
- }
- try {
- c.remove(new Object());
- } catch (UnsupportedOperationException e) {
- // Correct
- return;
- }
- fail("Allowed modification of map");
- }
-
- /**
- * @tests java.util.Collections#unmodifiableSortedSet(java.util.SortedSet)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "unmodifiableSortedSet",
- args = {java.util.SortedSet.class}
- )
- public void test_unmodifiableSortedSetLjava_util_SortedSet() {
- // Test for method java.util.SortedSet
- // java.util.Collections.unmodifiableSortedSet(java.util.SortedSet)
- boolean exception = false;
- SortedSet ss = new TreeSet();
- ss.addAll(s);
- SortedSet c = Collections.unmodifiableSortedSet(ss);
- assertTrue("Returned set is of incorrect size", c.size() == ss.size());
- Iterator i = ll.iterator();
- while (i.hasNext())
- assertTrue("Returned set missing elements", c.contains(i.next()));
- try {
- c.add(new Object());
- } catch (UnsupportedOperationException e) {
- exception = true;
- // Correct
- }
- if (!exception) {
- fail("Allowed modification of set");
- }
- try {
- c.remove(new Object());
- } catch (UnsupportedOperationException e) {
- // Correct
- return;
- }
- fail("Allowed modification of set");
- }
-
- /**
- * Test unmodifiable objects toString methods
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unmodifiableCollection",
- args = {java.util.Collection.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "unmodifiableMap",
- args = {java.util.Map.class}
- )
- })
- public void test_unmodifiable_toString_methods() {
- // Regression for HARMONY-552
- ArrayList al = new ArrayList();
- al.add("a");
- al.add("b");
- Collection uc = Collections.unmodifiableCollection(al);
- assertEquals("[a, b]", uc.toString());
- HashMap m = new HashMap();
- m.put("one", "1");
- m.put("two", "2");
- Map um = Collections.unmodifiableMap(m);
- assertEquals("{one=1, two=2}", um.toString());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "singletonList",
- args = {java.lang.Object.class}
- )
- public void test_singletonListLjava_lang_Object() {
- // Test for method java.util.Set
- // java.util.Collections.singleton(java.lang.Object)
- String str = "Singleton";
-
- List single = Collections.singletonList(str);
- assertEquals(1, single.size());
- assertTrue(single.contains(str));
- assertFalse(single.contains(null));
- assertFalse(Collections.singletonList(null).contains(str));
- assertTrue(Collections.singletonList(null).contains(null));
-
- try {
- single.add("New element");
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "singletonMap",
- args = {java.lang.Object.class, java.lang.Object.class}
- )
- public void test_singletonMapLjava_lang_Object() {
- // Test for method java.util.Set
- // java.util.Collections.singleton(java.lang.Object)
- Double key = new Double (3.14);
- String value = "Fundamental constant";
-
- Map single = Collections.singletonMap(key, value);
- assertEquals(1, single.size());
- assertTrue(single.containsKey(key));
- assertTrue(single.containsValue(value));
- assertFalse(single.containsKey(null));
- assertFalse(single.containsValue(null));
- assertFalse(Collections.singletonMap(null, null).containsKey(key));
- assertFalse(Collections.singletonMap(null, null).containsValue(value));
- assertTrue(Collections.singletonMap(null, null).containsKey(null));
- assertTrue(Collections.singletonMap(null, null).containsValue(null));
-
- try {
- single.clear();
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
-
- try {
- single.put(new Double(1), "one wrong value");
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- ll = new LinkedList();
- myll = new LinkedList();
- s = new HashSet();
- mys = new HashSet();
- reversedLinkedList = new LinkedList(); // to be sorted in reverse order
- myReversedLinkedList = new LinkedList(); // to be sorted in reverse
- // order
- hm = new HashMap();
- for (int i = 0; i < objArray.length; i++) {
- ll.add(objArray[i]);
- myll.add(myobjArray[i]);
- s.add(objArray[i]);
- mys.add(myobjArray[i]);
- reversedLinkedList.add(objArray[objArray.length - i - 1]);
- myReversedLinkedList.add(myobjArray[myobjArray.length - i - 1]);
- hm.put(objArray[i].toString(), objArray[i]);
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-
- protected void doneSuite() {
- objArray = null;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/ConcurrentModTest.java b/luni/src/test/java/tests/api/java/util/ConcurrentModTest.java
deleted file mode 100644
index ffa68d3..0000000
--- a/luni/src/test/java/tests/api/java/util/ConcurrentModTest.java
+++ /dev/null
@@ -1,753 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.AbstractList;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.ConcurrentModificationException;
-import java.util.List;
-import java.util.Vector;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(AbstractList.class)
-public class ConcurrentModTest extends TestCase {
-
- /*
- * Test method for 'java.util.AbstractList.subList(int, int)'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Doesn't verify IndexOutOfBoundsException.",
- method = "get",
- args = {int.class}
- )
- public void testGet() {
- AbstractList al = new ArrayList();
- Double one = new Double(1.0);
- Double two = new Double(2.0);
- Double three = new Double(3.0);
- Double four = new Double(4.0);
- al.add(one);
- al.add(two);
- al.add(three);
- al.add(four);
- List sub = al.subList(1, 3);
- assertEquals(2, sub.size());
- // the sub.get(1) is 3.0
- assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0);
- assertTrue(((Double) sub.get(1)).doubleValue() > 2.0);
-
- al.remove(1); // remove the 2.0
-
- try {
- // illegal call the subList's method get(int).
- sub.get(1);
- fail("It should throws ConcurrentModificationException.");
- } catch (ConcurrentModificationException e) {
- return;
- }
-
- try {
- al.get(-1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
-
- try {
- al.get(al.size()+1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
- }
-
- /*
- * Test method for 'java.util.AbstractList.subList(int, int)'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify UnsupportedOperationException, ClassCastException, IllegalArgumentException, IndexOutOfBoundsException.",
- method = "set",
- args = {int.class, java.lang.Object.class}
- )
- public void testSet() {
- AbstractList al = new ArrayList();
- Double one = new Double(1.0);
- Double two = new Double(2.0);
- Double three = new Double(3.0);
- Double four = new Double(4.0);
- al.add(one);
- al.add(two);
- al.add(three);
- al.add(four);
- List sub = al.subList(1, 3);
- assertEquals(2, sub.size());
- // the sub.get(1) is 3.0
- assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0);
- assertTrue(((Double) sub.get(1)).doubleValue() > 2.0);
-
- al.remove(1); // remove the 2.0
-
- try {
- // illegal call the subList's method set(int,Object).
- sub.set(1, two);
- fail("It should throws ConcurrentModificationException.");
- } catch (ConcurrentModificationException e) {
- return;
- }
- }
-
- /*
- * Test method for 'java.util.AbstractList.subList(int, int)'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify UnsupportedOperationException, ClassCastException, IllegalArgumentException, IndexOutOfBoundsException.",
- method = "add",
- args = {java.lang.Object.class}
- )
- public void testAdd() {
- AbstractList al = new ArrayList();
- Double one = new Double(1.0);
- Double two = new Double(2.0);
- Double three = new Double(3.0);
- Double four = new Double(4.0);
- al.add(one);
- al.add(two);
- al.add(three);
- al.add(four);
- List sub = al.subList(1, 3);
- assertEquals(2, sub.size());
- // the sub.get(1) is 3.0
- assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0);
- assertTrue(((Double) sub.get(1)).doubleValue() > 2.0);
-
- al.remove(1); // remove the 2.0
-
- try {
- // illegal call the subList's method Add(int,Object).
- sub.add(1, two);
- fail("It should throws ConcurrentModificationException.");
- } catch (ConcurrentModificationException e) {
- return;
- }
- }
-
- /*
- * Test method for 'java.util.AbstractList.subList(int, int)'
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {int.class}
- )
- public void testRemove() {
- AbstractList al = new ArrayList();
- Double one = new Double(1.0);
- Double two = new Double(2.0);
- Double three = new Double(3.0);
- Double four = new Double(4.0);
- al.add(one);
- al.add(two);
- al.add(three);
- al.add(four);
- List sub = al.subList(1, 3);
- assertEquals(2, sub.size());
- // the sub.get(1) is 3.0
- assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0);
- assertTrue(((Double) sub.get(1)).doubleValue() > 2.0);
-
- al.remove(1); // remove the 2.0
-
- try {
- // illegal call the subList's method remove(int).
- sub.remove(1);
- fail("It should throws ConcurrentModificationException.");
- } catch (ConcurrentModificationException e) {
- return;
- }
-
- try {
- sub.remove(-1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
-
- try {
- sub.remove(sub.size() + 1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
-
- al = new AbstractList() {
-
- @Override
- public Object get(int index) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public int size() {
- // TODO Auto-generated method stub
- return 0;
- }
- };
-
- try {
- al.remove(1);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException ee) {
- //expected
- }
- }
-
- /*
- * Test method for 'java.util.AbstractList.subList(int, int)'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify UnsupportedOperationException, ClassCastException, IllegalArgumentException, NullPointerException.",
- method = "addAll",
- args = {int.class, java.util.Collection.class}
- )
- public void testAddAll() {
- AbstractList al = new ArrayList();
- Double one = new Double(1.0);
- Double two = new Double(2.0);
- Double three = new Double(3.0);
- Double four = new Double(4.0);
- al.add(one);
- al.add(two);
- al.add(three);
- al.add(four);
- List sub = al.subList(1, 3);
- assertEquals(2, sub.size());
- // the sub.get(1) is 3.0
- assertTrue(((Double) sub.get(1)).doubleValue() <= 3.0);
- assertTrue(((Double) sub.get(1)).doubleValue() > 2.0);
-
- al.remove(1); // remove the 2.0
-
- try {
- // illegal call the subList's method addAll(int,Collection).
- Collection c = new Vector();
- Double five = new Double(5.0);
- c.add(five);
- sub.addAll(1, c);
- fail("It should throws ConcurrentModificationException.");
- } catch (ConcurrentModificationException e) {
- return;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Class is abstract - test testing simplest implementation.",
- method = "add",
- args = {java.lang.Object.class}
- )
- public void test_addLjava_lang_Object() {
- AbstractList abstr = new AbstractList() {
-
- @Override
- public Object get(int arg0) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
-
- };
-
- try {
- abstr.add(null);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //ecpected
- }
- abstr = new AbstractList<Double>() {
- @Override
- public boolean add(Double value) {
- return true;
- }
-
- @Override
- public Double get(int index) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- try {
- abstr.add(1);
- fail("ClassCastException expected");
- } catch (ClassCastException ee) {
- //expected
- }
-
- abstr = new AbstractList<Integer>() {
- final int forbiddenValue = 33;
- @Override
- public boolean add(Integer value) {
- if (value == forbiddenValue) {
- throw new IllegalArgumentException();
- }
- return true;
- }
-
- @Override
- public Integer get(int index) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- abstr.add(1);
- try {
- abstr.add(33);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ee) {
- //expected
- }
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "add",
- args = {int.class, java.lang.Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AbstractList",
- args = {}
- )
- })
- public void test_addILjava_lang_Object() {
- AbstractList abstr = new AbstractList() {
-
- @Override
- public Object get(int arg0) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
-
- };
-
- try {
- abstr.add(1, null);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //ecpected
- }
- abstr = new AbstractList<Double>() {
- @Override
- public void add(int index, Double value) {
- }
-
- @Override
- public Double get(int index) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- try {
- abstr.add(1, 1);
- fail("ClassCastException expected");
- } catch (ClassCastException ee) {
- //expected
- }
-
- abstr = new AbstractList<Integer>() {
- final int forbiddenValue = 33;
- @Override
- public void add(int index, Integer value) {
- if (value == forbiddenValue) {
- throw new IllegalArgumentException();
- }
- }
-
- @Override
- public Integer get(int index) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- abstr.add(1, 1);
- try {
- abstr.add(1, 33);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ee) {
- //expected
- }
-
- abstr = new ArrayList();
-
- abstr.add(0, "element");
- abstr.add(1, null);
- abstr.add(2, 1);
- abstr.add(3, new Double(33));
-
- try {
- abstr.add(-3, new Double(33));
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
-
- try {
- abstr.add(abstr.size() + 1, new Double(33));
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addAll",
- args = {int.class, java.util.Collection.class}
- )
- public void test_addAllILjava_util_Collection() {
- Collection c = new Vector();
- c.add(new Double(33));
- c.add(10);
- c.add("String");
-
- AbstractList abstr = new AbstractList() {
- @Override
- public Object get(int arg0) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- try {
- abstr.addAll(0, null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- try {
- abstr.addAll(0, c);
- fail("UnsuportedOperationException expected");
- } catch (UnsupportedOperationException ee) {
- //expected
- }
-
- abstr = new AbstractList<Double>() {
- @Override
- public void add(int index, Double value) {
- }
-
- @Override
- public Double get(int arg0) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- try {
- abstr.addAll(0, c);
- fail("ClassCastException expected");
- } catch (ClassCastException ee) {
- //expectd
- }
-
- abstr = new AbstractList<Integer>() {
- final int forbiddenValue = 33;
- @Override
- public void add(int index, Integer value) {
- if (value == forbiddenValue) {
- throw new IllegalArgumentException();
- }
- }
-
- @Override
- public Integer get(int arg0) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
- c.clear();
- c.add(new Integer(1));
- c.add(new Integer(2));
- c.add(new Integer(3));
- c.add(new Integer(4));
- c.add(new Integer(5));
-
- abstr.addAll(0, c);
-
- c.add(new Integer(33));
-
- try {
- abstr.addAll(0, c);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ee) {
- //expected
- }
- abstr = new ArrayList();
- abstr.addAll(0, c);
-
- try {
- abstr.addAll(-1, c);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
-
- try {
- abstr.addAll(abstr.size() + 1, c);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- AbstractList abstr = new ArrayList();
-
- assertEquals(0, abstr.size());
- abstr.add("String");
- abstr.add("1");
- abstr.add(2);
- abstr.add(new Double(3));
- assertEquals(4, abstr.size());
- abstr.clear();
- assertEquals(0, abstr.size());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- Collection c = new Vector();
- c.add(new Double(33));
- c.add(10);
- c.add("String");
-
- AbstractList abstr = new ArrayList();
- AbstractList abstr1 = new ArrayList();
-
- assertFalse(abstr.equals(this));
- abstr.add(new Double(33));
- abstr.add(10);
- abstr.add("String");
- assertTrue(abstr.equals(c));
- abstr1.addAll(c);
- assertTrue(abstr.equals(abstr1));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "set",
- args = {int.class, java.lang.Object.class}
- )
- public void test_setILjava_lang_Object() {
- Collection c = new Vector();
- c.add(new Double(33));
- c.add(10);
- c.add("String");
-
- AbstractList abstr1 = new ArrayList();
- AbstractList abstr2 = new ArrayList();
-
- abstr1.addAll(c);
- abstr2.addAll(c);
- assertTrue(abstr1.equals(abstr2));
- abstr1.set(1, 1);
- assertFalse(abstr1.equals(abstr2));
-
- try {
- abstr1.set(abstr1.size() + 1, 1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
-
- try {
- abstr1.set(-1, 1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException ee) {
- //expected
- }
-
- AbstractList abstr = new AbstractList() {
-
- @Override
- public Object get(int index) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
-
- };
-
- try {
- abstr.set(0, null);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException ee) {
- //expected
- }
-
- abstr = new AbstractList<Double>() {
- @Override
- public Double set(int index, Double value) {
- return value;
- }
-
- @Override
- public Double get(int index) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- try {
- abstr.set(0, 1);
- fail("ClassCastException expected");
- } catch (ClassCastException ee) {
- //expected
- }
-
- abstr = new AbstractList<Integer>() {
- final int forbiddenValue = 33;
- @Override
- public Integer set(int index, Integer value) {
- if (value == forbiddenValue) {
- throw new IllegalArgumentException();
- }
- return value;
- }
-
- @Override
- public Integer get(int index) {
- return null;
- }
-
- @Override
- public int size() {
- return 0;
- }
- };
-
- try {
- abstr.set(0, 33);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ee) {
- //expected
- }
- }
- class Mock_ArrayList extends ArrayList {
- @Override
- public void removeRange(int fromIndex, int toIndex) {
- super.removeRange(fromIndex, toIndex);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "removeRange",
- args = {int.class, int.class}
- )
- public void test_removeRangeII() {
- Mock_ArrayList al1 = new Mock_ArrayList();
- al1.add(1);
- al1.add(2);
- al1.add(3);
- al1.add(4);
- al1.add(5);
- Mock_ArrayList al2 = new Mock_ArrayList();
-
- al2.add(1);
- al2.add(5);
- assertNotSame(al1,al2);
- al1.removeRange(1, 4);
- assertEquals(al1,al2);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/ConcurrentModificationExceptionTest.java b/luni/src/test/java/tests/api/java/util/ConcurrentModificationExceptionTest.java
deleted file mode 100644
index 3f642d6..0000000
--- a/luni/src/test/java/tests/api/java/util/ConcurrentModificationExceptionTest.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.Collection;
-import java.util.ConcurrentModificationException;
-import java.util.Iterator;
-import java.util.LinkedList;
-
-@TestTargetClass(ConcurrentModificationException.class)
-public class ConcurrentModificationExceptionTest extends
- junit.framework.TestCase {
-
- static public class CollectionModifier implements Runnable {
- Collection col;
-
- boolean keepGoing = true;
-
- public CollectionModifier(Collection c) {
- col = c;
- }
-
- public void stopNow() {
- keepGoing = false;
- }
-
- public void run() {
- Object someItem = new Integer(-1);
- while (keepGoing) {
- col.add(someItem);
- col.remove(someItem);
- }
- }
- }
-
- /**
- * @tests java.util.ConcurrentModificationException#ConcurrentModificationException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ConcurrentModificationException",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.ConcurrentModificationException()
- Collection myCollection = new LinkedList();
- Iterator myIterator = myCollection.iterator();
- for (int counter = 0; counter < 50; counter++)
- myCollection.add(new Integer(counter));
- CollectionModifier cm = new CollectionModifier(myCollection);
- Thread collectionSlapper = new Thread(cm);
- try {
- collectionSlapper.start();
- while (myIterator.hasNext())
- myIterator.next();
- } catch (ConcurrentModificationException e) {
- cm.stopNow();
- return;
- }
- cm.stopNow();
- // The exception should have been thrown--if the code flow makes it here
- // the test has failed
- fail("Failed to throw expected ConcurrentModificationException");
- }
-
- /**
- * @tests java.util.ConcurrentModificationException#ConcurrentModificationException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ConcurrentModificationException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method
- // java.util.ConcurrentModificationException(java.lang.String)
- String errorMessage = "This is an error message";
- try {
- // This is here to stop "unreachable code" unresolved problem
- if (true)
- throw new ConcurrentModificationException(errorMessage);
- } catch (ConcurrentModificationException e) {
- assertTrue("Exception thrown without error message", e.getMessage()
- .equals(errorMessage));
- return;
- }
- fail("Failed to throw expected ConcurrentModificationException");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/CurrencyTest.java b/luni/src/test/java/tests/api/java/util/CurrencyTest.java
deleted file mode 100644
index 04c92ee..0000000
--- a/luni/src/test/java/tests/api/java/util/CurrencyTest.java
+++ /dev/null
@@ -1,449 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.AndroidOnly;
-
-import java.io.UnsupportedEncodingException;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Currency;
-import java.util.Iterator;
-import java.util.Locale;
-
-@TestTargetClass(Currency.class)
-public class CurrencyTest extends junit.framework.TestCase {
-
- private static Locale defaultLocale = Locale.getDefault();
-
- /**
- * @tests java.util.Currency#getInstance(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "getInstance(String) method is tested in test_getInstanceLjava_util_Locale() test.",
- method = "getInstance",
- args = {java.lang.String.class}
- )
- public void test_getInstanceLjava_lang_String() {
- // see test_getInstanceLjava_util_Locale() tests
- }
-
- /**
- * @tests java.util.Currency#getInstance(java.util.Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInstance",
- args = {java.util.Locale.class}
- )
- @KnownFailure("getInstance instead of returning null value for region without currency throws exception which should be thrown only in case of locale does not support country code.")
- public void test_getInstanceLjava_util_Locale() {
- /*
- * the behaviour in all these three cases should be the same since this
- * method ignores language and variant component of the locale.
- */
- Currency c0 = Currency.getInstance("CAD");
- Currency c1 = Currency.getInstance(new Locale("en", "CA"));
- assertTrue(
- "Currency.getInstance(new Locale(\"en\",\"CA\")) isn't equal to Currency.getInstance(\"CAD\")",
- c1 == c0);
- Currency c2 = Currency.getInstance(new Locale("fr", "CA"));
- assertTrue(
- "Currency.getInstance(new Locale(\"fr\",\"CA\")) isn't equal to Currency.getInstance(\"CAD\")",
- c2 == c0);
- Currency c3 = Currency.getInstance(new Locale("", "CA"));
- assertTrue(
- "Currency.getInstance(new Locale(\"\",\"CA\")) isn't equal to Currency.getInstance(\"CAD\")",
- c3 == c0);
-
- c0 = Currency.getInstance("JPY");
- c1 = Currency.getInstance(new Locale("ja", "JP"));
- assertTrue(
- "Currency.getInstance(new Locale(\"ja\",\"JP\")) isn't equal to Currency.getInstance(\"JPY\")",
- c1 == c0);
- c2 = Currency.getInstance(new Locale("", "JP"));
- assertTrue(
- "Currency.getInstance(new Locale(\"\",\"JP\")) isn't equal to Currency.getInstance(\"JPY\")",
- c2 == c0);
- c3 = Currency.getInstance(new Locale("bogus", "JP"));
- assertTrue(
- "Currency.getInstance(new Locale(\"bogus\",\"JP\")) isn't equal to Currency.getInstance(\"JPY\")",
- c3 == c0);
-
- Locale localeGu = new Locale("gu", "IN");
- Currency cGu = Currency.getInstance(localeGu);
- Locale localeKn = new Locale("kn", "IN");
- Currency cKn = Currency.getInstance(localeKn);
- assertTrue("Currency.getInstance(Locale_" + localeGu.toString() + "))"
- + "isn't equal to " + "Currency.getInstance(Locale_"
- + localeKn.toString() + "))", cGu == cKn);
-
- // some teritories do not have currencies, like Antarctica
- Locale loc = new Locale("", "AQ");
- try {
- Currency curr = Currency.getInstance(loc);
- assertNull(
- "Currency.getInstance(new Locale(\"\", \"AQ\")) did not return null",
- curr);
- } catch (IllegalArgumentException e) {
- fail("Unexpected IllegalArgumentException " + e);
- }
-
- // unsupported/legacy iso3 countries
- loc = new Locale("", "ZR");
- try {
- Currency curr = Currency.getInstance(loc);
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- }
-
- loc = new Locale("", "ZAR");
- try {
- Currency curr = Currency.getInstance(loc);
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- }
-
- loc = new Locale("", "FX");
- try {
- Currency curr = Currency.getInstance(loc);
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- }
-
- loc = new Locale("", "FXX");
- try {
- Currency curr = Currency.getInstance(loc);
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- }
- }
-
- /**
- * @tests java.util.Currency#getSymbol()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSymbol",
- args = {}
- )
- @KnownFailure("getSymbol() returns wrong value for currency symbol")
- public void test_getSymbol() {
-
- Currency currK = Currency.getInstance("KRW");
- Currency currI = Currency.getInstance("INR");
- Currency currUS = Currency.getInstance("USD");
-
- Locale.setDefault(Locale.US);
- assertEquals("currK.getSymbol()", "KRW", currK.getSymbol());
- assertEquals("currI.getSymbol()", "INR", currI.getSymbol());
- assertEquals("currUS.getSymbol()", "$", currUS.getSymbol());
-
- Locale.setDefault(new Locale("ko", "KR"));
- assertEquals("currK.getSymbol()", "\uffe6", currK.getSymbol());
- assertEquals("currI.getSymbol()", "INR", currI.getSymbol());
- assertEquals("currUS.getSymbol()", "USD", currUS.getSymbol());
-
- // test what happens if this is an invalid locale,
- // one with Korean country but an India language
- // this method should return the currency codes in that case
- Locale.setDefault(new Locale("kr", "KR"));
- assertEquals("currK.getSymbol()", "KRW", currK.getSymbol());
- assertEquals("currI.getSymbol()", "INR", currI.getSymbol());
- assertEquals("currUS.getSymbol()", "USD", currUS.getSymbol());
- }
-
- /**
- * @tests java.util.Currency#getSymbol(java.util.Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSymbol",
- args = {java.util.Locale.class}
- )
- @AndroidOnly("specification doesn't include strong requirements for returnig symbol. On android platform used wrong character for yen sign: \u00a5 instead of \uffe5. Both of them give correct image though")
- public void test_getSymbolLjava_util_Locale() {
- //Tests was simplified because java specification not
- // includes strong requirements for returnig symbol.
- // on android platform used wrong character for yen
- // sign: \u00a5 instead of \uffe5
- Locale[] loc1 = new Locale[]{
- Locale.JAPAN, Locale.JAPANESE,
- Locale.FRANCE, Locale.FRENCH,
- Locale.US, Locale.UK,
- Locale.CANADA, Locale.CANADA_FRENCH,
- Locale.ENGLISH,
- new Locale("ja", "JP"), new Locale("", "JP"),
-
- new Locale("fr", "FR"), new Locale("", "FR"),
-
- new Locale("en", "US"), new Locale("", "US"),
- new Locale("es", "US"), new Locale("ar", "US"),
- new Locale("ja", "US"),
-
- new Locale("en", "CA"), new Locale("fr", "CA"),
- new Locale("", "CA"), new Locale("ar", "CA"),
-
- new Locale("ja", "JP"), new Locale("", "JP"),
- new Locale("ar", "JP"),
-
- new Locale("ja", "AE"), new Locale("en", "AE"),
- new Locale("ar", "AE"),
-
- new Locale("da", "DK"), new Locale("", "DK"),
-
- new Locale("da", ""), new Locale("ja", ""),
- new Locale("en", "")};
-
- String[] euro = new String[] {"EUR", "\u20ac"};
- String[] yen = new String[] {"JPY", "\uffe5", "\uffe5JP", "JP\uffe5"};
- String[] dollar = new String[] {"USD", "$", "US$", "$US"};
- String[] cDollar = new String[] {"CAD", "$", "Can$", "$Ca"};
- String[] crone = new String[] {"DKK", "kr", "CrD"};
-
- Currency currE = Currency.getInstance("EUR");
- Currency currJ = Currency.getInstance("JPY");
- Currency currUS = Currency.getInstance("USD");
- Currency currCA = Currency.getInstance("CAD");
- Currency currDKK = Currency.getInstance("DKK");
-
- int i, j, k;
- boolean flag;
-
- Locale.setDefault(Locale.US);
- Locale.setDefault(new Locale("ja", "JP"));
- Locale.setDefault(new Locale("da", "DK"));
-
- for(k = 0; k < loc1.length; k++) {
- Locale.setDefault(loc1[k]);
-
- for (i = 0; i < loc1.length; i++) {
- flag = false;
- for (j = 0; j < euro.length; j++) {
- if (currE.getSymbol(loc1[i]).equals(euro[j])) {
- flag = true;
- break;
- }
- }
- assertTrue(flag);
- }
-
- for (i = 0; i < loc1.length; i++) {
- flag = false;
- for (j = 0; j < yen.length; j++) {
- byte[] b1 = null;
- byte[] b2 = null;
- if (currJ.getSymbol(loc1[i]).equals(yen[j])) {
- flag = true;
- break;
- }
- }
- assertTrue(flag);
- }
-
- for (i = 0; i < loc1.length; i++) {
- flag = false;
- for (j = 0; j < dollar.length; j++) {
- if (currUS.getSymbol(loc1[i]).equals(dollar[j])) {
- flag = true;
- break;
- }
- }
- assertTrue(flag);
- }
-
- for (i = 0; i < loc1.length; i++) {
- flag = false;
- for (j = 0; j < cDollar.length; j++) {
- if (currCA.getSymbol(loc1[i]).equals(cDollar[j])) {
- flag = true;
- break;
- }
- }
- assertTrue(flag);
- }
-
- for (i = 0; i < loc1.length; i++) {
- flag = false;
- for (j = 0; j < dollar.length; j++) {
- if (currCA.getSymbol(loc1[i]).equals(cDollar[j])) {
- flag = true;
- break;
- }
- }
- assertTrue(flag);
- }
- }
- }
-
- /**
- * @tests java.util.Currency#getDefaultFractionDigits()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDefaultFractionDigits",
- args = {}
- )
- @KnownFailure("method return wrong number of digits for pseudo-currency")
- public void test_getDefaultFractionDigits() {
- Currency c1 = Currency.getInstance("EUR");
- c1.getDefaultFractionDigits();
- assertEquals(" Currency.getInstance(\"" + c1
- + "\") returned incorrect number of digits. ", 2, c1
- .getDefaultFractionDigits());
-
- Currency c2 = Currency.getInstance("JPY");
- c2.getDefaultFractionDigits();
- assertEquals(" Currency.getInstance(\"" + c2
- + "\") returned incorrect number of digits. ", 0, c2
- .getDefaultFractionDigits());
-
- Currency c3 = Currency.getInstance("XBD");
- c3.getDefaultFractionDigits();
- assertEquals(" Currency.getInstance(\"" + c3
- + "\") returned incorrect number of digits. ", -1, c3
- .getDefaultFractionDigits());
-
- }
-
- /**
- * @tests java.util.Currency#getCurrencyCode() Note: lines under remarks
- * (Locale.CHINESE, Locale.ENGLISH, Locale.FRENCH, Locale.GERMAN,
- * Locale.ITALIAN, Locale.JAPANESE, Locale.KOREAN) raises exception
- * on SUN VM
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCurrencyCode",
- args = {}
- )
- public void test_getCurrencyCode() {
- final Collection<Locale> locVal = Arrays.asList(
- Locale.CANADA,
- Locale.CANADA_FRENCH,
- Locale.CHINA,
- // Locale.CHINESE,
- // Locale.ENGLISH,
- Locale.FRANCE,
- // Locale.FRENCH,
- // Locale.GERMAN,
- Locale.GERMANY,
- // Locale.ITALIAN,
- Locale.ITALY, Locale.JAPAN,
- // Locale.JAPANESE,
- Locale.KOREA,
- // Locale.KOREAN,
- Locale.PRC, Locale.SIMPLIFIED_CHINESE, Locale.TAIWAN, Locale.TRADITIONAL_CHINESE,
- Locale.UK, Locale.US);
- final Collection<String> locDat = Arrays.asList("CAD", "CAD", "CNY", "EUR", "EUR", "EUR",
- "JPY", "KRW", "CNY", "CNY", "TWD", "TWD", "GBP", "USD");
-
- Iterator<String> dat = locDat.iterator();
- for (Locale l : locVal) {
- String d = dat.next().trim();
- assertEquals("For locale " + l + " currency code wrong", Currency.getInstance(l)
- .getCurrencyCode(), d);
- }
- }
-
- /**
- * @tests java.util.Currency#toString() Note: lines under remarks
- * (Locale.CHINESE, Locale.ENGLISH, Locale.FRENCH, Locale.GERMAN,
- * Locale.ITALIAN, Locale.JAPANESE, Locale.KOREAN) raises exception
- * on SUN VM
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- final Collection<Locale> locVal = Arrays.asList(
- Locale.CANADA,
- Locale.CANADA_FRENCH,
- Locale.CHINA,
- // Locale.CHINESE,
- // Locale.ENGLISH,
- Locale.FRANCE,
- // Locale.FRENCH,
- // Locale.GERMAN,
- Locale.GERMANY,
- // Locale.ITALIAN,
- Locale.ITALY, Locale.JAPAN,
- // Locale.JAPANESE,
- Locale.KOREA,
- // Locale.KOREAN,
- Locale.PRC, Locale.SIMPLIFIED_CHINESE, Locale.TAIWAN, Locale.TRADITIONAL_CHINESE,
- Locale.UK, Locale.US);
- final Collection<String> locDat = Arrays.asList("CAD", "CAD", "CNY", "EUR", "EUR", "EUR",
- "JPY", "KRW", "CNY", "CNY", "TWD", "TWD", "GBP", "USD");
-
- Iterator<String> dat = locDat.iterator();
- for (Locale l : locVal) {
- String d = dat.next().trim();
- assertEquals("For locale " + l + " Currency.toString method returns wrong value",
- Currency.getInstance(l).toString(), d);
- }
- }
-
- protected void setUp() {
- Locale.setDefault(defaultLocale);
- }
-
- protected void tearDown() {
- }
-
- /**
- * Helper method to display Currency info
- *
- * @param c
- */
- private void printCurrency(Currency c) {
- System.out.println();
- System.out.println(c.getCurrencyCode());
- System.out.println(c.getSymbol());
- System.out.println(c.getDefaultFractionDigits());
- }
-
- /**
- * helper method to display Locale info
- */
- private static void printLocale(Locale loc) {
- System.out.println();
- System.out.println(loc.getDisplayName());
- System.out.println(loc.getCountry());
- System.out.println(loc.getLanguage());
- System.out.println(loc.getDisplayCountry());
- System.out.println(loc.getDisplayLanguage());
- System.out.println(loc.getDisplayName());
- System.out.println(loc.getISO3Country());
- System.out.println(loc.getISO3Language());
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/DateTest.java b/luni/src/test/java/tests/api/java/util/DateTest.java
deleted file mode 100644
index 8420ed0..0000000
--- a/luni/src/test/java/tests/api/java/util/DateTest.java
+++ /dev/null
@@ -1,718 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.Locale;
-import java.util.TimeZone;
-
-@TestTargetClass(Date.class)
-public class DateTest extends junit.framework.TestCase {
-
- /**
- * @tests java.util.Date#Date()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Date",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.Date()
- GregorianCalendar gc = new GregorianCalendar(1998, Calendar.OCTOBER,
- 13, 19, 9);
- long oldTime = gc.getTime().getTime();
- long now = new Date().getTime();
- assertTrue("Created incorrect date: " + oldTime + " now: " + now,
- oldTime < now);
- }
-
- /**
- * @tests java.util.Date#Date(int, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Date",
- args = {int.class, int.class, int.class}
- )
- public void test_ConstructorIII() {
- // Test for method java.util.Date(int, int, int)
- Date d1 = new Date(70, 0, 1); // the epoch + local time
-
- // the epoch + local time
- Date d2 = new Date(0 + d1.getTimezoneOffset() * 60 * 1000);
-
- assertTrue("Created incorrect date", d1.equals(d2));
-
- Date date = new Date(99, 5, 22);
- Calendar cal = new GregorianCalendar(1999, Calendar.JUNE, 22);
- assertTrue("Wrong time zone", date.equals(cal.getTime()));
- }
-
- /**
- * @tests java.util.Date#Date(int, int, int, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Date",
- args = {int.class, int.class, int.class, int.class, int.class}
- )
- public void test_ConstructorIIIII() {
- // Test for method java.util.Date(int, int, int, int, int)
-
- // the epoch + local time + (1 hour and 1 minute)
- Date d1 = new Date(70, 0, 1, 1, 1);
-
- // the epoch + local time + (1 hour and 1 minute)
- Date d2 = new Date(0 + d1.getTimezoneOffset() * 60 * 1000 + 60 * 60
- * 1000 + 60 * 1000);
-
- assertTrue("Created incorrect date", d1.equals(d2));
- }
-
- /**
- * @tests java.util.Date#Date(int, int, int, int, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Date",
- args = {int.class, int.class, int.class, int.class, int.class, int.class}
- )
- public void test_ConstructorIIIIII() {
- // Test for method java.util.Date(int, int, int, int, int, int)
-
- // the epoch + local time + (1 hour and 1 minute + 1 second)
- Date d1 = new Date(70, 0, 1, 1, 1, 1);
-
- // the epoch + local time + (1 hour and 1 minute + 1 second)
- Date d2 = new Date(0 + d1.getTimezoneOffset() * 60 * 1000 + 60 * 60
- * 1000 + 60 * 1000 + 1000);
-
- assertTrue("Created incorrect date", d1.equals(d2));
- }
-
- /**
- * @tests java.util.Date#Date(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Date",
- args = {long.class}
- )
- public void test_ConstructorJ() {
- // Test for method java.util.Date(long)
- assertTrue("Used to test", true);
- }
-
- /**
- * @tests java.util.Date#Date(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Date",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.util.Date(java.lang.String)
- Date d1 = new Date("January 1, 1970, 00:00:00 GMT"); // the epoch
- Date d2 = new Date(0); // the epoch
- assertTrue("Created incorrect date", d1.equals(d2));
-
- try {
- // Regression for HARMONY-238
- new Date(null);
- fail("Constructor Date((String)null) should "
- + "throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Date#after(java.util.Date)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "after",
- args = {java.util.Date.class}
- )
- public void test_afterLjava_util_Date() {
- // Test for method boolean java.util.Date.after(java.util.Date)
- Date d1 = new Date(0);
- Date d2 = new Date(1900000);
- assertTrue("Older was returned as newer", d2.after(d1));
- assertTrue("Newer was returned as older", !d1.after(d2));
-
- try {
- d1.after(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Date#before(java.util.Date)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "before",
- args = {java.util.Date.class}
- )
- public void test_beforeLjava_util_Date() {
- // Test for method boolean java.util.Date.before(java.util.Date)
- Date d1 = new Date(0);
- Date d2 = new Date(1900000);
- assertTrue("Older was returned as newer", !d2.before(d1));
- assertTrue("Newer was returned as older", d1.before(d2));
-
- try {
- d1.before(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Date#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- // Test for method java.lang.Object java.util.Date.clone()
- Date d1 = new Date(100000);
- Date d2 = (Date) d1.clone();
- assertTrue(
- "Cloning date results in same reference--new date is equivalent",
- d1 != d2);
- assertTrue("Cloning date results unequal date", d1.equals(d2));
- }
-
- /**
- * @tests java.util.Date#compareTo(java.util.Date)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.util.Date.class}
- )
- public void test_compareToLjava_util_Date() {
- // Test for method int java.util.Date.compareTo(java.util.Date)
- final int someNumber = 10000;
- Date d1 = new Date(someNumber);
- Date d2 = new Date(someNumber);
- Date d3 = new Date(someNumber + 1);
- Date d4 = new Date(someNumber - 1);
- assertEquals("Comparing a date to itself did not answer zero", 0, d1
- .compareTo(d1));
- assertEquals("Comparing equal dates did not answer zero", 0, d1
- .compareTo(d2));
- assertEquals("date1.compareTo(date2), where date1 > date2, did not result in 1",
- 1, d1.compareTo(d4));
- assertEquals("date1.compareTo(date2), where date1 < date2, did not result in -1",
- -1, d1.compareTo(d3));
-
- try {
- d1.compareTo(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Date#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean java.util.Date.equals(java.lang.Object)
- Date d1 = new Date(0);
- Date d2 = new Date(1900000);
- Date d3 = new Date(1900000);
- assertTrue("Equality test failed", d2.equals(d3));
- assertTrue("Equality test failed", !d1.equals(d2));
- }
-
- /**
- * @tests java.util.Date#getDate()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDate",
- args = {}
- )
- public void test_getDate() {
- // Test for method int java.util.Date.getDate()
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- assertEquals("Returned incorrect date", 13, d.getDate());
- }
-
- /**
- * @tests java.util.Date#getDay()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDay",
- args = {}
- )
- public void test_getDay() {
- // Test for method int java.util.Date.getDay()
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- assertEquals("Returned incorrect day", 2, d.getDay());
- }
-
- /**
- * @tests java.util.Date#getHours()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getHours",
- args = {}
- )
- public void test_getHours() {
- // Test for method int java.util.Date.getHours()
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- assertEquals("Returned incorrect hours", 19, d.getHours());
- }
-
- /**
- * @tests java.util.Date#getMinutes()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMinutes",
- args = {}
- )
- public void test_getMinutes() {
- // Test for method int java.util.Date.getMinutes()
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- assertEquals("Returned incorrect minutes", 9, d.getMinutes());
- }
-
- /**
- * @tests java.util.Date#getMonth()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMonth",
- args = {}
- )
- public void test_getMonth() {
- // Test for method int java.util.Date.getMonth()
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- assertEquals("Returned incorrect month", 9, d.getMonth());
- }
-
- /**
- * @tests java.util.Date#getSeconds()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSeconds",
- args = {}
- )
- public void test_getSeconds() {
- // Test for method int java.util.Date.getSeconds()
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- assertEquals("Returned incorrect seconds", 0, d.getSeconds());
- }
-
- /**
- * @tests java.util.Date#getTime()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTime",
- args = {}
- )
- public void test_getTime() {
- // Test for method long java.util.Date.getTime()
- Date d1 = new Date(0);
- Date d2 = new Date(1900000);
- assertEquals("Returned incorrect time", 1900000, d2.getTime());
- assertEquals("Returned incorrect time", 0, d1.getTime());
- }
-
- /**
- * @tests java.util.Date#getTimezoneOffset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTimezoneOffset",
- args = {}
- )
- public void test_getTimezoneOffset() {
- // Test for method int java.util.Date.getTimezoneOffset()
- assertTrue("Used to test", true);
- int offset = new Date(96, 1, 14).getTimezoneOffset();
- assertTrue(offset > -720 && offset < 720);
- }
-
- /**
- * @tests java.util.Date#getYear()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getYear",
- args = {}
- )
- public void test_getYear() {
- // Test for method int java.util.Date.getYear()
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- assertEquals("Returned incorrect year", 98, d.getYear());
- }
-
- /**
- * @tests java.util.Date#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- // Test for method int java.util.Date.hashCode()
- Date d1 = new Date(0);
- Date d2 = new Date(1900000);
- assertEquals("Returned incorrect hash", 1900000, d2.hashCode());
- assertEquals("Returned incorrect hash", 0, d1.hashCode());
- }
-
- /**
- * @tests java.util.Date#parse(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "parse",
- args = {java.lang.String.class}
- )
- public void test_parseLjava_lang_String() {
- // Test for method long java.util.Date.parse(java.lang.String)
- Date d = new Date(Date.parse("13 October 1998"));
- GregorianCalendar cal = new GregorianCalendar();
- cal.setTime(d);
- assertEquals("Parsed incorrect month", 9, cal.get(Calendar.MONTH));
- assertEquals("Parsed incorrect year", 1998, cal.get(Calendar.YEAR));
- assertEquals("Parsed incorrect date", 13, cal.get(Calendar.DATE));
-
- d = new Date(Date.parse("Jan-12 1999"));
- assertTrue("Wrong parsed date 1", d.equals(new GregorianCalendar(1999,
- 0, 12).getTime()));
- d = new Date(Date.parse("Jan12-1999"));
- assertTrue("Wrong parsed date 2", d.equals(new GregorianCalendar(1999,
- 0, 12).getTime()));
- d = new Date(Date.parse("Jan12 69-1"));
- cal.setTimeZone(TimeZone.getTimeZone("GMT"));
- cal.clear();
- cal.set(1969, Calendar.JANUARY, 12, 1, 0);
- assertTrue("Wrong parsed date 3", d.equals(cal.getTime()));
- d = new Date(Date.parse("6:45:13 3/2/1200 MST"));
- cal.setTimeZone(TimeZone.getTimeZone("MST"));
- cal.clear();
- cal.set(1200, 2, 2, 6, 45, 13);
- assertTrue("Wrong parsed date 4", d.equals(cal.getTime()));
- d = new Date(Date.parse("Mon, 22 Nov 1999 12:52:06 GMT"));
- cal.setTimeZone(TimeZone.getTimeZone("GMT"));
- cal.clear();
- cal.set(1999, Calendar.NOVEMBER, 22, 12, 52, 06);
- assertTrue("Wrong parsed date 5", d.equals(cal.getTime()));
-
- try {
- // Regression for HARMONY-259
- Date.parse(null);
- fail("Date.parse(null) should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Date#setDate(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setDate",
- args = {int.class}
- )
- public void test_setDateI() {
- // Test for method void java.util.Date.setDate(int)
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- d.setDate(23);
- assertEquals("Set incorrect date", 23, d.getDate());
- }
-
- /**
- * @tests java.util.Date#setHours(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setHours",
- args = {int.class}
- )
- public void test_setHoursI() {
- // Test for method void java.util.Date.setHours(int)
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- d.setHours(23);
- assertEquals("Set incorrect hours", 23, d.getHours());
- }
-
- /**
- * @tests java.util.Date#setMinutes(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setMinutes",
- args = {int.class}
- )
- public void test_setMinutesI() {
- // Test for method void java.util.Date.setMinutes(int)
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- d.setMinutes(45);
- assertEquals("Set incorrect mins", 45, d.getMinutes());
- }
-
- /**
- * @tests java.util.Date#setMonth(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setMonth",
- args = {int.class}
- )
- public void test_setMonthI() {
- // Test for method void java.util.Date.setMonth(int)
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- d.setMonth(0);
- assertEquals("Set incorrect month", 0, d.getMonth());
- }
-
- /**
- * @tests java.util.Date#setSeconds(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setSeconds",
- args = {int.class}
- )
- public void test_setSecondsI() {
- // Test for method void java.util.Date.setSeconds(int)
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- d.setSeconds(13);
- assertEquals("Set incorrect seconds", 13, d.getSeconds());
- }
-
- /**
- * @tests java.util.Date#setTime(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setTime",
- args = {long.class}
- )
- public void test_setTimeJ() {
- // Test for method void java.util.Date.setTime(long)
- Date d1 = new Date(0);
- Date d2 = new Date(1900000);
- d1.setTime(900);
- d2.setTime(890000);
- assertEquals("Returned incorrect time", 890000, d2.getTime());
- assertEquals("Returned incorrect time", 900, d1.getTime());
- }
-
- /**
- * @tests java.util.Date#setYear(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setYear",
- args = {int.class}
- )
- public void test_setYearI() {
- // Test for method void java.util.Date.setYear(int)
- Date d = new GregorianCalendar(1998, Calendar.OCTOBER, 13, 19, 9)
- .getTime();
- d.setYear(8);
- assertEquals("Set incorrect year", 8, d.getYear());
- }
-
- /**
- * @tests java.util.Date#toGMTString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toGMTString",
- args = {}
- )
- public void test_toGMTString() {
- // Test for method java.lang.String java.util.Date.toGMTString()
- assertEquals("Did not convert epoch to GMT string correctly", "1 Jan 1970 00:00:00 GMT", new Date(0)
- .toGMTString());
- assertEquals("Did not convert epoch + 1yr to GMT string correctly",
- "1 Jan 1971 00:00:00 GMT", new Date((long) 365 * 24 * 60 * 60 * 1000).toGMTString()
- );
- }
-
- /**
- * @tests java.util.Date#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.util.Date.toString()
- Calendar cal = Calendar.getInstance();
- cal.set(Calendar.DATE, 1);
- cal.set(Calendar.MONTH, Calendar.JANUARY);
- cal.set(Calendar.YEAR, 1970);
- cal.set(Calendar.HOUR_OF_DAY, 0);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- Date d = cal.getTime();
- String result = d.toString();
- assertTrue("Incorrect result: " + d, result
- .startsWith("Thu Jan 01 00:00:00")
- && result.endsWith("1970"));
-
- TimeZone tz = TimeZone.getDefault();
- TimeZone.setDefault(TimeZone.getTimeZone("GMT-5"));
- try {
- Date d1 = new Date(0);
- assertTrue("Returned incorrect string: " + d1, d1.toString()
- .equals("Wed Dec 31 19:00:00 GMT-05:00 1969"));
- } finally {
- TimeZone.setDefault(tz);
- }
- }
-
- /**
- * @tests java.util.Date#UTC(int, int, int, int, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UTC",
- args = {int.class, int.class, int.class, int.class, int.class, int.class}
- )
- public void test_UTCIIIIII() {
- // Test for method long java.util.Date.UTC(int, int, int, int, int, int)
- assertTrue("Returned incorrect UTC value for epoch", Date.UTC(70, 0, 1,
- 0, 0, 0) == (long) 0);
- assertTrue("Returned incorrect UTC value for epoch +1yr", Date.UTC(71,
- 0, 1, 0, 0, 0) == (long) 365 * 24 * 60 * 60 * 1000);
- }
- /**
- * @tests java.util.Date#toLocaleString() Test for method java.lang.String
- * java.util.Date.toGMTString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toLocaleString",
- args = {}
- )
- public void test_toLocaleString() {
- Locale loc = Locale.getDefault();
- Locale.setDefault(Locale.US);
- TimeZone tz = TimeZone.getDefault();
- TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
- try {
- assertEquals("Did not convert epoch to GMT string correctly", "Jan 1, 1970 12:00:00 AM",
- new Date(0).toLocaleString());
- assertEquals("Did not convert epoch + 1yr to GMT string correctly",
- "Jan 1, 1971 12:00:00 AM", new Date((long)365 * 24 * 60 * 60 * 1000)
- .toLocaleString());
- } finally {
- Locale.setDefault(loc);
- TimeZone.setDefault(tz);
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/EmptyStackExceptionTest.java b/luni/src/test/java/tests/api/java/util/EmptyStackExceptionTest.java
deleted file mode 100644
index 77254fb..0000000
--- a/luni/src/test/java/tests/api/java/util/EmptyStackExceptionTest.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.EmptyStackException;
-import java.util.Stack;
-
-@TestTargetClass(EmptyStackException.class)
-public class EmptyStackExceptionTest extends junit.framework.TestCase {
-
- static Object[] objArray = new Object[10];
- Stack s;
-
- {
- for (int counter = 0; counter < objArray.length; counter++)
- objArray[counter] = new Integer(counter);
- }
-
- /**
- * @tests java.util.EmptyStackException#EmptyStackException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "EmptyStackException",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.EmptyStackException()
- try {
- for (int counter = 0; counter < objArray.length + 1; counter++)
- s.pop();
- } catch (EmptyStackException e) {
- return;
- }
- fail("Expected EmptyStackException not thrown");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- s = new Stack();
- for (int counter = 0; counter < objArray.length; counter++)
- s.push(objArray[counter]);
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/EnumMapTest.java b/luni/src/test/java/tests/api/java/util/EnumMapTest.java
deleted file mode 100644
index 26e11c3..0000000
--- a/luni/src/test/java/tests/api/java/util/EnumMapTest.java
+++ /dev/null
@@ -1,1288 +0,0 @@
-/* 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.AndroidOnly;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.Set;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(EnumMap.class)
-public class EnumMapTest extends TestCase {
- enum Size {
- Small, Middle, Big {};
- }
-
- enum Color {
- Red, Green, Blue {};
- }
-
- enum Empty {
- //Empty
- }
-
- private static class MockEntry<K, V> implements Map.Entry<K, V> {
- private K key;
-
- private V value;
-
- public MockEntry(K key, V value) {
- this.key = key;
- this.value = value;
- }
-
- @Override
- public int hashCode() {
- return (key == null ? 0 : key.hashCode())
- ^ (value == null ? 0 : value.hashCode());
- }
-
- public K getKey() {
- return key;
- }
-
- public V getValue() {
- return value;
- }
-
- public V setValue(V object) {
- V oldValue = value;
- value = object;
- return oldValue;
- }
- }
-
- /**
- * @tests java.util.EnumMap#EnumMap(Class)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "EnumMap",
- args = {java.lang.Class.class}
- )
- @SuppressWarnings({ "unchecked", "boxing" })
- public void test_ConstructorLjava_lang_Class() {
- try {
- new EnumMap((Class) null);
- fail("Expected NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // Expected
- }
-
-
- try {
- new EnumMap(Size.Big.getClass());
- fail("Expected NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // Expected
- }
-
- try {
- new EnumMap(Integer.class);
- fail("Expected NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // Expected
- }
-
- EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
- assertNull("Return non-null for non mapped key", enumColorMap.put( //$NON-NLS-1$
- Color.Green, 2));
- assertEquals("Get returned incorrect value for given key", 2, //$NON-NLS-1$
- enumColorMap.get(Color.Green));
-
- EnumMap enumEmptyMap = new EnumMap<Empty, Double>(Empty.class);
- try {
- enumEmptyMap.put(Color.Red, 2);
- fail("Expected ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // Expected
- }
-
- EnumMap enumSizeMap = new EnumMap(Size.class);
- assertNull("Return non-null for non mapped key", enumSizeMap.put( //$NON-NLS-1$
- Size.Big, 2));
- assertEquals("Get returned incorrect value for given key", 2, //$NON-NLS-1$
- enumSizeMap.get(Size.Big));
- try {
- enumSizeMap.put(Color.Red, 2);
- fail("Expected ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // Expected
- }
-
- enumSizeMap = new EnumMap(Size.Middle.getClass());
- assertNull("Return non-null for non mapped key", enumSizeMap.put( //$NON-NLS-1$
- Size.Small, 1));
- assertEquals("Get returned incorrect value for given key", 1, //$NON-NLS-1$
- enumSizeMap.get(Size.Small));
- try {
- enumSizeMap.put(Color.Red, 2);
- fail("Expected ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.util.EnumMap#EnumMap(EnumMap)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "EnumMap",
- args = {java.util.EnumMap.class}
- )
- @SuppressWarnings({ "unchecked", "boxing" })
- public void test_ConstructorLjava_util_EnumMap() {
- EnumMap enumMap;
- EnumMap enumColorMap = null;
- try {
- enumMap = new EnumMap(enumColorMap);
- fail("Expected NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // Expected
- }
-
- enumColorMap = new EnumMap<Color, Double>(Color.class);
- Double double1 = new Double(1);
- enumColorMap.put(Color.Green, 2);
- enumColorMap.put(Color.Blue, double1);
-
- enumMap = new EnumMap(enumColorMap);
- assertEquals("Constructor fails", 2, enumMap.get(Color.Green)); //$NON-NLS-1$
- assertSame("Constructor fails", double1, enumMap.get(Color.Blue)); //$NON-NLS-1$
- assertNull("Constructor fails", enumMap.get(Color.Red)); //$NON-NLS-1$
- enumMap.put(Color.Red, 1);
- assertEquals("Wrong value", 1, enumMap.get(Color.Red)); //$NON-NLS-1$
-
- try {
- enumMap.put(Size.Middle, 2);
- fail("Expected ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.util.EnumMap#EnumMap(Map)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "EnumMap",
- args = {java.util.Map.class}
- )
- @SuppressWarnings({ "unchecked", "boxing" })
- public void test_ConstructorLjava_util_Map() {
- EnumMap enumMap;
- Map enumColorMap = null;
- try {
- enumMap = new EnumMap(enumColorMap);
- fail("Expected NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // Expected
- }
- enumColorMap = new EnumMap<Color, Double>(Color.class);
- enumMap = new EnumMap(enumColorMap);
- enumColorMap.put(Color.Blue, 3);
- enumMap = new EnumMap(enumColorMap);
-
- HashMap hashColorMap = null;
- try {
- enumMap = new EnumMap(hashColorMap);
- fail("Expected NullPointerException");//$NON-NLS-1$
- } catch (NullPointerException e) {
- // Expected
- }
-
- hashColorMap = new HashMap();
- try {
- enumMap = new EnumMap(hashColorMap);
- fail("Expected IllegalArgumentException"); //$NON-NLS-1$
- } catch (IllegalArgumentException e) {
- // Expected
- }
-
- hashColorMap.put(Color.Green, 2);
- enumMap = new EnumMap(hashColorMap);
- assertEquals("Constructor fails", 2, enumMap.get(Color.Green)); //$NON-NLS-1$
- assertNull("Constructor fails", enumMap.get(Color.Red)); //$NON-NLS-1$
- enumMap.put(Color.Red, 1);
- assertEquals("Wrong value", 1, enumMap.get(Color.Red)); //$NON-NLS-1$
- hashColorMap.put(Size.Big, 3);
- try {
- enumMap = new EnumMap(hashColorMap);
- fail("Expected ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // Expected
- }
-
- hashColorMap = new HashMap();
- hashColorMap.put(new Integer(1), 1);
- try {
- enumMap = new EnumMap(hashColorMap);
- fail("Expected ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.util.EnumMap#clear()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- @SuppressWarnings({ "unchecked", "boxing" })
- public void test_clear() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Small, 1);
- enumSizeMap.clear();
- assertNull("Failed to clear all elements", enumSizeMap.get(Size.Small)); //$NON-NLS-1$
- }
-
- /**
- * @tests java.util.EnumMap#containsKey(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "containsKey",
- args = {java.lang.Object.class}
- )
- @SuppressWarnings( { "unchecked", "boxing" })
- public void test_containsKeyLjava_lang_Object() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- assertFalse("Returned true for uncontained key", enumSizeMap //$NON-NLS-1$
- .containsKey(Size.Small));
- enumSizeMap.put(Size.Small, 1);
- assertTrue("Returned false for contained key", enumSizeMap //$NON-NLS-1$
- .containsKey(Size.Small));
-
- enumSizeMap.put(Size.Big, null);
- assertTrue("Returned false for contained key", enumSizeMap //$NON-NLS-1$
- .containsKey(Size.Big));
-
- assertFalse("Returned true for uncontained key", enumSizeMap //$NON-NLS-1$
- .containsKey(Color.Red));
- assertFalse("Returned true for uncontained key", enumSizeMap //$NON-NLS-1$
- .containsKey(new Integer("3"))); //$NON-NLS-1$
- assertFalse("Returned true for uncontained key", enumSizeMap //$NON-NLS-1$
- .containsKey(null));
- }
-
- /**
- * @tests java.util.EnumMap#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- @SuppressWarnings( { "unchecked", "boxing" })
- public void test_clone() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- Integer integer = new Integer("3"); //$NON-NLS-1$
- enumSizeMap.put(Size.Small, integer);
- EnumMap enumSizeMapClone = enumSizeMap.clone();
- assertNotSame("Should not be same", enumSizeMap, enumSizeMapClone); //$NON-NLS-1$
- assertEquals("Clone answered unequal EnumMap", enumSizeMap, //$NON-NLS-1$
- enumSizeMapClone);
-
- assertSame("Should be same", enumSizeMap.get(Size.Small), //$NON-NLS-1$
- enumSizeMapClone.get(Size.Small));
- assertSame("Clone is not shallow clone", integer, enumSizeMapClone //$NON-NLS-1$
- .get(Size.Small));
- enumSizeMap.remove(Size.Small);
- assertSame("Clone is not shallow clone", integer, enumSizeMapClone //$NON-NLS-1$
- .get(Size.Small));
- }
-
- /**
- * @tests java.util.EnumMap#containsValue(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "containsValue",
- args = {java.lang.Object.class}
- )
- @SuppressWarnings( { "unchecked", "boxing" })
- public void test_containsValueLjava_lang_Object() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- Double double1 = new Double(3);
- Double double2 = new Double(3);
-
- assertFalse("Returned true for uncontained value", enumSizeMap //$NON-NLS-1$
- .containsValue(double1));
- enumSizeMap.put(Size.Middle, 2);
- enumSizeMap.put(Size.Small, double1);
- assertTrue("Returned false for contained value", enumSizeMap //$NON-NLS-1$
- .containsValue(double1));
- assertTrue("Returned false for contained value", enumSizeMap //$NON-NLS-1$
- .containsValue(double2));
- assertTrue("Returned false for contained value", enumSizeMap //$NON-NLS-1$
- .containsValue(2));
- assertFalse("Returned true for uncontained value", enumSizeMap //$NON-NLS-1$
- .containsValue(1));
-
- assertFalse("Returned true for uncontained value", enumSizeMap //$NON-NLS-1$
- .containsValue(null));
- enumSizeMap.put(Size.Big, null);
- assertTrue("Returned false for contained value", enumSizeMap //$NON-NLS-1$
- .containsValue(null));
- }
-
- /**
- * @tests java.util.EnumMap#entrySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "entrySet",
- args = {}
- )
- @AndroidOnly("Map.Entry is indirectly modified on RI when Iterator.next() is invoked")
- @SuppressWarnings({ "unchecked", "boxing" })
- public void test_entrySet() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- MockEntry mockEntry = new MockEntry(Size.Middle, 1);
- Set set = enumSizeMap.entrySet();
-
- Set set1 = enumSizeMap.entrySet();
- assertSame("Should be same", set1, set); //$NON-NLS-1$
- try {
- set.add(mockEntry);
- fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$
- } catch (UnsupportedOperationException e) {
- // Expected
- }
-
- assertTrue("Returned false for contained object", set//$NON-NLS-1$
- .contains(mockEntry));
- mockEntry = new MockEntry(Size.Middle, null);
- assertFalse("Returned true for uncontained object", set //$NON-NLS-1$
- .contains(mockEntry));
- assertFalse("Returned true for uncontained object", set //$NON-NLS-1$
- .contains(Size.Small));
- mockEntry = new MockEntry(new Integer(1), 1);
- assertFalse("Returned true for uncontained object", set //$NON-NLS-1$
- .contains(mockEntry));
- assertFalse("Returned true for uncontained object", set //$NON-NLS-1$
- .contains(new Integer(1)));
-
- mockEntry = new MockEntry(Size.Big, null);
- assertTrue("Returned false for contained object", set//$NON-NLS-1$
- .contains(mockEntry));
- assertTrue("Returned false when the object can be removed", set //$NON-NLS-1$
- .remove(mockEntry));
- assertFalse("Returned true for uncontained object", set //$NON-NLS-1$
- .contains(mockEntry));
- assertFalse("Returned true when the object can not be removed", set //$NON-NLS-1$
- .remove(mockEntry));
- mockEntry = new MockEntry(new Integer(1), 1);
- assertFalse("Returned true when the object can not be removed", set //$NON-NLS-1$
- .remove(mockEntry));
- assertFalse("Returned true when the object can not be removed", set //$NON-NLS-1$
- .remove(new Integer(1)));
-
- // The set is backed by the map so changes to one are reflected by the
- // other.
- enumSizeMap.put(Size.Big, 3);
- mockEntry = new MockEntry(Size.Big, 3);
- assertTrue("Returned false for contained object", set//$NON-NLS-1$
- .contains(mockEntry));
- enumSizeMap.remove(Size.Big);
- assertFalse("Returned true for uncontained object", set //$NON-NLS-1$
- .contains(mockEntry));
-
- assertEquals("Wrong size", 1, set.size()); //$NON-NLS-1$
- set.clear();
- assertEquals("Wrong size", 0, set.size()); //$NON-NLS-1$
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- set = enumSizeMap.entrySet();
- Collection c = new ArrayList();
- c.add(new MockEntry(Size.Middle, 1));
- assertTrue("Return wrong value", set.containsAll(c)); //$NON-NLS-1$
- assertTrue("Remove does not success", set.removeAll(c)); //$NON-NLS-1$
-
- enumSizeMap.put(Size.Middle, 1);
- c.add(new MockEntry(Size.Big, 3));
- assertTrue("Remove does not success", set.removeAll(c)); //$NON-NLS-1$
- assertFalse("Should return false", set.removeAll(c)); //$NON-NLS-1$
- assertEquals("Wrong size", 1, set.size()); //$NON-NLS-1$
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- set = enumSizeMap.entrySet();
- c = new ArrayList();
- c.add(new MockEntry(Size.Middle, 1));
- c.add(new MockEntry(Size.Big, 3));
-
- assertTrue("Retain does not success", set.retainAll(c)); //$NON-NLS-1$
- assertEquals("Wrong size", 1, set.size()); //$NON-NLS-1$
- assertFalse("Should return false", set.retainAll(c)); //$NON-NLS-1$
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
-
- set = enumSizeMap.entrySet();
- Object[] array = set.toArray();
- assertEquals("Wrong length", 2, array.length); //$NON-NLS-1$
- Map.Entry entry = (Map.Entry) array[0];
- assertEquals("Wrong key", Size.Middle, entry.getKey()); //$NON-NLS-1$
- assertEquals("Wrong value", 1, entry.getValue()); //$NON-NLS-1$
-
- Object[] array1 = new Object[10];
- array1 = set.toArray();
- assertEquals("Wrong length", 2, array1.length); //$NON-NLS-1$
- entry = (Map.Entry) array[0];
- assertEquals("Wrong key", Size.Middle, entry.getKey()); //$NON-NLS-1$
- assertEquals("Wrong value", 1, entry.getValue()); //$NON-NLS-1$
-
- array1 = new Object[10];
- array1 = set.toArray(array1);
- assertEquals("Wrong length", 10, array1.length); //$NON-NLS-1$
- entry = (Map.Entry) array[1];
- assertEquals("Wrong key", Size.Big, entry.getKey()); //$NON-NLS-1$
- assertNull("Should be null", array1[2]); //$NON-NLS-1$
-
- set = enumSizeMap.entrySet();
- Integer integer = new Integer("1"); //$NON-NLS-1$
- assertFalse("Returned true when the object can not be removed", set //$NON-NLS-1$
- .remove(integer));
- assertTrue("Returned false when the object can be removed", set //$NON-NLS-1$
- .remove(entry));
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- set = enumSizeMap.entrySet();
- Iterator iter = set.iterator();
- entry = (Map.Entry) iter.next();
- assertTrue("Returned false for contained object", set.contains(entry)); //$NON-NLS-1$
- mockEntry = new MockEntry(Size.Middle, 2);
- assertFalse("Returned true for uncontained object", set //$NON-NLS-1$
- .contains(mockEntry));
- mockEntry = new MockEntry(new Integer(2), 2);
- assertFalse("Returned true for uncontained object", set //$NON-NLS-1$
- .contains(mockEntry));
- entry = (Map.Entry) iter.next();
- assertTrue("Returned false for contained object", set.contains(entry)); //$NON-NLS-1$
-
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.remove(Size.Big);
- mockEntry = new MockEntry(Size.Big, null);
- assertEquals("Wrong size", 1, set.size()); //$NON-NLS-1$
- assertFalse("Returned true for uncontained object", set.contains(mockEntry)); //$NON-NLS-1$
- enumSizeMap.put(Size.Big, 2);
- mockEntry = new MockEntry(Size.Big, 2);
- assertTrue("Returned false for contained object", set //$NON-NLS-1$
- .contains(mockEntry));
-
- iter.remove();
- try {
- iter.remove();
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
- // Expected
- }
- try {
- entry.setValue(2);
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
- // Expected
- }
- try {
- set.contains(entry);
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
- // Expected
- }
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- set = enumSizeMap.entrySet();
- iter = set.iterator();
- entry = (Map.Entry) iter.next();
- assertEquals("Wrong key", Size.Middle, entry.getKey()); //$NON-NLS-1$
-
- assertTrue("Returned false for contained object", set.contains(entry)); //$NON-NLS-1$
- enumSizeMap.put(Size.Middle, 3);
- assertTrue("Returned false for contained object", set.contains(entry)); //$NON-NLS-1$
- entry.setValue(2);
- assertTrue("Returned false for contained object", set.contains(entry)); //$NON-NLS-1$
- assertFalse("Returned true for uncontained object", set //$NON-NLS-1$
- .remove(new Integer(1)));
-
- iter.next();
- assertEquals("Wrong key", Size.Middle, entry.getKey()); //$NON-NLS-1$
- set.clear();
- assertEquals("Wrong size", 0, set.size()); //$NON-NLS-1$
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- set = enumSizeMap.entrySet();
- iter = set.iterator();
- mockEntry = new MockEntry(Size.Middle, 1);
-
- assertFalse("Wrong result", entry.equals(mockEntry)); //$NON-NLS-1$
- try {
- iter.remove();
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
- // Expected
- }
- entry = (Map.Entry) iter.next();
- assertEquals("Wrong key", Size.Middle, entry.getKey()); //$NON-NLS-1$
- assertTrue("Should return true", entry.equals(mockEntry)); //$NON-NLS-1$
- assertEquals("Should be equal", mockEntry.hashCode(), entry.hashCode()); //$NON-NLS-1$
- mockEntry = new MockEntry(Size.Big, 1);
- assertFalse("Wrong result", entry.equals(mockEntry)); //$NON-NLS-1$
-
- entry = (Map.Entry) iter.next();
- assertFalse("Wrong result", entry.equals(mockEntry)); //$NON-NLS-1$
- assertEquals("Wrong key", Size.Big, entry.getKey()); //$NON-NLS-1$
- iter.remove();
- assertFalse("Wrong result", entry.equals(mockEntry)); //$NON-NLS-1$
- assertEquals("Wrong size", 1, set.size()); //$NON-NLS-1$
- try {
- iter.remove();
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
- // Expected
- }
- try {
- iter.next();
- fail("Should throw NoSuchElementException"); //$NON-NLS-1$
- } catch (NoSuchElementException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.util.EnumMap#equals(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- @SuppressWarnings( { "unchecked", "boxing" })
- public void test_equalsLjava_lang_Object() {
- EnumMap enumMap = new EnumMap(Size.class);
- enumMap.put(Size.Small, 1);
-
- EnumMap enumSizeMap = new EnumMap(Size.class);
- assertFalse("Returned true for unequal EnumMap", enumSizeMap //$NON-NLS-1$
- .equals(enumMap));
- enumSizeMap.put(Size.Small, 1);
- assertTrue("Returned false for equal EnumMap", enumSizeMap //$NON-NLS-1$
- .equals(enumMap));
- enumSizeMap.put(Size.Big, null);
- assertFalse("Returned true for unequal EnumMap", enumSizeMap //$NON-NLS-1$
- .equals(enumMap));
-
- enumMap.put(Size.Middle, null);
- assertFalse("Returned true for unequal EnumMap", enumSizeMap //$NON-NLS-1$
- .equals(enumMap));
- enumMap.remove(Size.Middle);
- enumMap.put(Size.Big, 3);
- assertFalse("Returned true for unequal EnumMap", enumSizeMap //$NON-NLS-1$
- .equals(enumMap));
- enumMap.put(Size.Big, null);
- assertTrue("Returned false for equal EnumMap", enumSizeMap //$NON-NLS-1$
- .equals(enumMap));
-
- HashMap hashMap = new HashMap();
- hashMap.put(Size.Small, 1);
- assertFalse("Returned true for unequal EnumMap", hashMap //$NON-NLS-1$
- .equals(enumMap));
- hashMap.put(Size.Big, null);
- assertTrue("Returned false for equal EnumMap", enumMap.equals(hashMap)); //$NON-NLS-1$
-
- assertFalse("Should return false", enumSizeMap //$NON-NLS-1$
- .equals(new Integer(1)));
- }
-
- /**
- * @tests java.util.EnumMap#keySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "keySet",
- args = {}
- )
- @SuppressWarnings( { "unchecked", "boxing" })
- public void test_keySet() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 2);
- enumSizeMap.put(Size.Big, null);
- Set set = enumSizeMap.keySet();
-
- Set set1 = enumSizeMap.keySet();
- assertSame("Should be same", set1, set); //$NON-NLS-1$
- try {
- set.add(Size.Big);
- fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$
- } catch (UnsupportedOperationException e) {
- // Expected
- }
-
- assertTrue("Returned false for contained object", set//$NON-NLS-1$
- .contains(Size.Middle));
- assertTrue("Returned false for contained object", set//$NON-NLS-1$
- .contains(Size.Big));
- assertFalse("Returned true for uncontained object", set //$NON-NLS-1$
- .contains(Size.Small));
- assertFalse("Returned true for uncontained object", set //$NON-NLS-1$
- .contains(new Integer(1)));
- assertTrue("Returned false when the object can be removed", set //$NON-NLS-1$
- .remove(Size.Big));
- assertFalse("Returned true for uncontained object", set //$NON-NLS-1$
- .contains(Size.Big));
- assertFalse("Returned true when the object can not be removed", set //$NON-NLS-1$
- .remove(Size.Big));
- assertFalse("Returned true when the object can not be removed", set //$NON-NLS-1$
- .remove(new Integer(1)));
-
- // The set is backed by the map so changes to one are reflected by the
- // other.
- enumSizeMap.put(Size.Big, 3);
- assertTrue("Returned false for contained object", set//$NON-NLS-1$
- .contains(Size.Big));
- enumSizeMap.remove(Size.Big);
- assertFalse("Returned true for uncontained object", set //$NON-NLS-1$
- .contains(Size.Big));
-
- assertEquals("Wrong size", 1, set.size()); //$NON-NLS-1$
- set.clear();
- assertEquals("Wrong size", 0, set.size()); //$NON-NLS-1$
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- set = enumSizeMap.keySet();
- Collection c = new ArrayList();
- c.add(Size.Big);
- assertTrue("Should return true", set.containsAll(c)); //$NON-NLS-1$
- c.add(Size.Small);
- assertFalse("Should return false", set.containsAll(c)); //$NON-NLS-1$
- assertTrue("Should return true", set.removeAll(c)); //$NON-NLS-1$
- assertEquals("Wrong size", 1, set.size()); //$NON-NLS-1$
- assertFalse("Should return false", set.removeAll(c)); //$NON-NLS-1$
- assertEquals("Wrong size", 1, set.size()); //$NON-NLS-1$
- try {
- set.addAll(c);
- fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$
- } catch (UnsupportedOperationException e) {
- // Expected
- }
-
- enumSizeMap.put(Size.Big, null);
- assertEquals("Wrong size", 2, set.size()); //$NON-NLS-1$
- assertTrue("Should return true", set.retainAll(c)); //$NON-NLS-1$
- assertEquals("Wrong size", 1, set.size()); //$NON-NLS-1$
- assertFalse("Should return false", set.retainAll(c)); //$NON-NLS-1$
- assertEquals(1, set.size());
- Object[] array = set.toArray();
- assertEquals("Wrong length", 1, array.length); //$NON-NLS-1$
- assertEquals("Wrong key", Size.Big, array[0]); //$NON-NLS-1$
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- set = enumSizeMap.keySet();
- c = new ArrayList();
- c.add(Color.Blue);
- assertFalse("Should return false", set.remove(c)); //$NON-NLS-1$
- assertEquals("Wrong size", 2, set.size()); //$NON-NLS-1$
- assertTrue("Should return true", set.retainAll(c)); //$NON-NLS-1$
- assertEquals("Wrong size", 0, set.size()); //$NON-NLS-1$
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- set = enumSizeMap.keySet();
-
- Iterator iter = set.iterator();
- Enum enumKey = (Enum) iter.next();
- assertTrue("Returned false for contained object", set.contains(enumKey)); //$NON-NLS-1$
- enumKey = (Enum) iter.next();
- assertTrue("Returned false for contained object", set.contains(enumKey)); //$NON-NLS-1$
-
- enumSizeMap.remove(Size.Big);
- assertFalse("Returned true for uncontained object", set //$NON-NLS-1$
- .contains(enumKey));
- iter.remove();
- try {
- iter.remove();
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
- // Expected
- }
- assertFalse("Returned true for uncontained object", set //$NON-NLS-1$
- .contains(enumKey));
-
- iter = set.iterator();
- enumKey = (Enum) iter.next();
- assertTrue("Returned false for contained object", set.contains(enumKey)); //$NON-NLS-1$
- enumSizeMap.put(Size.Middle, 3);
- assertTrue("Returned false for contained object", set.contains(enumKey)); //$NON-NLS-1$
-
- enumSizeMap = new EnumMap(Size.class);
- enumSizeMap.put(Size.Middle, 1);
- enumSizeMap.put(Size.Big, null);
- set = enumSizeMap.keySet();
- iter = set.iterator();
- try {
- iter.remove();
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
- // Expected
- }
- enumKey = (Enum) iter.next();
- assertEquals("Wrong key", Size.Middle, enumKey); //$NON-NLS-1$
- assertSame("Wrong key", Size.Middle, enumKey); //$NON-NLS-1$
- assertFalse("Returned true for unequal object", iter.equals(enumKey)); //$NON-NLS-1$
- iter.remove();
- assertFalse("Returned true for uncontained object", set //$NON-NLS-1$
- .contains(enumKey));
- try {
- iter.remove();
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
- // Expected
- }
-
- assertEquals("Wrong size", 1, set.size()); //$NON-NLS-1$
- enumKey = (Enum) iter.next();
- assertEquals("Wrong key", Size.Big, enumKey); //$NON-NLS-1$
- iter.remove();
- try {
- iter.next();
- fail("Should throw NoSuchElementException"); //$NON-NLS-1$
- } catch (NoSuchElementException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.util.EnumMap#get(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {java.lang.Object.class}
- )
- @SuppressWarnings({ "unchecked", "boxing" })
- public void test_getLjava_lang_Object() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- assertNull("Get returned non-null for non mapped key", enumSizeMap //$NON-NLS-1$
- .get(Size.Big));
- enumSizeMap.put(Size.Big, 1);
- assertEquals("Get returned incorrect value for given key", 1, //$NON-NLS-1$
- enumSizeMap.get(Size.Big));
-
- assertNull("Get returned non-null for non mapped key", enumSizeMap //$NON-NLS-1$
- .get(Size.Small));
- assertNull("Get returned non-null for non existent key", enumSizeMap //$NON-NLS-1$
- .get(Color.Red));
- assertNull("Get returned non-null for non existent key", enumSizeMap //$NON-NLS-1$
- .get(new Integer(1)));
- assertNull("Get returned non-null for non existent key", enumSizeMap //$NON-NLS-1$
- .get(null));
-
- EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
- assertNull("Get returned non-null for non mapped key", enumColorMap //$NON-NLS-1$
- .get(Color.Green));
- enumColorMap.put(Color.Green, 2);
- assertEquals("Get returned incorrect value for given key", 2, //$NON-NLS-1$
- enumColorMap.get(Color.Green));
- assertNull("Get returned non-null for non mapped key", enumColorMap //$NON-NLS-1$
- .get(Color.Blue));
-
- enumColorMap.put(Color.Green, new Double(4));
- assertEquals("Get returned incorrect value for given key", //$NON-NLS-1$
- new Double(4), enumColorMap.get(Color.Green));
- enumColorMap.put(Color.Green, new Integer("3"));//$NON-NLS-1$
- assertEquals("Get returned incorrect value for given key", new Integer( //$NON-NLS-1$
- "3"), enumColorMap.get(Color.Green));//$NON-NLS-1$
- enumColorMap.put(Color.Green, null);
- assertNull("Can not handle null value", enumColorMap.get(Color.Green)); //$NON-NLS-1$
- Float f = new Float("3.4");//$NON-NLS-1$
- enumColorMap.put(Color.Green, f);
- assertSame("Get returned incorrect value for given key", f, //$NON-NLS-1$
- enumColorMap.get(Color.Green));
- }
-
- /**
- * @tests java.util.EnumMap#put(Object,Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "put",
- args = {Enum.class, java.lang.Object.class}
- )
- public void test_putLjava_lang_ObjectLjava_lang_Object() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- try {
- enumSizeMap.put(Color.Red, 2);
- fail("Expected ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // Expected
- }
- assertNull("Return non-null for non mapped key", enumSizeMap.put( //$NON-NLS-1$
- Size.Small, 1));
-
- EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
- try {
- enumColorMap.put(Size.Big, 2);
- fail("Expected ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // Expected
- }
- try {
- enumColorMap.put(null, 2);
- fail("Expected NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // Expected
- }
- assertNull("Return non-null for non mapped key", enumColorMap.put( //$NON-NLS-1$
- Color.Green, 2));
- assertEquals("Return wrong value", 2, enumColorMap.put(Color.Green, //$NON-NLS-1$
- new Double(4)));
- assertEquals("Return wrong value", new Double(4), enumColorMap.put( //$NON-NLS-1$
- Color.Green, new Integer("3")));//$NON-NLS-1$
- assertEquals("Return wrong value", new Integer("3"), enumColorMap.put( //$NON-NLS-1$//$NON-NLS-2$
- Color.Green, null));
- Float f = new Float("3.4");//$NON-NLS-1$
- assertNull("Return non-null for non mapped key", enumColorMap.put( //$NON-NLS-1$
- Color.Green, f));
- assertNull("Return non-null for non mapped key", enumColorMap.put( //$NON-NLS-1$
- Color.Blue, 2));
- assertEquals("Return wrong value", 2, enumColorMap.put(Color.Blue, //$NON-NLS-1$
- new Double(4)));
- }
-
- /**
- * @tests java.util.EnumMap#putAll(Map)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "putAll",
- args = {java.util.Map.class}
- )
- @SuppressWarnings({ "unchecked", "boxing" })
- public void test_putAllLjava_util_Map() {
- EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
- enumColorMap.put(Color.Green, 2);
-
- EnumMap enumSizeMap = new EnumMap(Size.class);
- enumColorMap.putAll(enumSizeMap);
-
- enumSizeMap.put(Size.Big, 1);
- try {
- enumColorMap.putAll(enumSizeMap);
- fail("Expected ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // Expected
- }
-
- EnumMap enumColorMap1 = new EnumMap<Color, Double>(Color.class);
- enumColorMap1.put(Color.Blue, 3);
- enumColorMap.putAll(enumColorMap1);
- assertEquals("Get returned incorrect value for given key", 3, //$NON-NLS-1$
- enumColorMap.get(Color.Blue));
- assertEquals("Wrong Size", 2, enumColorMap.size()); //$NON-NLS-1$
-
- enumColorMap = new EnumMap<Color, Double>(Color.class);
-
- HashMap hashColorMap = null;
- try {
- enumColorMap.putAll(hashColorMap);
- fail("Expected NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // Expected
- }
-
- hashColorMap = new HashMap();
- enumColorMap.putAll(hashColorMap);
-
- hashColorMap.put(Color.Green, 2);
- enumColorMap.putAll(hashColorMap);
- assertEquals("Get returned incorrect value for given key", 2, //$NON-NLS-1$
- enumColorMap.get(Color.Green));
- assertNull("Get returned non-null for non mapped key", enumColorMap //$NON-NLS-1$
- .get(Color.Red));
- hashColorMap.put(Color.Red, new Integer(1));
- enumColorMap.putAll(hashColorMap);
- assertEquals("Get returned incorrect value for given key", new Integer(//$NON-NLS-1$
- 2), enumColorMap.get(Color.Green));
- hashColorMap.put(Size.Big, 3);
- try {
- enumColorMap.putAll(hashColorMap);
- fail("Expected ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // Expected
- }
-
- hashColorMap = new HashMap();
- hashColorMap.put(new Integer(1), 1);
- try {
- enumColorMap.putAll(hashColorMap);
- fail("Expected ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.util.EnumMap#remove(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {java.lang.Object.class}
- )
- @SuppressWarnings({ "unchecked", "boxing" })
- public void test_removeLjava_lang_Object() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- assertNull("Remove of non-mapped key returned non-null", enumSizeMap //$NON-NLS-1$
- .remove(Size.Big));
- enumSizeMap.put(Size.Big, 3);
- enumSizeMap.put(Size.Middle, 2);
-
- assertNull("Get returned non-null for non mapped key", enumSizeMap //$NON-NLS-1$
- .get(Size.Small));
- assertEquals("Remove returned incorrect value", 3, enumSizeMap //$NON-NLS-1$
- .remove(Size.Big));
- assertNull("Get returned non-null for non mapped key", enumSizeMap //$NON-NLS-1$
- .get(Size.Big));
- assertNull("Remove of non-mapped key returned non-null", enumSizeMap //$NON-NLS-1$
- .remove(Size.Big));
- assertNull("Remove of non-existent key returned non-null", enumSizeMap //$NON-NLS-1$
- .remove(Color.Red));
- assertNull("Remove of non-existent key returned non-null", enumSizeMap //$NON-NLS-1$
- .remove(new Double(4)));
- assertNull("Remove of non-existent key returned non-null", enumSizeMap //$NON-NLS-1$
- .remove(null));
-
- EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
- assertNull("Get returned non-null for non mapped key", enumColorMap //$NON-NLS-1$
- .get(Color.Green));
- enumColorMap.put(Color.Green, new Double(4));
- assertEquals("Remove returned incorrect value", new Double(4), //$NON-NLS-1$
- enumColorMap.remove(Color.Green));
- assertNull("Get returned non-null for non mapped key", enumColorMap //$NON-NLS-1$
- .get(Color.Green));
- enumColorMap.put(Color.Green, null);
- assertNull("Can not handle null value", enumColorMap //$NON-NLS-1$
- .remove(Color.Green));
- assertNull("Get returned non-null for non mapped key", enumColorMap //$NON-NLS-1$
- .get(Color.Green));
- }
-
- /**
- * @tests java.util.EnumMap#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- @SuppressWarnings({ "unchecked", "boxing" })
- public void test_size() {
- EnumMap enumSizeMap = new EnumMap(Size.class);
- assertEquals("Wrong size", 0, enumSizeMap.size()); //$NON-NLS-1$
- enumSizeMap.put(Size.Small, 1);
- assertEquals("Wrong size", 1, enumSizeMap.size()); //$NON-NLS-1$
- enumSizeMap.put(Size.Small, 0);
- assertEquals("Wrong size", 1, enumSizeMap.size()); //$NON-NLS-1$
- try {
- enumSizeMap.put(Color.Red, 2);
- fail("Expected ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // Expected
- }
- assertEquals("Wrong size", 1, enumSizeMap.size()); //$NON-NLS-1$
-
- enumSizeMap.put(Size.Middle, null);
- assertEquals("Wrong size", 2, enumSizeMap.size()); //$NON-NLS-1$
- enumSizeMap.remove(Size.Big);
- assertEquals("Wrong size", 2, enumSizeMap.size()); //$NON-NLS-1$
- enumSizeMap.remove(Size.Middle);
- assertEquals("Wrong size", 1, enumSizeMap.size()); //$NON-NLS-1$
- enumSizeMap.remove(Color.Green);
- assertEquals("Wrong size", 1, enumSizeMap.size()); //$NON-NLS-1$
-
- EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
- enumColorMap.put(Color.Green, 2);
- assertEquals("Wrong size", 1, enumColorMap.size()); //$NON-NLS-1$
- enumColorMap.remove(Color.Green);
- assertEquals("Wrong size", 0, enumColorMap.size()); //$NON-NLS-1$
-
- EnumMap enumEmptyMap = new EnumMap<Empty, Double>(Empty.class);
- assertEquals("Wrong size", 0, enumEmptyMap.size()); //$NON-NLS-1$
- }
-
- /**
- * @tests java.util.EnumMap#values()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
- @SuppressWarnings( { "unchecked", "boxing" })
- public void test_values() {
- EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
- enumColorMap.put(Color.Red, 1);
- enumColorMap.put(Color.Blue, null);
- Collection collection = enumColorMap.values();
-
- Collection collection1 = enumColorMap.values();
- assertSame("Should be same", collection1, collection); //$NON-NLS-1$
- try {
- collection.add(new Integer(1));
- fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$
- } catch (UnsupportedOperationException e) {
- // Expected
- }
-
- assertTrue("Returned false for contained object", collection//$NON-NLS-1$
- .contains(1));
- assertTrue("Returned false for contained object", collection//$NON-NLS-1$
- .contains(null));
- assertFalse("Returned true for uncontained object", collection //$NON-NLS-1$
- .contains(2));
-
- assertTrue("Returned false when the object can be removed", collection //$NON-NLS-1$
- .remove(null));
- assertFalse("Returned true for uncontained object", collection //$NON-NLS-1$
- .contains(null));
- assertFalse("Returned true when the object can not be removed", //$NON-NLS-1$
- collection.remove(null));
-
- // The set is backed by the map so changes to one are reflected by the
- // other.
- enumColorMap.put(Color.Blue, 3);
- assertTrue("Returned false for contained object", collection//$NON-NLS-1$
- .contains(3));
- enumColorMap.remove(Color.Blue);
- assertFalse("Returned true for uncontained object", collection//$NON-NLS-1$
- .contains(3));
-
- assertEquals("Wrong size", 1, collection.size()); //$NON-NLS-1$
- collection.clear();
- assertEquals("Wrong size", 0, collection.size()); //$NON-NLS-1$
-
- enumColorMap = new EnumMap<Color, Double>(Color.class);
- enumColorMap.put(Color.Red, 1);
- enumColorMap.put(Color.Blue, null);
- collection = enumColorMap.values();
- Collection c = new ArrayList();
- c.add(new Integer(1));
- assertTrue("Should return true", collection.containsAll(c)); //$NON-NLS-1$
- c.add(new Double(3.4));
- assertFalse("Should return false", collection.containsAll(c)); //$NON-NLS-1$
- assertTrue("Should return true", collection.removeAll(c)); //$NON-NLS-1$
- assertEquals("Wrong size", 1, collection.size()); //$NON-NLS-1$
- assertFalse("Should return false", collection.removeAll(c)); //$NON-NLS-1$
- assertEquals("Wrong size", 1, collection.size()); //$NON-NLS-1$
- try {
- collection.addAll(c);
- fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$
- } catch (UnsupportedOperationException e) {
- // Expected
- }
-
- enumColorMap.put(Color.Red, 1);
- assertEquals("Wrong size", 2, collection.size()); //$NON-NLS-1$
- assertTrue("Should return true", collection.retainAll(c)); //$NON-NLS-1$
- assertEquals("Wrong size", 1, collection.size()); //$NON-NLS-1$
- assertFalse("Should return false", collection.retainAll(c)); //$NON-NLS-1$
- assertEquals(1, collection.size());
- Object[] array = collection.toArray();
- assertEquals("Wrong length", 1, array.length); //$NON-NLS-1$
- assertEquals("Wrong key", 1, array[0]); //$NON-NLS-1$
-
- enumColorMap = new EnumMap<Color, Double>(Color.class);
- enumColorMap.put(Color.Red, 1);
- enumColorMap.put(Color.Blue, null);
- collection = enumColorMap.values();
-
- assertEquals("Wrong size", 2, collection.size()); //$NON-NLS-1$
- assertFalse("Returned true when the object can not be removed", //$NON-NLS-1$
- collection.remove(new Integer("10"))); //$NON-NLS-1$
-
- Iterator iter = enumColorMap.values().iterator();
- Object value = iter.next();
- assertTrue("Returned false for contained object", collection //$NON-NLS-1$
- .contains(value));
- value = iter.next();
- assertTrue("Returned false for contained object", collection //$NON-NLS-1$
- .contains(value));
-
- enumColorMap.put(Color.Green, 1);
- enumColorMap.remove(Color.Blue);
- assertFalse("Returned true for uncontained object", collection //$NON-NLS-1$
- .contains(value));
- iter.remove();
- try {
- iter.remove();
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
- // Expected
- }
- assertFalse("Returned true for uncontained object", collection //$NON-NLS-1$
- .contains(value));
-
- iter = enumColorMap.values().iterator();
- value = iter.next();
- assertTrue("Returned false for contained object", collection //$NON-NLS-1$
- .contains(value));
- enumColorMap.put(Color.Green, 3);
- assertTrue("Returned false for contained object", collection //$NON-NLS-1$
- .contains(value));
- assertTrue("Returned false for contained object", collection //$NON-NLS-1$
- .remove(new Integer("1"))); //$NON-NLS-1$
- assertEquals("Wrong size", 1, collection.size()); //$NON-NLS-1$
- collection.clear();
- assertEquals("Wrong size", 0, collection.size()); //$NON-NLS-1$
-
- enumColorMap = new EnumMap<Color, Double>(Color.class);
- Integer integer1 = new Integer(1);
- enumColorMap.put(Color.Green, integer1);
- enumColorMap.put(Color.Blue, null);
- collection = enumColorMap.values();
- iter = enumColorMap.values().iterator();
- try {
- iter.remove();
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
- // Expected
- }
- value = iter.next();
- assertEquals("Wrong value", integer1, value); //$NON-NLS-1$
- assertSame("Wrong value", integer1, value); //$NON-NLS-1$
- assertFalse("Returned true for unequal object", iter.equals(value)); //$NON-NLS-1$
- iter.remove();
- assertFalse("Returned true for unequal object", iter.equals(value)); //$NON-NLS-1$
- try {
- iter.remove();
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
- // Expected
- }
- assertEquals("Wrong size", 1, collection.size()); //$NON-NLS-1$
- value = iter.next();
- assertFalse("Returned true for unequal object", iter.equals(value)); //$NON-NLS-1$
- iter.remove();
- try {
- iter.next();
- fail("Should throw NoSuchElementException"); //$NON-NLS-1$
- } catch (NoSuchElementException e) {
- // Expected
- }
- }
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- )
- @SuppressWarnings({ "unchecked", "boxing" })
- public void testSerializationSelf() throws Exception {
- EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
- enumColorMap.put(Color.Blue, 3);
- SerializationTest.verifySelf(enumColorMap);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- )
- @SuppressWarnings({ "unchecked", "boxing" })
- public void testSerializationCompatibility() throws Exception {
- EnumMap enumColorMap = new EnumMap<Color, Double>(Color.class);
- enumColorMap.put(Color.Red, 1);
- enumColorMap.put(Color.Blue, 3);
- SerializationTest.verifyGolden(this, enumColorMap);
- }
-
- /**
- * Sets up the fixture.
- */
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- /**
- * Tears down the fixture.
- */
- @Override
- protected void tearDown() throws Exception{
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/EnumSetTest.java b/luni/src/test/java/tests/api/java/util/EnumSetTest.java
deleted file mode 100644
index 172e319..0000000
--- a/luni/src/test/java/tests/api/java/util/EnumSetTest.java
+++ /dev/null
@@ -1,2112 +0,0 @@
-/* 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.EnumSet;
-import java.util.Iterator;
-import java.util.NoSuchElementException;
-import java.util.Set;
-
-import junit.framework.TestCase;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-@TestTargetClass(EnumSet.class)
-public class EnumSetTest extends TestCase {
- static final boolean disableRIBugs = true;
-
- static enum EnumWithInnerClass {
- a, b, c, d, e, f {
- },
- }
-
- enum EnumWithAllInnerClass {
- a {},
- b {},
- }
-
- static enum EnumFoo {
- 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, aa, bb, cc, dd, ee, ff, gg, hh, ii, jj, kk, ll,
- }
-
- static enum EmptyEnum {
- // expected
- }
-
- static enum HugeEnumWithInnerClass {
- 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{}, aa{}, bb{}, cc{}, dd{}, ee{}, ff{}, gg{}, hh{}, ii{}, jj{}, kk{}, ll{}, mm{},
- }
-
- static enum HugeEnum {
- 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, aa, bb, cc, dd, ee, ff, gg, hh, ii, jj, kk, ll, mm,
- }
-
- /**
- * @tests java.util.EnumSet#noneOf(java.lang.Class)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "noneOf",
- args = {java.lang.Class.class}
- )
- @SuppressWarnings("unchecked")
- public void test_NoneOf_LClass() {
- try {
- EnumSet.noneOf((Class) null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- EnumSet.noneOf(Enum.class);
- fail("Should throw ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException cce) {
- // expected
- }
-
- Class<EnumWithAllInnerClass> c = (Class<EnumWithAllInnerClass>) EnumWithAllInnerClass.a
- .getClass();
- try {
- EnumSet.noneOf(c);
- fail("Should throw ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // expected
- }
-
- EnumSet<EnumWithAllInnerClass> setWithInnerClass = EnumSet
- .noneOf(EnumWithAllInnerClass.class);
- assertNotNull(setWithInnerClass);
-
- // test enum type with more than 64 elements
- Class<HugeEnumWithInnerClass> hc = (Class<HugeEnumWithInnerClass>) HugeEnumWithInnerClass.a
- .getClass();
- try {
- EnumSet.noneOf(hc);
- fail("Should throw ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // expected
- }
-
- EnumSet<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet
- .noneOf(HugeEnumWithInnerClass.class);
- assertNotNull(hugeSetWithInnerClass);
- }
-
- /**
- * @tests java.util.EnumSet#allOf(java.lang.Class)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "allOf",
- args = {java.lang.Class.class}
- )
- @SuppressWarnings("unchecked")
- public void test_AllOf_LClass() {
- try {
- EnumSet.allOf((Class) null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- EnumSet.allOf(Enum.class);
- fail("Should throw ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException cce) {
- // expected
- }
-
- EnumSet<EnumFoo> enumSet = EnumSet.allOf(EnumFoo.class);
- assertEquals("Size of enumSet should be 64", 64, enumSet.size()); //$NON-NLS-1$
-
- assertFalse(
- "enumSet should not contain null value", enumSet.contains(null)); //$NON-NLS-1$
- assertTrue(
- "enumSet should contain EnumFoo.a", enumSet.contains(EnumFoo.a)); //$NON-NLS-1$
- assertTrue(
- "enumSet should contain EnumFoo.b", enumSet.contains(EnumFoo.b)); //$NON-NLS-1$
-
- enumSet.add(EnumFoo.a);
- assertEquals("Should be equal", 64, enumSet.size()); //$NON-NLS-1$
-
- EnumSet<EnumFoo> anotherSet = EnumSet.allOf(EnumFoo.class);
- assertEquals("Should be equal", enumSet, anotherSet); //$NON-NLS-1$
- assertNotSame("Should not be identical", enumSet, anotherSet); //$NON-NLS-1$
-
- // test enum with more than 64 elements
- EnumSet<HugeEnum> hugeEnumSet = EnumSet.allOf(HugeEnum.class);
- assertEquals(65, hugeEnumSet.size());
-
- assertFalse(hugeEnumSet.contains(null));
- assertTrue(hugeEnumSet.contains(HugeEnum.a));
- assertTrue(hugeEnumSet.contains(HugeEnum.b));
-
- hugeEnumSet.add(HugeEnum.a);
- assertEquals(65, hugeEnumSet.size());
-
- EnumSet<HugeEnum> anotherHugeSet = EnumSet.allOf(HugeEnum.class);
- assertEquals(hugeEnumSet, anotherHugeSet);
- assertNotSame(hugeEnumSet, anotherHugeSet);
-
- }
-
- /**
- * @tests java.util.EnumSet#add(E)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "add",
- args = {java.lang.Object.class}
- )
- @SuppressWarnings("unchecked")
- public void test_add_E() {
- Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- set.add(EnumFoo.a);
- set.add(EnumFoo.b);
-
- try {
- set.add(null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- // test enum type with more than 64 elements
- Set rawSet = set;
- try {
- rawSet.add(HugeEnumWithInnerClass.b);
- fail("Should throw ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // expected
- }
-
- set.clear();
- try {
- set.add(null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- boolean result = set.add(EnumFoo.a);
- assertEquals("Size should be 1:", 1, set.size()); //$NON-NLS-1$
- assertTrue("Return value should be true", result); //$NON-NLS-1$
-
- result = set.add(EnumFoo.a);
- assertEquals("Size should be 1:", 1, set.size()); //$NON-NLS-1$
- assertFalse("Return value should be false", result); //$NON-NLS-1$
-
- set.add(EnumFoo.b);
- assertEquals("Size should be 2:", 2, set.size()); //$NON-NLS-1$
-
- rawSet = set;
- try {
- rawSet.add(EnumWithAllInnerClass.a);
- fail("Should throw ClassCastException"); //$NON-NLS-1$
- } catch(ClassCastException e) {
- // expected
- }
-
- try {
- rawSet.add(EnumWithInnerClass.a);
- fail("Should throw ClassCastException"); //$NON-NLS-1$
- } catch(ClassCastException e) {
- // expected
- }
-
- try {
- rawSet.add(new Object());
- fail("Should throw ClassCastException"); //$NON-NLS-1$
- } catch(ClassCastException e) {
- // expected
- }
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
- result = hugeSet.add(HugeEnum.a);
- assertTrue(result);
-
- result = hugeSet.add(HugeEnum.a);
- assertFalse(result);
-
- try {
- hugeSet.add(null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- rawSet = hugeSet;
- try {
- rawSet.add(HugeEnumWithInnerClass.b);
- fail("Should throw ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // expected
- }
-
- try {
- rawSet.add(new Object());
- fail("Should throw ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // expected
- }
-
- result = hugeSet.add(HugeEnum.mm);
- assertTrue(result);
- result = hugeSet.add(HugeEnum.mm);
- assertFalse(result);
- assertEquals(2, hugeSet.size());
-
- }
-
- /**
- * @tests java.util.EnumSet#addAll(Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addAll",
- args = {java.util.Collection.class}
- )
- @SuppressWarnings( { "unchecked", "boxing" })
- public void test_addAll_LCollection() {
-
- Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- assertEquals("Size should be 0:", 0, set.size()); //$NON-NLS-1$
-
- try {
- set.addAll(null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- Set emptySet = EnumSet.noneOf(EmptyEnum.class);
- Enum[] elements = EmptyEnum.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- emptySet.add(elements[i]);
- }
- boolean result = set.addAll(emptySet);
- assertFalse(result);
-
- Collection<EnumFoo> collection = new ArrayList<EnumFoo>();
- collection.add(EnumFoo.a);
- collection.add(EnumFoo.b);
- result = set.addAll(collection);
- assertTrue("addAll should be successful", result); //$NON-NLS-1$
- assertEquals("Size should be 2:", 2, set.size()); //$NON-NLS-1$
-
- set = EnumSet.noneOf(EnumFoo.class);
-
- Collection rawCollection = new ArrayList<Integer>();
- result = set.addAll(rawCollection);
- assertFalse(result);
- rawCollection.add(1);
- try {
- set.addAll(rawCollection);
- fail("Should throw ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // expected
- }
-
- Set<EnumFoo> fullSet = EnumSet.noneOf(EnumFoo.class);
- fullSet.add(EnumFoo.a);
- fullSet.add(EnumFoo.b);
- result = set.addAll(fullSet);
- assertTrue("addAll should be successful", result); //$NON-NLS-1$
- assertEquals("Size of set should be 2", 2, set.size()); //$NON-NLS-1$
-
- try {
- fullSet.addAll(null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- Set fullSetWithSubclass = EnumSet.noneOf(EnumWithInnerClass.class);
- elements = EnumWithInnerClass.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- fullSetWithSubclass.add(elements[i]);
- }
- try {
- set.addAll(fullSetWithSubclass);
- fail("Should throw ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // expected
- }
- Set<EnumWithInnerClass> setWithSubclass = fullSetWithSubclass;
- result = setWithSubclass.addAll(setWithSubclass);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- Set<EnumWithInnerClass> anotherSetWithSubclass = EnumSet
- .noneOf(EnumWithInnerClass.class);
- elements = EnumWithInnerClass.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- anotherSetWithSubclass.add((EnumWithInnerClass) elements[i]);
- }
- result = setWithSubclass.addAll(anotherSetWithSubclass);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- anotherSetWithSubclass.remove(EnumWithInnerClass.a);
- result = setWithSubclass.addAll(anotherSetWithSubclass);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
- assertEquals(0, hugeSet.size());
-
- try {
- hugeSet.addAll(null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- hugeSet = EnumSet.allOf(HugeEnum.class);
- result = hugeSet.addAll(hugeSet);
- assertFalse(result);
-
- hugeSet = EnumSet.noneOf(HugeEnum.class);
- Collection<HugeEnum> hugeCollection = new ArrayList<HugeEnum>();
- hugeCollection.add(HugeEnum.a);
- hugeCollection.add(HugeEnum.b);
- result = hugeSet.addAll(hugeCollection);
- assertTrue(result);
- assertEquals(2, set.size());
-
- hugeSet = EnumSet.noneOf(HugeEnum.class);
-
- rawCollection = new ArrayList<Integer>();
- result = hugeSet.addAll(rawCollection);
- assertFalse(result);
- rawCollection.add(1);
- try {
- hugeSet.addAll(rawCollection);
- fail("Should throw ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // expected
- }
-
- EnumSet<HugeEnum> aHugeSet = EnumSet.noneOf(HugeEnum.class);
- aHugeSet.add(HugeEnum.a);
- aHugeSet.add(HugeEnum.b);
- result = hugeSet.addAll(aHugeSet);
- assertTrue(result);
- assertEquals(2, hugeSet.size());
-
- try {
- aHugeSet.addAll(null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- Set hugeSetWithSubclass = EnumSet.allOf(HugeEnumWithInnerClass.class);
- try {
- hugeSet.addAll(hugeSetWithSubclass);
- fail("Should throw ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // expected
- }
- Set<HugeEnumWithInnerClass> hugeSetWithInnerSubclass = hugeSetWithSubclass;
- result = hugeSetWithInnerSubclass.addAll(hugeSetWithInnerSubclass);
- assertFalse(result);
-
- Set<HugeEnumWithInnerClass> anotherHugeSetWithSubclass = EnumSet
- .allOf(HugeEnumWithInnerClass.class);
- result = hugeSetWithSubclass.addAll(anotherHugeSetWithSubclass);
- assertFalse(result);
-
- anotherHugeSetWithSubclass.remove(HugeEnumWithInnerClass.a);
- result = setWithSubclass.addAll(anotherSetWithSubclass);
- assertFalse(result);
-
- }
-
- /**
- * @tests java.util.EnumSet#remove(Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify exceptions.",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_remove_LOject() {
- Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- Enum[] elements = EnumFoo.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- set.add((EnumFoo) elements[i]);
- }
-
- boolean result = set.remove(null);
- assertFalse("'set' does not contain null", result); //$NON-NLS-1$
-
- result = set.remove(EnumFoo.a);
- assertTrue("Should return true", result); //$NON-NLS-1$
- result = set.remove(EnumFoo.a);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- assertEquals("Size of set should be 63:", 63, set.size()); //$NON-NLS-1$
-
- result = set.remove(EnumWithInnerClass.a);
- assertFalse("Should return false", result); //$NON-NLS-1$
- result = set.remove(EnumWithInnerClass.f);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- // test enum with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class);
-
- result = hugeSet.remove(null);
- assertFalse("'set' does not contain null", result); //$NON-NLS-1$
-
- result = hugeSet.remove(HugeEnum.a);
- assertTrue("Should return true", result); //$NON-NLS-1$
- result = hugeSet.remove(HugeEnum.a);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- assertEquals("Size of set should be 64:", 64, hugeSet.size()); //$NON-NLS-1$
-
- result = hugeSet.remove(HugeEnumWithInnerClass.a);
- assertFalse("Should return false", result); //$NON-NLS-1$
- result = hugeSet.remove(HugeEnumWithInnerClass.f);
- assertFalse("Should return false", result); //$NON-NLS-1$
- }
-
- /**
- * @tests java.util.EnumSet#equals(Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equals_LObject() {
- Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- Enum[] elements = EnumFoo.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- set.add((EnumFoo) elements[i]);
- }
-
- assertFalse("Should return false", set.equals(null)); //$NON-NLS-1$
- assertFalse(
- "Should return false", set.equals(new Object())); //$NON-NLS-1$
-
- Set<EnumFoo> anotherSet = EnumSet.noneOf(EnumFoo.class);
- elements = EnumFoo.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- anotherSet.add((EnumFoo) elements[i]);
- }
- assertTrue("Should return true", set.equals(anotherSet)); //$NON-NLS-1$
-
- anotherSet.remove(EnumFoo.a);
- assertFalse(
- "Should return false", set.equals(anotherSet)); //$NON-NLS-1$
-
- Set<EnumWithInnerClass> setWithInnerClass = EnumSet
- .noneOf(EnumWithInnerClass.class);
- elements = EnumWithInnerClass.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- setWithInnerClass.add((EnumWithInnerClass) elements[i]);
- }
-
- assertFalse(
- "Should return false", set.equals(setWithInnerClass)); //$NON-NLS-1$
-
- setWithInnerClass.clear();
- set.clear();
- assertTrue("Should be equal", set.equals(setWithInnerClass)); //$NON-NLS-1$
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
- assertTrue(hugeSet.equals(set));
-
- hugeSet = EnumSet.allOf(HugeEnum.class);
- assertFalse(hugeSet.equals(null));
- assertFalse(hugeSet.equals(new Object()));
-
- Set<HugeEnum> anotherHugeSet = EnumSet.allOf(HugeEnum.class);
- anotherHugeSet.remove(HugeEnum.a);
- assertFalse(hugeSet.equals(anotherHugeSet));
-
- Set<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet
- .allOf(HugeEnumWithInnerClass.class);
- assertFalse(hugeSet.equals(hugeSetWithInnerClass));
- hugeSetWithInnerClass.clear();
- hugeSet.clear();
- assertTrue(hugeSet.equals(hugeSetWithInnerClass));
- }
-
- /**
- * @tests java.util.EnumSet#clear()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- set.add(EnumFoo.a);
- set.add(EnumFoo.b);
- assertEquals("Size should be 2", 2, set.size()); //$NON-NLS-1$
-
- set.clear();
-
- assertEquals("Size should be 0", 0, set.size()); //$NON-NLS-1$
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class);
- assertEquals(65, hugeSet.size());
-
- boolean result = hugeSet.contains(HugeEnum.aa);
- assertTrue(result);
-
- hugeSet.clear();
- assertEquals(0, hugeSet.size());
- result = hugeSet.contains(HugeEnum.aa);
- assertFalse(result);
- }
-
- /**
- * @tests java.util.EnumSet#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- public void test_size() {
- Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- set.add(EnumFoo.a);
- set.add(EnumFoo.b);
- assertEquals("Size should be 2", 2, set.size()); //$NON-NLS-1$
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
- hugeSet.add(HugeEnum.a);
- hugeSet.add(HugeEnum.bb);
- assertEquals("Size should be 2", 2, hugeSet.size()); //$NON-NLS-1$
- }
-
- /**
- * @tests java.util.EnumSet#complementOf(java.util.EnumSet)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "complementOf",
- args = {java.util.EnumSet.class}
- )
- public void test_ComplementOf_LEnumSet() {
-
- try {
- EnumSet.complementOf((EnumSet<EnumFoo>) null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
-
- EnumSet<EnumWithInnerClass> set = EnumSet
- .noneOf(EnumWithInnerClass.class);
- set.add(EnumWithInnerClass.d);
- set.add(EnumWithInnerClass.e);
- set.add(EnumWithInnerClass.f);
-
- assertEquals("Size should be 3:", 3, set.size()); //$NON-NLS-1$
-
- EnumSet<EnumWithInnerClass> complementOfE = EnumSet.complementOf(set);
- assertTrue(set.contains(EnumWithInnerClass.d));
- assertEquals(
- "complementOfE should have size 3", 3, complementOfE.size()); //$NON-NLS-1$
- assertTrue("complementOfE should contain EnumWithSubclass.a:", //$NON-NLS-1$
- complementOfE.contains(EnumWithInnerClass.a));
- assertTrue("complementOfE should contain EnumWithSubclass.b:", //$NON-NLS-1$
- complementOfE.contains(EnumWithInnerClass.b));
- assertTrue("complementOfE should contain EnumWithSubclass.c:", //$NON-NLS-1$
- complementOfE.contains(EnumWithInnerClass.c));
-
- // test enum type with more than 64 elements
- EnumSet<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
- assertEquals(0, hugeSet.size());
- Set<HugeEnum> complementHugeSet = EnumSet.complementOf(hugeSet);
- assertEquals(65, complementHugeSet.size());
-
- hugeSet.add(HugeEnum.A);
- hugeSet.add(HugeEnum.mm);
- complementHugeSet = EnumSet.complementOf(hugeSet);
- assertEquals(63, complementHugeSet.size());
-
- try {
- EnumSet.complementOf((EnumSet<HugeEnum>) null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
- }
-
- /**
- * @tests java.util.EnumSet#contains(Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ClassCastException, and NullPointerException.",
- method = "contains",
- args = {java.lang.Object.class}
- )
- public void test_contains_LObject() {
- Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- Enum[] elements = EnumFoo.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- set.add((EnumFoo)elements[i]);
- }
- boolean result = set.contains(null);
- assertFalse("Should not contain null:", result); //$NON-NLS-1$
-
- result = set.contains(EnumFoo.a);
- assertTrue("Should contain EnumFoo.a", result); //$NON-NLS-1$
- result = set.contains(EnumFoo.ll);
- assertTrue("Should contain EnumFoo.ll", result); //$NON-NLS-1$
-
- result = set.contains(EnumFoo.b);
- assertTrue("Should contain EnumFoo.b", result); //$NON-NLS-1$
-
- result = set.contains(new Object());
- assertFalse("Should not contain Object instance", result); //$NON-NLS-1$
-
- result = set.contains(EnumWithInnerClass.a);
- assertFalse("Should not contain EnumWithSubclass.a", result); //$NON-NLS-1$
-
- set = EnumSet.noneOf(EnumFoo.class);
- set.add(EnumFoo.aa);
- set.add(EnumFoo.bb);
- set.add(EnumFoo.cc);
-
- assertEquals("Size of set should be 3", 3, set.size()); //$NON-NLS-1$
- assertTrue("set should contain EnumFoo.aa", set.contains(EnumFoo.aa)); //$NON-NLS-1$
-
- Set<EnumWithInnerClass> setWithSubclass = EnumSet
- .noneOf(EnumWithInnerClass.class);
- setWithSubclass.add(EnumWithInnerClass.a);
- setWithSubclass.add(EnumWithInnerClass.b);
- setWithSubclass.add(EnumWithInnerClass.c);
- setWithSubclass.add(EnumWithInnerClass.d);
- setWithSubclass.add(EnumWithInnerClass.e);
- setWithSubclass.add(EnumWithInnerClass.f);
- result = setWithSubclass.contains(EnumWithInnerClass.f);
- assertTrue("Should contain EnumWithSubclass.f", result); //$NON-NLS-1$
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class);
- hugeSet.add(HugeEnum.a);
- result = hugeSet.contains(HugeEnum.a);
- assertTrue(result);
-
- result = hugeSet.contains(HugeEnum.b);
- assertTrue(result);
-
- result = hugeSet.contains(null);
- assertFalse(result);
-
- result = hugeSet.contains(HugeEnum.a);
- assertTrue(result);
-
- result = hugeSet.contains(HugeEnum.ll);
- assertTrue(result);
-
- result = hugeSet.contains(new Object());
- assertFalse(result);
-
- result = hugeSet.contains(Enum.class);
- assertFalse(result);
-
- }
-
- /**
- * @tests java.util.EnumSet#containsAll(Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "containsAll",
- args = {java.util.Collection.class}
- )
- @SuppressWarnings( { "unchecked", "boxing" })
- public void test_containsAll_LCollection() {
- EnumSet<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- Enum[] elements = EnumFoo.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- set.add((EnumFoo)elements[i]);
- }
- try {
- set.containsAll(null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- EnumSet<EmptyEnum> emptySet = EnumSet.noneOf(EmptyEnum.class);
- elements = EmptyEnum.class.getEnumConstants();
- for(int i = 0; i < elements.length; i++) {
- emptySet.add((EmptyEnum)elements[i]);
- }
- boolean result = set.containsAll(emptySet);
- assertTrue("Should return true", result); //$NON-NLS-1$
-
- Collection rawCollection = new ArrayList();
- result = set.containsAll(rawCollection);
- assertTrue("Should contain empty collection:", result); //$NON-NLS-1$
-
- rawCollection.add(1);
- result = set.containsAll(rawCollection);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- rawCollection.add(EnumWithInnerClass.a);
- result = set.containsAll(rawCollection);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- EnumSet rawSet = EnumSet.noneOf(EnumFoo.class);
- result = set.containsAll(rawSet);
- assertTrue("Should contain empty set", result); //$NON-NLS-1$
-
- emptySet = EnumSet.noneOf(EmptyEnum.class);
- result = set.containsAll(emptySet);
- assertTrue("No class cast should be performed on empty set", result); //$NON-NLS-1$
-
- Collection<EnumFoo> collection = new ArrayList<EnumFoo>();
- collection.add(EnumFoo.a);
- result = set.containsAll(collection);
- assertTrue("Should contain all elements in collection", result); //$NON-NLS-1$
-
- EnumSet<EnumFoo> fooSet = EnumSet.noneOf(EnumFoo.class);
- fooSet.add(EnumFoo.a);
- result = set.containsAll(fooSet);
- assertTrue("Should return true", result); //$NON-NLS-1$
-
- set.clear();
- try {
- set.containsAll(null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- Collection<EnumWithInnerClass> collectionWithSubclass = new ArrayList<EnumWithInnerClass>();
- collectionWithSubclass.add(EnumWithInnerClass.a);
- result = set.containsAll(collectionWithSubclass);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- EnumSet<EnumWithInnerClass> setWithSubclass = EnumSet
- .noneOf(EnumWithInnerClass.class);
- setWithSubclass.add(EnumWithInnerClass.a);
- result = set.containsAll(setWithSubclass);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
- hugeSet.add(HugeEnum.a);
- hugeSet.add(HugeEnum.b);
- hugeSet.add(HugeEnum.aa);
- hugeSet.add(HugeEnum.bb);
- hugeSet.add(HugeEnum.cc);
- hugeSet.add(HugeEnum.dd);
-
- Set<HugeEnum> anotherHugeSet = EnumSet.noneOf(HugeEnum.class);
- hugeSet.add(HugeEnum.b);
- hugeSet.add(HugeEnum.cc);
- result = hugeSet.containsAll(anotherHugeSet);
- assertTrue(result);
-
- try {
- hugeSet.containsAll(null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch(NullPointerException e) {
- // expected
- }
-
- Set<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet
- .noneOf(HugeEnumWithInnerClass.class);
- hugeSetWithInnerClass.add(HugeEnumWithInnerClass.a);
- hugeSetWithInnerClass.add(HugeEnumWithInnerClass.b);
- result = hugeSetWithInnerClass.containsAll(hugeSetWithInnerClass);
- assertTrue(result);
- result = hugeSet.containsAll(hugeSetWithInnerClass);
- assertFalse(result);
-
- rawCollection = new ArrayList();
- result = hugeSet.containsAll(rawCollection);
- assertTrue("Should contain empty collection:", result); //$NON-NLS-1$
-
- rawCollection.add(1);
- result = hugeSet.containsAll(rawCollection);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- rawCollection.add(EnumWithInnerClass.a);
- result = set.containsAll(rawCollection);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- rawSet = EnumSet.noneOf(HugeEnum.class);
- result = hugeSet.containsAll(rawSet);
- assertTrue("Should contain empty set", result); //$NON-NLS-1$
-
- EnumSet<HugeEnumWithInnerClass> emptyHugeSet
- = EnumSet.noneOf(HugeEnumWithInnerClass.class);
- result = hugeSet.containsAll(emptyHugeSet);
- assertTrue("No class cast should be performed on empty set", result); //$NON-NLS-1$
-
- Collection<HugeEnum> hugeCollection = new ArrayList<HugeEnum>();
- hugeCollection.add(HugeEnum.a);
- result = hugeSet.containsAll(hugeCollection);
- assertTrue("Should contain all elements in collection", result); //$NON-NLS-1$
-
- hugeSet.clear();
- try {
- hugeSet.containsAll(null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- Collection<HugeEnumWithInnerClass> hugeCollectionWithSubclass = new ArrayList<HugeEnumWithInnerClass>();
- hugeCollectionWithSubclass.add(HugeEnumWithInnerClass.a);
- result = hugeSet.containsAll(hugeCollectionWithSubclass);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- EnumSet<HugeEnumWithInnerClass> hugeSetWithSubclass = EnumSet
- .noneOf(HugeEnumWithInnerClass.class);
- hugeSetWithSubclass.add(HugeEnumWithInnerClass.a);
- result = hugeSet.containsAll(hugeSetWithSubclass);
- assertFalse("Should return false", result); //$NON-NLS-1$
- }
-
- /**
- * @tests java.util.EnumSet#copyOf(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "copyOf",
- args = {java.util.Collection.class}
- )
- @SuppressWarnings("unchecked")
- public void test_CopyOf_LCollection() {
- try {
- EnumSet.copyOf((Collection) null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
-
- Collection collection = new ArrayList();
- try {
- EnumSet.copyOf(collection);
- fail("Should throw IllegalArgumentException"); //$NON-NLS-1$
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- collection.add(new Object());
- try {
- EnumSet.copyOf(collection);
- fail("Should throw ClassCastException"); //$NON-NLS-1$
- } catch (ClassCastException e) {
- // expected
- }
-
- Collection<EnumFoo> enumCollection = new ArrayList<EnumFoo>();
- enumCollection.add(EnumFoo.b);
-
- EnumSet<EnumFoo> copyOfEnumCollection = EnumSet.copyOf(enumCollection);
- assertEquals("Size of copyOfEnumCollection should be 1:", //$NON-NLS-1$
- 1, copyOfEnumCollection.size());
- assertTrue("copyOfEnumCollection should contain EnumFoo.b:", //$NON-NLS-1$
- copyOfEnumCollection.contains(EnumFoo.b));
-
- enumCollection.add(null);
- assertEquals("Size of enumCollection should be 2:", //$NON-NLS-1$
- 2, enumCollection.size());
-
- try {
- copyOfEnumCollection = EnumSet.copyOf(enumCollection);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
-
- Collection rawEnumCollection = new ArrayList();
- rawEnumCollection.add(EnumFoo.a);
- rawEnumCollection.add(EnumWithInnerClass.a);
- try {
- EnumSet.copyOf(rawEnumCollection);
- fail("Should throw ClassCastException"); //$NON-NLS-1$
- } catch(ClassCastException e) {
- // expected
- }
-
- // test enum type with more than 64 elements
- Collection<HugeEnum> hugeEnumCollection = new ArrayList<HugeEnum>();
- hugeEnumCollection.add(HugeEnum.b);
-
- EnumSet<HugeEnum> copyOfHugeEnumCollection = EnumSet.copyOf(hugeEnumCollection);
- assertEquals(1, copyOfHugeEnumCollection.size());
- assertTrue(copyOfHugeEnumCollection.contains(HugeEnum.b));
-
- hugeEnumCollection.add(null);
- assertEquals(2, hugeEnumCollection.size());
-
- try {
- copyOfHugeEnumCollection = EnumSet.copyOf(hugeEnumCollection);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
-
- rawEnumCollection = new ArrayList();
- rawEnumCollection.add(HugeEnum.a);
- rawEnumCollection.add(HugeEnumWithInnerClass.a);
- try {
- EnumSet.copyOf(rawEnumCollection);
- fail("Should throw ClassCastException"); //$NON-NLS-1$
- } catch(ClassCastException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.EnumSet#copyOf(java.util.EnumSet)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "copyOf",
- args = {java.util.EnumSet.class}
- )
- @SuppressWarnings("unchecked")
- public void test_CopyOf_LEnumSet() {
- EnumSet<EnumWithInnerClass> enumSet = EnumSet
- .noneOf(EnumWithInnerClass.class);
- enumSet.add(EnumWithInnerClass.a);
- enumSet.add(EnumWithInnerClass.f);
- EnumSet<EnumWithInnerClass> copyOfE = EnumSet.copyOf(enumSet);
- assertEquals("Size of enumSet and copyOfE should be equal", //$NON-NLS-1$
- enumSet.size(), copyOfE.size());
-
- assertTrue("EnumWithSubclass.a should be contained in copyOfE", //$NON-NLS-1$
- copyOfE.contains(EnumWithInnerClass.a));
- assertTrue("EnumWithSubclass.f should be contained in copyOfE", //$NON-NLS-1$
- copyOfE.contains(EnumWithInnerClass.f));
-
- Object[] enumValue = copyOfE.toArray();
- assertSame("enumValue[0] should be identical with EnumWithSubclass.a", //$NON-NLS-1$
- enumValue[0], EnumWithInnerClass.a);
- assertSame("enumValue[1] should be identical with EnumWithSubclass.f", //$NON-NLS-1$
- enumValue[1], EnumWithInnerClass.f);
-
- try {
- EnumSet.copyOf((EnumSet) null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
-
- // test enum type with more than 64 elements
- EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet
- .noneOf(HugeEnumWithInnerClass.class);
- hugeEnumSet.add(HugeEnumWithInnerClass.a);
- hugeEnumSet.add(HugeEnumWithInnerClass.f);
- EnumSet<HugeEnumWithInnerClass> copyOfHugeEnum = EnumSet.copyOf(hugeEnumSet);
- assertEquals(enumSet.size(), copyOfE.size());
-
- assertTrue(copyOfHugeEnum.contains(HugeEnumWithInnerClass.a));
- assertTrue(copyOfHugeEnum.contains(HugeEnumWithInnerClass.f));
-
- Object[] hugeEnumValue = copyOfHugeEnum.toArray();
- assertSame(hugeEnumValue[0], HugeEnumWithInnerClass.a);
- assertSame(hugeEnumValue[1], HugeEnumWithInnerClass.f);
- }
-
- /**
- * @tests java.util.EnumSet#removeAll(Collection)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify UnsupportedOperationException, ClassCastException.",
- method = "removeAll",
- args = {java.util.Collection.class}
- )
- @SuppressWarnings("unchecked")
- public void test_removeAll_LCollection() {
- Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- try {
- set.removeAll(null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- set = EnumSet.allOf(EnumFoo.class);
- assertEquals("Size of set should be 64:", 64, set.size()); //$NON-NLS-1$
-
- try {
- set.removeAll(null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- Collection<EnumFoo> collection = new ArrayList<EnumFoo>();
- collection.add(EnumFoo.a);
-
- boolean result = set.removeAll(collection);
- assertTrue("Should return true", result); //$NON-NLS-1$
- assertEquals("Size of set should be 63", 63, set.size()); //$NON-NLS-1$
-
- collection = new ArrayList();
- result = set.removeAll(collection);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- Set<EmptyEnum> emptySet = EnumSet.noneOf(EmptyEnum.class);
- result = set.removeAll(emptySet);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- EnumSet<EnumFoo> emptyFooSet = EnumSet.noneOf(EnumFoo.class);
- result = set.removeAll(emptyFooSet);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- emptyFooSet.add(EnumFoo.a);
- result = set.removeAll(emptyFooSet);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- Set<EnumWithInnerClass> setWithSubclass = EnumSet
- .noneOf(EnumWithInnerClass.class);
- result = set.removeAll(setWithSubclass);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- setWithSubclass.add(EnumWithInnerClass.a);
- result = set.removeAll(setWithSubclass);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- Set<EnumFoo> anotherSet = EnumSet.noneOf(EnumFoo.class);
- anotherSet.add(EnumFoo.a);
-
- set = EnumSet.allOf(EnumFoo.class);
- result = set.removeAll(anotherSet);
- assertTrue("Should return true", result); //$NON-NLS-1$
- assertEquals("Size of set should be 63:", 63, set.size()); //$NON-NLS-1$
-
- Set<EnumWithInnerClass> setWithInnerClass = EnumSet
- .noneOf(EnumWithInnerClass.class);
- setWithInnerClass.add(EnumWithInnerClass.a);
- setWithInnerClass.add(EnumWithInnerClass.b);
-
- Set<EnumWithInnerClass> anotherSetWithInnerClass = EnumSet
- .noneOf(EnumWithInnerClass.class);
- anotherSetWithInnerClass.add(EnumWithInnerClass.c);
- anotherSetWithInnerClass.add(EnumWithInnerClass.d);
- result = anotherSetWithInnerClass.removeAll(setWithInnerClass);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- anotherSetWithInnerClass.add(EnumWithInnerClass.a);
- result = anotherSetWithInnerClass.removeAll(setWithInnerClass);
- assertTrue("Should return true", result); //$NON-NLS-1$
- assertEquals("Size of anotherSetWithInnerClass should remain 2", //$NON-NLS-1$
- 2, anotherSetWithInnerClass.size());
-
- anotherSetWithInnerClass.remove(EnumWithInnerClass.c);
- anotherSetWithInnerClass.remove(EnumWithInnerClass.d);
- result = anotherSetWithInnerClass.remove(setWithInnerClass);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- Set rawSet = EnumSet.allOf(EnumWithAllInnerClass.class);
- result = rawSet.removeAll(EnumSet.allOf(EnumFoo.class));
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- setWithInnerClass = EnumSet.allOf(EnumWithInnerClass.class);
- anotherSetWithInnerClass = EnumSet.allOf(EnumWithInnerClass.class);
- setWithInnerClass.remove(EnumWithInnerClass.a);
- anotherSetWithInnerClass.remove(EnumWithInnerClass.f);
- result = setWithInnerClass.removeAll(anotherSetWithInnerClass);
- assertTrue("Should return true", result); //$NON-NLS-1$
- assertEquals("Size of setWithInnerClass should be 1", 1, setWithInnerClass.size()); //$NON-NLS-1$
-
- result = setWithInnerClass.contains(EnumWithInnerClass.f);
- assertTrue("Should return true", result); //$NON-NLS-1$
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class);
-
- Collection<HugeEnum> hugeCollection = new ArrayList<HugeEnum>();
- hugeCollection.add(HugeEnum.a);
-
- result = hugeSet.removeAll(hugeCollection);
- assertTrue(result);
- assertEquals(64, hugeSet.size());
-
- collection = new ArrayList();
- result = hugeSet.removeAll(collection);
- assertFalse(result);
-
- Set<HugeEnum> emptyHugeSet = EnumSet.noneOf(HugeEnum.class);
- result = hugeSet.removeAll(emptyHugeSet);
- assertFalse(result);
-
- Set<HugeEnumWithInnerClass> hugeSetWithSubclass = EnumSet
- .noneOf(HugeEnumWithInnerClass.class);
- result = hugeSet.removeAll(hugeSetWithSubclass);
- assertFalse(result);
-
- hugeSetWithSubclass.add(HugeEnumWithInnerClass.a);
- result = hugeSet.removeAll(hugeSetWithSubclass);
- assertFalse(result);
-
- Set<HugeEnum> anotherHugeSet = EnumSet.noneOf(HugeEnum.class);
- anotherHugeSet.add(HugeEnum.a);
-
- hugeSet = EnumSet.allOf(HugeEnum.class);
- result = hugeSet.removeAll(anotherHugeSet);
- assertTrue(result);
- assertEquals(63, set.size());
-
- Set<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet
- .noneOf(HugeEnumWithInnerClass.class);
- hugeSetWithInnerClass.add(HugeEnumWithInnerClass.a);
- hugeSetWithInnerClass.add(HugeEnumWithInnerClass.b);
-
- Set<HugeEnumWithInnerClass> anotherHugeSetWithInnerClass = EnumSet
- .noneOf(HugeEnumWithInnerClass.class);
- anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.c);
- anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.d);
- result = anotherHugeSetWithInnerClass.removeAll(setWithInnerClass);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.a);
- result = anotherHugeSetWithInnerClass.removeAll(hugeSetWithInnerClass);
- assertTrue(result);
- assertEquals(2, anotherHugeSetWithInnerClass.size());
-
- anotherHugeSetWithInnerClass.remove(HugeEnumWithInnerClass.c);
- anotherHugeSetWithInnerClass.remove(HugeEnumWithInnerClass.d);
- result = anotherHugeSetWithInnerClass.remove(hugeSetWithInnerClass);
- assertFalse(result);
-
- rawSet = EnumSet.allOf(HugeEnumWithInnerClass.class);
- result = rawSet.removeAll(EnumSet.allOf(HugeEnum.class));
- assertFalse(result);
-
- hugeSetWithInnerClass = EnumSet.allOf(HugeEnumWithInnerClass.class);
- anotherHugeSetWithInnerClass = EnumSet.allOf(HugeEnumWithInnerClass.class);
- hugeSetWithInnerClass.remove(HugeEnumWithInnerClass.a);
- anotherHugeSetWithInnerClass.remove(HugeEnumWithInnerClass.f);
- result = hugeSetWithInnerClass.removeAll(anotherHugeSetWithInnerClass);
- assertTrue(result);
- assertEquals(1, hugeSetWithInnerClass.size());
-
- result = hugeSetWithInnerClass.contains(HugeEnumWithInnerClass.f);
- assertTrue(result);
- }
-
- /**
- * @tests java.util.EnumSet#retainAll(Collection)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify UnsupportedOperationException, ClassCastException.",
- method = "retainAll",
- args = {java.util.Collection.class}
- )
- @SuppressWarnings("unchecked")
- public void test_retainAll_LCollection() {
- Set<EnumFoo> set = EnumSet.allOf(EnumFoo.class);
-
- try {
- set.retainAll(null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- set.clear();
- boolean result = set.retainAll(null);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- Collection rawCollection = new ArrayList();
- result = set.retainAll(rawCollection);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- rawCollection.add(EnumFoo.a);
- result = set.retainAll(rawCollection);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- rawCollection.add(EnumWithInnerClass.a);
- result = set.retainAll(rawCollection);
- assertFalse("Should return false", result); //$NON-NLS-1$
- assertEquals("Size of set should be 0:", 0, set.size()); //$NON-NLS-1$
-
- rawCollection.remove(EnumFoo.a);
- result = set.retainAll(rawCollection);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- Set<EnumFoo> anotherSet = EnumSet.allOf(EnumFoo.class);
- result = set.retainAll(anotherSet);
- assertFalse("Should return false", result); //$NON-NLS-1$
- assertEquals("Size of set should be 0", 0, set.size()); //$NON-NLS-1$
-
- Set<EnumWithInnerClass> setWithInnerClass = EnumSet
- .allOf(EnumWithInnerClass.class);
- result = set.retainAll(setWithInnerClass);
- assertTrue("Should return true", result); //$NON-NLS-1$
- assertEquals("Size of set should be 0", 0, set.size()); //$NON-NLS-1$
-
- setWithInnerClass = EnumSet.noneOf(EnumWithInnerClass.class);
- result = set.retainAll(setWithInnerClass);
- assertTrue("Should return true", result); //$NON-NLS-1$
-
- Set<EmptyEnum> emptySet = EnumSet.allOf(EmptyEnum.class);
- result = set.retainAll(emptySet);
- assertTrue("Should return true", result); //$NON-NLS-1$
-
- Set<EnumWithAllInnerClass> setWithAllInnerClass = EnumSet
- .allOf(EnumWithAllInnerClass.class);
- result = set.retainAll(setWithAllInnerClass);
- assertTrue("Should return true", result); //$NON-NLS-1$
-
- set.add(EnumFoo.a);
- result = set.retainAll(setWithInnerClass);
- assertTrue("Should return true", result); //$NON-NLS-1$
- assertEquals("Size of set should be 0", 0, set.size()); //$NON-NLS-1$
-
- setWithInnerClass = EnumSet.allOf(EnumWithInnerClass.class);
- setWithInnerClass.remove(EnumWithInnerClass.f);
- Set<EnumWithInnerClass> anotherSetWithInnerClass = EnumSet
- .noneOf(EnumWithInnerClass.class);
- anotherSetWithInnerClass.add(EnumWithInnerClass.e);
- anotherSetWithInnerClass.add(EnumWithInnerClass.f);
-
- result = setWithInnerClass.retainAll(anotherSetWithInnerClass);
- assertTrue("Should return true", result); //$NON-NLS-1$
- result = setWithInnerClass.contains(EnumWithInnerClass.e);
- assertTrue("Should contain EnumWithInnerClass.e", result); //$NON-NLS-1$
- result = setWithInnerClass.contains(EnumWithInnerClass.b);
- assertFalse("Should not contain EnumWithInnerClass.b", result); //$NON-NLS-1$
- assertEquals("Size of set should be 1:", 1, setWithInnerClass.size()); //$NON-NLS-1$
-
- anotherSetWithInnerClass = EnumSet.allOf(EnumWithInnerClass.class);
- result = setWithInnerClass.retainAll(anotherSetWithInnerClass);
-
- assertFalse("Return value should be false", result); //$NON-NLS-1$
-
- rawCollection = new ArrayList();
- rawCollection.add(EnumWithInnerClass.e);
- rawCollection.add(EnumWithInnerClass.f);
- result = setWithInnerClass.retainAll(rawCollection);
- assertFalse("Should return false", result); //$NON-NLS-1$
-
- set = EnumSet.allOf(EnumFoo.class);
- set.remove(EnumFoo.a);
- anotherSet = EnumSet.noneOf(EnumFoo.class);
- anotherSet.add(EnumFoo.a);
- result = set.retainAll(anotherSet);
- assertTrue("Should return true", result); //$NON-NLS-1$
- assertEquals("size should be 0", 0, set.size()); //$NON-NLS-1$
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class);
-
- try {
- hugeSet.retainAll(null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- hugeSet.clear();
- result = hugeSet.retainAll(null);
- assertFalse(result);
-
- rawCollection = new ArrayList();
- result = hugeSet.retainAll(rawCollection);
- assertFalse(result);
-
- rawCollection.add(HugeEnum.a);
- result = hugeSet.retainAll(rawCollection);
- assertFalse(result);
-
- rawCollection.add(HugeEnumWithInnerClass.a);
- result = hugeSet.retainAll(rawCollection);
- assertFalse(result);
- assertEquals(0, set.size());
-
- rawCollection.remove(HugeEnum.a);
- result = set.retainAll(rawCollection);
- assertFalse(result);
-
- Set<HugeEnum> anotherHugeSet = EnumSet.allOf(HugeEnum.class);
- result = hugeSet.retainAll(anotherHugeSet);
- assertFalse(result);
- assertEquals(0, hugeSet.size());
-
- Set<HugeEnumWithInnerClass> hugeSetWithInnerClass = EnumSet
- .allOf(HugeEnumWithInnerClass.class);
- result = hugeSet.retainAll(hugeSetWithInnerClass);
- assertTrue(result);
- assertEquals(0, hugeSet.size());
-
- hugeSetWithInnerClass = EnumSet.noneOf(HugeEnumWithInnerClass.class);
- result = hugeSet.retainAll(hugeSetWithInnerClass);
- assertTrue(result);
-
- Set<HugeEnumWithInnerClass> hugeSetWithAllInnerClass = EnumSet
- .allOf(HugeEnumWithInnerClass.class);
- result = hugeSet.retainAll(hugeSetWithAllInnerClass);
- assertTrue(result);
-
- hugeSet.add(HugeEnum.a);
- result = hugeSet.retainAll(hugeSetWithInnerClass);
- assertTrue(result);
- assertEquals(0, hugeSet.size());
-
- hugeSetWithInnerClass = EnumSet.allOf(HugeEnumWithInnerClass.class);
- hugeSetWithInnerClass.remove(HugeEnumWithInnerClass.f);
- Set<HugeEnumWithInnerClass> anotherHugeSetWithInnerClass = EnumSet
- .noneOf(HugeEnumWithInnerClass.class);
- anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.e);
- anotherHugeSetWithInnerClass.add(HugeEnumWithInnerClass.f);
-
- result = hugeSetWithInnerClass.retainAll(anotherHugeSetWithInnerClass);
- assertTrue(result);
- result = hugeSetWithInnerClass.contains(HugeEnumWithInnerClass.e);
- assertTrue("Should contain HugeEnumWithInnerClass.e", result); //$NON-NLS-1$
- result = hugeSetWithInnerClass.contains(HugeEnumWithInnerClass.b);
- assertFalse("Should not contain HugeEnumWithInnerClass.b", result); //$NON-NLS-1$
- assertEquals("Size of hugeSet should be 1:", 1, hugeSetWithInnerClass.size()); //$NON-NLS-1$
-
- anotherHugeSetWithInnerClass = EnumSet.allOf(HugeEnumWithInnerClass.class);
- result = hugeSetWithInnerClass.retainAll(anotherHugeSetWithInnerClass);
-
- assertFalse("Return value should be false", result); //$NON-NLS-1$
-
- rawCollection = new ArrayList();
- rawCollection.add(HugeEnumWithInnerClass.e);
- rawCollection.add(HugeEnumWithInnerClass.f);
- result = hugeSetWithInnerClass.retainAll(rawCollection);
- assertFalse(result);
-
- hugeSet = EnumSet.allOf(HugeEnum.class);
- hugeSet.remove(HugeEnum.a);
- anotherHugeSet = EnumSet.noneOf(HugeEnum.class);
- anotherHugeSet.add(HugeEnum.a);
- result = hugeSet.retainAll(anotherHugeSet);
- assertTrue(result);
- assertEquals(0, hugeSet.size());
- }
-
- /**
- * @tests java.util.EnumSet#iterator()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "iterator",
- args = {}
- )
- public void test_iterator() {
- Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
- set.add(EnumFoo.a);
- set.add(EnumFoo.b);
-
- Iterator<EnumFoo> iterator = set.iterator();
- Iterator<EnumFoo> anotherIterator = set.iterator();
- assertNotSame("Should not be same", iterator, anotherIterator); //$NON-NLS-1$
- try {
- iterator.remove();
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
- // expectedd
- }
-
- assertTrue("Should has next element:", iterator.hasNext()); //$NON-NLS-1$
- assertSame("Should be identical", EnumFoo.a, iterator.next()); //$NON-NLS-1$
- iterator.remove();
- assertTrue("Should has next element:", iterator.hasNext()); //$NON-NLS-1$
- assertSame("Should be identical", EnumFoo.b, iterator.next()); //$NON-NLS-1$
- assertFalse("Should not has next element:", iterator.hasNext()); //$NON-NLS-1$
- assertFalse("Should not has next element:", iterator.hasNext()); //$NON-NLS-1$
-
- assertEquals("Size should be 1:", 1, set.size()); //$NON-NLS-1$
-
- try {
- iterator.next();
- fail("Should throw NoSuchElementException"); //$NON-NLS-1$
- } catch (NoSuchElementException e) {
- // expected
- }
- set = EnumSet.noneOf(EnumFoo.class);
- set.add(EnumFoo.a);
- iterator = set.iterator();
- assertEquals("Should be equal", EnumFoo.a, iterator.next()); //$NON-NLS-1$
- iterator.remove();
- try {
- iterator.remove();
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch(IllegalStateException e) {
- // expected
- }
-
- Set<EmptyEnum> emptySet = EnumSet.allOf(EmptyEnum.class);
- Iterator<EmptyEnum> emptyIterator = emptySet.iterator();
- try {
- emptyIterator.next();
- fail("Should throw NoSuchElementException"); //$NON-NLS-1$
- } catch (NoSuchElementException e) {
- // expected
- }
-
- Set<EnumWithInnerClass> setWithSubclass = EnumSet
- .allOf(EnumWithInnerClass.class);
- setWithSubclass.remove(EnumWithInnerClass.e);
- Iterator<EnumWithInnerClass> iteratorWithSubclass = setWithSubclass
- .iterator();
- assertSame("Should be same", EnumWithInnerClass.a, iteratorWithSubclass.next()); //$NON-NLS-1$
-
- assertTrue("Should return true", iteratorWithSubclass.hasNext()); //$NON-NLS-1$
- assertSame("Should be same", EnumWithInnerClass.b, iteratorWithSubclass.next()); //$NON-NLS-1$
-
- setWithSubclass.remove(EnumWithInnerClass.c);
- assertTrue("Should return true", iteratorWithSubclass.hasNext()); //$NON-NLS-1$
- assertSame("Should be same", EnumWithInnerClass.c, iteratorWithSubclass.next()); //$NON-NLS-1$
-
- assertTrue("Should return true", iteratorWithSubclass.hasNext()); //$NON-NLS-1$
- assertSame("Should be same", EnumWithInnerClass.d, iteratorWithSubclass.next()); //$NON-NLS-1$
-
- setWithSubclass.add(EnumWithInnerClass.e);
- assertTrue("Should return true", iteratorWithSubclass.hasNext()); //$NON-NLS-1$
- assertSame("Should be same", EnumWithInnerClass.f, iteratorWithSubclass.next()); //$NON-NLS-1$
-
- set = EnumSet.noneOf(EnumFoo.class);
- iterator = set.iterator();
- try {
- iterator.next();
- fail("Should throw NoSuchElementException"); //$NON-NLS-1$
- } catch (NoSuchElementException e) {
- // expected
- }
-
- set.add(EnumFoo.a);
- iterator = set.iterator();
- assertEquals("Should return EnumFoo.a", EnumFoo.a, iterator.next()); //$NON-NLS-1$
- assertEquals("Size of set should be 1", 1, set.size()); //$NON-NLS-1$
- iterator.remove();
- assertEquals("Size of set should be 0", 0, set.size()); //$NON-NLS-1$
- assertFalse("Should return false", set.contains(EnumFoo.a)); //$NON-NLS-1$
-
- set.add(EnumFoo.a);
- set.add(EnumFoo.b);
- iterator = set.iterator();
- assertEquals("Should be equals", EnumFoo.a, iterator.next()); //$NON-NLS-1$
- iterator.remove();
- try {
- iterator.remove();
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch(IllegalStateException e) {
- // expected
- }
-
- assertTrue("Should have next element", iterator.hasNext()); //$NON-NLS-1$
- try {
- iterator.remove();
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
- // expected
- }
- assertEquals("Size of set should be 1", 1, set.size()); //$NON-NLS-1$
- assertTrue("Should have next element", iterator.hasNext()); //$NON-NLS-1$
- assertEquals("Should return EnumFoo.b", EnumFoo.b, iterator.next()); //$NON-NLS-1$
- set.remove(EnumFoo.b);
- assertEquals("Size of set should be 0", 0, set.size()); //$NON-NLS-1$
- iterator.remove();
- assertFalse("Should return false", set.contains(EnumFoo.a)); //$NON-NLS-1$
-
- // RI's bug, EnumFoo.b should not exist at the moment.
- if (!disableRIBugs) {
- assertFalse("Should return false", set.contains(EnumFoo.b)); //$NON-NLS-1$
- }
-
- // test enum type with more than 64 elements
- Set<HugeEnum> hugeSet = EnumSet.noneOf(HugeEnum.class);
- hugeSet.add(HugeEnum.a);
- hugeSet.add(HugeEnum.b);
-
- Iterator<HugeEnum> hIterator = hugeSet.iterator();
- Iterator<HugeEnum> anotherHugeIterator = hugeSet.iterator();
- assertNotSame(hIterator, anotherHugeIterator);
- try {
- hIterator.remove();
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
- // expectedd
- }
-
- assertTrue(hIterator.hasNext());
- assertSame(HugeEnum.a, hIterator.next());
- hIterator.remove();
- assertTrue(hIterator.hasNext());
- assertSame(HugeEnum.b, hIterator.next());
- assertFalse(hIterator.hasNext());
- assertFalse(hIterator.hasNext());
-
- assertEquals(1, hugeSet.size());
-
- try {
- hIterator.next();
- fail("Should throw NoSuchElementException"); //$NON-NLS-1$
- } catch (NoSuchElementException e) {
- // expected
- }
-
- Set<HugeEnumWithInnerClass> hugeSetWithSubclass = EnumSet
- .allOf(HugeEnumWithInnerClass.class);
- hugeSetWithSubclass.remove(HugeEnumWithInnerClass.e);
- Iterator<HugeEnumWithInnerClass> hugeIteratorWithSubclass = hugeSetWithSubclass
- .iterator();
- assertSame(HugeEnumWithInnerClass.a, hugeIteratorWithSubclass.next());
-
- assertTrue(hugeIteratorWithSubclass.hasNext());
- assertSame(HugeEnumWithInnerClass.b, hugeIteratorWithSubclass.next());
-
- setWithSubclass.remove(HugeEnumWithInnerClass.c);
- assertTrue(hugeIteratorWithSubclass.hasNext());
- assertSame(HugeEnumWithInnerClass.c, hugeIteratorWithSubclass.next());
-
- assertTrue(hugeIteratorWithSubclass.hasNext());
- assertSame(HugeEnumWithInnerClass.d, hugeIteratorWithSubclass.next());
-
- hugeSetWithSubclass.add(HugeEnumWithInnerClass.e);
- assertTrue(hugeIteratorWithSubclass.hasNext());
- assertSame(HugeEnumWithInnerClass.f, hugeIteratorWithSubclass.next());
-
- hugeSet = EnumSet.noneOf(HugeEnum.class);
- hIterator = hugeSet.iterator();
- try {
- hIterator.next();
- fail("Should throw NoSuchElementException"); //$NON-NLS-1$
- } catch (NoSuchElementException e) {
- // expected
- }
-
- hugeSet.add(HugeEnum.a);
- hIterator = hugeSet.iterator();
- assertEquals(HugeEnum.a, hIterator.next());
- assertEquals(1, hugeSet.size());
- hIterator.remove();
- assertEquals(0, hugeSet.size());
- assertFalse(hugeSet.contains(HugeEnum.a));
-
- hugeSet.add(HugeEnum.a);
- hugeSet.add(HugeEnum.b);
- hIterator = hugeSet.iterator();
- hIterator.next();
- hIterator.remove();
-
- assertTrue(hIterator.hasNext());
- try {
- hIterator.remove();
- fail("Should throw IllegalStateException"); //$NON-NLS-1$
- } catch (IllegalStateException e) {
- // expected
- }
- assertEquals(1, hugeSet.size());
- assertTrue(hIterator.hasNext());
- assertEquals(HugeEnum.b, hIterator.next());
- hugeSet.remove(HugeEnum.b);
- assertEquals(0, hugeSet.size());
- hIterator.remove();
- assertFalse(hugeSet.contains(HugeEnum.a));
- // RI's bug, EnumFoo.b should not exist at the moment.
- if(!disableRIBugs) {
- assertFalse("Should return false", set.contains(EnumFoo.b)); //$NON-NLS-1$
- }
- }
-
- /**
- * @tests java.util.EnumSet#of(E)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "of",
- args = {java.lang.Enum.class}
- )
- public void test_Of_E() {
- EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a);
- assertEquals("enumSet should have length 1:", 1, enumSet.size()); //$NON-NLS-1$
-
- assertTrue("enumSet should contain EnumWithSubclass.a:", //$NON-NLS-1$
- enumSet.contains(EnumWithInnerClass.a));
-
- try {
- EnumSet.of((EnumWithInnerClass) null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
-
- // test enum type with more than 64 elements
- EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a);
- assertEquals(1, hugeEnumSet.size());
-
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a));
- }
-
- /**
- * @tests java.util.EnumSet#of(E, E)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "of",
- args = {java.lang.Enum.class, java.lang.Enum.class}
- )
- public void test_Of_EE() {
- EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a,
- EnumWithInnerClass.b);
- assertEquals("enumSet should have length 2:", 2, enumSet.size()); //$NON-NLS-1$
-
- assertTrue("enumSet should contain EnumWithSubclass.a:", //$NON-NLS-1$
- enumSet.contains(EnumWithInnerClass.a));
- assertTrue("enumSet should contain EnumWithSubclass.b:", //$NON-NLS-1$
- enumSet.contains(EnumWithInnerClass.b));
-
- try {
- EnumSet.of((EnumWithInnerClass) null, EnumWithInnerClass.a);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
-
- try {
- EnumSet.of( EnumWithInnerClass.a, (EnumWithInnerClass) null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
-
- try {
- EnumSet.of( (EnumWithInnerClass) null, (EnumWithInnerClass) null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
-
- enumSet = EnumSet.of(EnumWithInnerClass.a, EnumWithInnerClass.a);
- assertEquals("Size of enumSet should be 1", //$NON-NLS-1$
- 1, enumSet.size());
-
- // test enum type with more than 64 elements
- EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a,
- HugeEnumWithInnerClass.b);
- assertEquals(2, hugeEnumSet.size());
-
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a));
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.b));
-
- try {
- EnumSet.of((HugeEnumWithInnerClass) null, HugeEnumWithInnerClass.a);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
-
- try {
- EnumSet.of( HugeEnumWithInnerClass.a, (HugeEnumWithInnerClass) null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
-
- try {
- EnumSet.of( (HugeEnumWithInnerClass) null, (HugeEnumWithInnerClass) null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
-
- hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.a);
- assertEquals(1, hugeEnumSet.size());
- }
-
- /**
- * @tests java.util.EnumSet#of(E, E, E)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "of",
- args = {java.lang.Enum.class, java.lang.Enum.class, java.lang.Enum.class}
- )
- public void test_Of_EEE() {
- EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a,
- EnumWithInnerClass.b, EnumWithInnerClass.c);
- assertEquals("Size of enumSet should be 3:", 3, enumSet.size()); //$NON-NLS-1$
-
- assertTrue(
- "enumSet should contain EnumWithSubclass.a:", enumSet.contains(EnumWithInnerClass.a)); //$NON-NLS-1$
- assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.c)); //$NON-NLS-1$
-
- try {
- EnumSet.of((EnumWithInnerClass) null, null, null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
-
- enumSet = EnumSet.of(EnumWithInnerClass.a, EnumWithInnerClass.b,
- EnumWithInnerClass.b);
- assertEquals("enumSet should contain 2 elements:", 2, enumSet.size()); //$NON-NLS-1$
-
- // test enum type with more than 64 elements
- EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a,
- HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.c);
- assertEquals(3, hugeEnumSet.size());
-
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a));
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.c));
-
- try {
- EnumSet.of((HugeEnumWithInnerClass) null, null, null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
-
- hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.b,
- HugeEnumWithInnerClass.b);
- assertEquals(2, hugeEnumSet.size());
- }
-
- /**
- * @tests java.util.EnumSet#of(E, E, E, E)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "of",
- args = {java.lang.Enum.class, java.lang.Enum.class, java.lang.Enum.class, java.lang.Enum.class}
- )
- public void test_Of_EEEE() {
- EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a,
- EnumWithInnerClass.b, EnumWithInnerClass.c,
- EnumWithInnerClass.d);
- assertEquals("Size of enumSet should be 4", 4, enumSet.size()); //$NON-NLS-1$
-
- assertTrue(
- "enumSet should contain EnumWithSubclass.a:", enumSet.contains(EnumWithInnerClass.a)); //$NON-NLS-1$
- assertTrue("enumSet should contain EnumWithSubclass.d:", enumSet //$NON-NLS-1$
- .contains(EnumWithInnerClass.d));
-
- try {
- EnumSet.of((EnumWithInnerClass) null, null, null, null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
-
- // test enum type with more than 64 elements
- EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a,
- HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.c,
- HugeEnumWithInnerClass.d);
- assertEquals(4, hugeEnumSet.size());
-
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a));
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.d));
-
- try {
- EnumSet.of((HugeEnumWithInnerClass) null, null, null, null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
- }
-
- /**
- * @tests java.util.EnumSet#of(E, E, E, E, E)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "of",
- args = {java.lang.Enum.class, java.lang.Enum.class, java.lang.Enum.class, java.lang.Enum.class, java.lang.Enum.class}
- )
- public void test_Of_EEEEE() {
- EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a,
- EnumWithInnerClass.b, EnumWithInnerClass.c,
- EnumWithInnerClass.d, EnumWithInnerClass.e);
- assertEquals("Size of enumSet should be 5:", 5, enumSet.size()); //$NON-NLS-1$
-
- assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.a)); //$NON-NLS-1$
- assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.e)); //$NON-NLS-1$
-
- try {
- EnumSet.of((EnumWithInnerClass) null, null, null, null, null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
-
- // test enum with more than 64 elements
- EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a,
- HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.c,
- HugeEnumWithInnerClass.d, HugeEnumWithInnerClass.e);
- assertEquals(5, hugeEnumSet.size());
-
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a));
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.e));
-
- try {
- EnumSet.of((HugeEnumWithInnerClass) null, null, null, null, null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
- }
-
- /**
- * @tests java.util.EnumSet#of(E, E...)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "of",
- args = {java.lang.Enum.class, java.lang.Enum[].class}
- )
- public void test_Of_EEArray() {
- EnumWithInnerClass[] enumArray = new EnumWithInnerClass[] {
- EnumWithInnerClass.b, EnumWithInnerClass.c };
- EnumSet<EnumWithInnerClass> enumSet = EnumSet.of(EnumWithInnerClass.a,
- enumArray);
- assertEquals("Should be equal", 3, enumSet.size()); //$NON-NLS-1$
-
- assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.a)); //$NON-NLS-1$
- assertTrue("Should return true", enumSet.contains(EnumWithInnerClass.c)); //$NON-NLS-1$
-
- try {
- EnumSet.of(EnumWithInnerClass.a, (EnumWithInnerClass[])null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
-
- EnumFoo[] foos = {EnumFoo.a, EnumFoo.c, EnumFoo.d};
- EnumSet<EnumFoo> set = EnumSet.of(EnumFoo.c, foos);
- assertEquals("size of set should be 1", 3, set.size()); //$NON-NLS-1$
- assertTrue("Should contain EnumFoo.a", set.contains(EnumFoo.a)); //$NON-NLS-1$
- assertTrue("Should contain EnumFoo.c", set.contains(EnumFoo.c)); //$NON-NLS-1$
- assertTrue("Should contain EnumFoo.d", set.contains(EnumFoo.d)); //$NON-NLS-1$
-
- // test enum type with more than 64 elements
- HugeEnumWithInnerClass[] hugeEnumArray = new HugeEnumWithInnerClass[] {
- HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.c };
- EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.of(HugeEnumWithInnerClass.a,
- hugeEnumArray);
- assertEquals(3, hugeEnumSet.size());
-
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.a));
- assertTrue(hugeEnumSet.contains(HugeEnumWithInnerClass.c));
-
- try {
- EnumSet.of(HugeEnumWithInnerClass.a, (HugeEnumWithInnerClass[])null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException npe) {
- // expected
- }
-
- HugeEnumWithInnerClass[] huges = {HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.c, HugeEnumWithInnerClass.d};
- EnumSet<HugeEnumWithInnerClass> hugeSet = EnumSet.of(HugeEnumWithInnerClass.c, huges);
- assertEquals(3, hugeSet.size());
- assertTrue(hugeSet.contains(HugeEnumWithInnerClass.a));
- assertTrue(hugeSet.contains(HugeEnumWithInnerClass.c));
- assertTrue(hugeSet.contains(HugeEnumWithInnerClass.d));
- }
-
- /**
- * @tests java.util.EnumSet#range(E, E)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "range",
- args = {java.lang.Enum.class, java.lang.Enum.class}
- )
- public void test_Range_EE() {
- try {
- EnumSet.range(EnumWithInnerClass.c, null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- EnumSet.range(null, EnumWithInnerClass.c);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- EnumSet.range(null, (EnumWithInnerClass) null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- EnumSet.range(EnumWithInnerClass.b, EnumWithInnerClass.a);
- fail("Should throw IllegalArgumentException"); //$NON-NLS-1$
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- EnumSet<EnumWithInnerClass> enumSet = EnumSet.range(
- EnumWithInnerClass.a, EnumWithInnerClass.a);
- assertEquals("Size of enumSet should be 1", 1, enumSet.size()); //$NON-NLS-1$
-
- enumSet = EnumSet.range(
- EnumWithInnerClass.a, EnumWithInnerClass.c);
- assertEquals("Size of enumSet should be 3", 3, enumSet.size()); //$NON-NLS-1$
-
- // test enum with more than 64 elements
- try {
- EnumSet.range(HugeEnumWithInnerClass.c, null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- EnumSet.range(null, HugeEnumWithInnerClass.c);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- EnumSet.range(null, (HugeEnumWithInnerClass) null);
- fail("Should throw NullPointerException"); //$NON-NLS-1$
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- EnumSet.range(HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.a);
- fail("Should throw IllegalArgumentException"); //$NON-NLS-1$
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- EnumSet<HugeEnumWithInnerClass> hugeEnumSet = EnumSet.range(
- HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.a);
- assertEquals(1, hugeEnumSet.size());
-
- hugeEnumSet = EnumSet.range(
- HugeEnumWithInnerClass.c, HugeEnumWithInnerClass.aa);
- assertEquals(51, hugeEnumSet.size());
-
- hugeEnumSet = EnumSet.range(
- HugeEnumWithInnerClass.a, HugeEnumWithInnerClass.mm);
- assertEquals(65, hugeEnumSet.size());
-
- hugeEnumSet = EnumSet.range(
- HugeEnumWithInnerClass.b, HugeEnumWithInnerClass.mm);
- assertEquals(64, hugeEnumSet.size());
- }
-
- /**
- * @tests java.util.EnumSet#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_Clone() {
- EnumSet<EnumFoo> enumSet = EnumSet.allOf(EnumFoo.class);
- EnumSet<EnumFoo> clonedEnumSet = enumSet.clone();
- assertEquals(enumSet, clonedEnumSet);
- assertNotSame(enumSet, clonedEnumSet);
- assertTrue(clonedEnumSet.contains(EnumFoo.a));
- assertTrue(clonedEnumSet.contains(EnumFoo.b));
- assertEquals(64, clonedEnumSet.size());
-
- // test enum type with more than 64 elements
- EnumSet<HugeEnum> hugeEnumSet = EnumSet.allOf(HugeEnum.class);
- EnumSet<HugeEnum> hugeClonedEnumSet = hugeEnumSet.clone();
- assertEquals(hugeEnumSet, hugeClonedEnumSet);
- assertNotSame(hugeEnumSet, hugeClonedEnumSet);
- assertTrue(hugeClonedEnumSet.contains(HugeEnum.a));
- assertTrue(hugeClonedEnumSet.contains(HugeEnum.b));
- assertEquals(65, hugeClonedEnumSet.size());
-
- hugeClonedEnumSet.remove(HugeEnum.a);
- assertEquals(64, hugeClonedEnumSet.size());
- assertFalse(hugeClonedEnumSet.contains(HugeEnum.a));
- assertEquals(65, hugeEnumSet.size());
- assertTrue(hugeEnumSet.contains(HugeEnum.a));
- }
-
- /**
- * @tests java.util.EnumSet#Serialization()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- )
- public void test_serialization() throws Exception {
- EnumSet<EnumFoo> set = EnumSet.allOf(EnumFoo.class);
- SerializationTest.verifySelf(set);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- )
- @SuppressWarnings( { "unchecked", "boxing" })
- public void testSerializationCompatibility() throws Exception {
- EnumSet<EnumFoo> set = EnumSet.allOf(EnumFoo.class);
- SerializationTest.verifyGolden(this, set);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/EventObjectTest.java b/luni/src/test/java/tests/api/java/util/EventObjectTest.java
deleted file mode 100644
index f86ac92..0000000
--- a/luni/src/test/java/tests/api/java/util/EventObjectTest.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.EventObject;
-
-@TestTargetClass(EventObject.class)
-public class EventObjectTest extends junit.framework.TestCase {
-
- Object myObject;
-
- EventObject myEventObject;
-
- /**
- * @tests java.util.EventObject#EventObject(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "See setUp method.",
- method = "EventObject",
- args = {java.lang.Object.class}
- )
- public void test_ConstructorLjava_lang_Object() {
- try {
- new EventObject(null);
- fail ("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.EventObject#getSource()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSource",
- args = {}
- )
- public void test_getSource() {
- // Test for method java.lang.Object java.util.EventObject.getSource()
- assertTrue("Wrong source returned",
- myEventObject.getSource() == myObject);
- }
-
- /**
- * @tests java.util.EventObject#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.util.EventObject.toString()
- assertTrue("Incorrect toString returned: " + myEventObject.toString(),
- myEventObject.toString().indexOf(
- "java.util.EventObject[source=java.lang.Object@") == 0);
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- myObject = new Object();
- myEventObject = new EventObject(myObject);
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/FormattableFlagsTest.java b/luni/src/test/java/tests/api/java/util/FormattableFlagsTest.java
deleted file mode 100644
index 3548b64..0000000
--- a/luni/src/test/java/tests/api/java/util/FormattableFlagsTest.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/* 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.FormattableFlags;
-import junit.framework.TestCase;
-
-@TestTargetClass(FormattableFlags.class)
-public class FormattableFlagsTest extends TestCase {
-
- /**
- * @test java.util.FormattableFlags ConstantFieldValues
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies fields.",
- method = "!Constants",
- args = {}
- )
- public void test_ConstantFieldValues() {
- assertEquals(1, FormattableFlags.LEFT_JUSTIFY);
- assertEquals(2, FormattableFlags.UPPERCASE);
- assertEquals(4, FormattableFlags.ALTERNATE);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/FormatterTest.java b/luni/src/test/java/tests/api/java/util/FormatterTest.java
deleted file mode 100644
index 6e1c86e..0000000
--- a/luni/src/test/java/tests/api/java/util/FormatterTest.java
+++ /dev/null
@@ -1,4692 +0,0 @@
-/* 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.AndroidOnly;
-
-import java.io.BufferedOutputStream;
-import java.io.Closeable;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.FilePermission;
-import java.io.Flushable;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.PipedOutputStream;
-import java.io.PrintStream;
-import java.io.UnsupportedEncodingException;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.nio.charset.Charset;
-import java.security.Permission;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.DuplicateFormatFlagsException;
-import java.util.FormatFlagsConversionMismatchException;
-import java.util.Formattable;
-import java.util.FormattableFlags;
-import java.util.Formatter;
-import java.util.FormatterClosedException;
-import java.util.IllegalFormatCodePointException;
-import java.util.IllegalFormatConversionException;
-import java.util.IllegalFormatException;
-import java.util.IllegalFormatFlagsException;
-import java.util.IllegalFormatPrecisionException;
-import java.util.IllegalFormatWidthException;
-import java.util.Locale;
-import java.util.MissingFormatArgumentException;
-import java.util.MissingFormatWidthException;
-import java.util.TimeZone;
-import java.util.UnknownFormatConversionException;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(Formatter.class)
-public class FormatterTest extends TestCase {
-
- class MockAppendable implements Appendable {
- public Appendable append(CharSequence arg0) throws IOException {
- return null;
- }
-
- public Appendable append(char arg0) throws IOException {
- return null;
- }
-
- public Appendable append(CharSequence arg0, int arg1, int arg2)
- throws IOException {
- return null;
- }
- }
-
- class MockSecurityManager extends SecurityManager {
- public void checkPermission(Permission p) {
- if (p.getActions().equals("write") && p instanceof FilePermission) {
- throw new SecurityException("Always throw security exception");
- }
- }
-
- public void checkPermission(Permission p, Object ctx) {
- checkPermission(p);
- }
- }
-
- class MockFormattable implements Formattable {
- public void formatTo(Formatter formatter, int flags, int width,
- int precision) throws IllegalFormatException {
- if ((flags & FormattableFlags.UPPERCASE) != 0) {
- formatter.format("CUSTOMIZED FORMAT FUNCTION" + " WIDTH: "
- + width + " PRECISION: " + precision);
- } else {
- formatter.format("customized format function" + " width: "
- + width + " precision: " + precision);
- }
- }
-
- public String toString() {
- return "formattable object";
- }
-
- public int hashCode() {
- return 0xf;
- }
- }
-
- class MockDestination implements Appendable, Flushable {
-
- private StringBuilder data = new StringBuilder();
-
- private boolean enabled = false;
-
- public Appendable append(char c) throws IOException {
- if (enabled) {
- data.append(c);
- enabled = true; // enable it after the first append
- } else {
- throw new IOException();
- }
- return this;
- }
-
- public Appendable append(CharSequence csq) throws IOException {
- if (enabled) {
- data.append(csq);
- enabled = true; // enable it after the first append
- } else {
- throw new IOException();
- }
- return this;
- }
-
- public Appendable append(CharSequence csq, int start, int end)
- throws IOException {
- if (enabled) {
- data.append(csq, start, end);
- enabled = true; // enable it after the first append
- } else {
- throw new IOException();
- }
- return this;
- }
-
- public void flush() throws IOException {
- throw new IOException("Always throw IOException");
- }
-
- public String toString() {
- return data.toString();
- }
- }
-
- private File notExist;
-
- private File fileWithContent;
-
- private File readOnly;
-
- private File secret;
-
- private TimeZone defaultTimeZone;
-
- /**
- * @tests java.util.Formatter#Formatter()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Formatter",
- args = {}
- )
- public void test_Constructor() {
- Formatter f = new Formatter();
- assertNotNull(f);
- assertTrue(f.out() instanceof StringBuilder);
- assertEquals(f.locale(), Locale.getDefault());
- assertNotNull(f.toString());
- }
-
- /**
- * @tests java.util.Formatter#Formatter(Appendable)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Formatter",
- args = {java.lang.Appendable.class}
- )
- public void test_ConstructorLjava_lang_Appendable() {
- MockAppendable ma = new MockAppendable();
- Formatter f1 = new Formatter(ma);
- assertEquals(ma, f1.out());
- assertEquals(f1.locale(), Locale.getDefault());
- assertNotNull(f1.toString());
-
- Formatter f2 = new Formatter((Appendable) null);
- /*
- * If a(the input param) is null then a StringBuilder will be created
- * and the output can be attained by invoking the out() method. But RI
- * raises an error of FormatterClosedException when invoking out() or
- * toString().
- */
- Appendable sb = f2.out();
- assertTrue(sb instanceof StringBuilder);
- assertNotNull(f2.toString());
- }
-
- /**
- * @tests java.util.Formatter#Formatter(Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Formatter",
- args = {java.util.Locale.class}
- )
- public void test_ConstructorLjava_util_Locale() {
- Formatter f1 = new Formatter(Locale.FRANCE);
- assertTrue(f1.out() instanceof StringBuilder);
- assertEquals(f1.locale(), Locale.FRANCE);
- assertNotNull(f1.toString());
-
- Formatter f2 = new Formatter((Locale) null);
- assertNull(f2.locale());
- assertTrue(f2.out() instanceof StringBuilder);
- assertNotNull(f2.toString());
- }
-
- /**
- * @tests java.util.Formatter#Formatter(Appendable, Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Formatter",
- args = {java.lang.Appendable.class, java.util.Locale.class}
- )
- public void test_ConstructorLjava_lang_AppendableLjava_util_Locale() {
- MockAppendable ma = new MockAppendable();
- Formatter f1 = new Formatter(ma, Locale.CANADA);
- assertEquals(ma, f1.out());
- assertEquals(f1.locale(), Locale.CANADA);
-
- Formatter f2 = new Formatter(ma, null);
- assertNull(f2.locale());
- assertEquals(ma, f1.out());
-
- Formatter f3 = new Formatter(null, Locale.GERMAN);
- assertEquals(f3.locale(), Locale.GERMAN);
- assertTrue(f3.out() instanceof StringBuilder);
- }
-
- /**
- * @tests java.util.Formatter#Formatter(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Formatter",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() throws IOException {
- Formatter f = null;
- try {
- f = new Formatter((String) null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e1) {
- // expected
- }
-
- f = new Formatter(notExist.getPath());
- assertEquals(f.locale(), Locale.getDefault());
- f.close();
-
- f = new Formatter(fileWithContent.getPath());
- assertEquals(0, fileWithContent.length());
- f.close();
-
- // FIXME This exception will not be thrown out on linux.
- try {
- f = new Formatter(readOnly.getPath());
- fail("should throw FileNotFoundException");
- } catch (FileNotFoundException e) {
- // expected
- }
-
- SecurityManager oldsm = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
- try {
- f = new Formatter(secret.getPath());
- fail("should throw SecurityException");
- } catch (SecurityException se) {
- // expected
- } finally {
- System.setSecurityManager(oldsm);
- }
- }
-
- /**
- * @tests java.util.Formatter#Formatter(String, String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Formatter",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_String()
- throws IOException {
- Formatter f = null;
- try {
- f = new Formatter((String) null, Charset.defaultCharset().name());
- fail("should throw NullPointerException");
- } catch (NullPointerException e1) {
- // expected
- }
-
- try {
- f = new Formatter(notExist.getPath(), null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e2) {
- // expected
- }
-
- f = new Formatter(notExist.getPath(), Charset.defaultCharset().name());
- assertEquals(f.locale(), Locale.getDefault());
- f.close();
-
- try {
- f = new Formatter(notExist.getPath(), "ISO 1111-1");
- fail("should throw UnsupportedEncodingException");
- } catch (UnsupportedEncodingException e1) {
- // expected
- }
-
- f = new Formatter(fileWithContent.getPath(), "UTF-16BE");
- assertEquals(0, fileWithContent.length());
- f.close();
-
- // FIXME This exception will not be thrown out on linux.
- try {
- f = new Formatter(readOnly.getPath(), "UTF-16BE");
- fail("should throw FileNotFoundException");
- } catch (FileNotFoundException e) {
- // expected
- }
-
- SecurityManager oldsm = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
- try {
- f = new Formatter(secret.getPath(), "UTF-16BE");
- fail("should throw SecurityException");
- } catch (SecurityException se) {
- // expected
- } finally {
- System.setSecurityManager(oldsm);
- }
- }
-
- /**
- * @tests java.util.Formatter#Formatter(String, String, Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Formatter",
- args = {java.lang.String.class, java.lang.String.class, java.util.Locale.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_util_Locale()
- throws IOException {
- Formatter f = null;
- try {
- f = new Formatter((String) null, Charset.defaultCharset().name(),
- Locale.KOREA);
- fail("should throw NullPointerException");
- } catch (NullPointerException e1) {
- // expected
- }
-
- try {
- f = new Formatter(notExist.getPath(), null, Locale.KOREA);
- fail("should throw NullPointerException");
- } catch (NullPointerException e2) {
- // expected
- }
-
- f = new Formatter(notExist.getPath(), Charset.defaultCharset().name(),
- null);
- assertNotNull(f);
- f.close();
-
- f = new Formatter(notExist.getPath(), Charset.defaultCharset().name(),
- Locale.KOREA);
- assertEquals(f.locale(), Locale.KOREA);
- f.close();
-
- try {
- f = new Formatter(notExist.getPath(), "ISO 1111-1", Locale.CHINA);
- fail("should throw UnsupportedEncodingException");
- } catch (UnsupportedEncodingException e1) {
- // expected
- }
-
- f = new Formatter(fileWithContent.getPath(), "UTF-16BE",
- Locale.CANADA_FRENCH);
- assertEquals(0, fileWithContent.length());
- f.close();
-
- try {
- f = new Formatter(readOnly.getPath(), Charset.defaultCharset()
- .name(), Locale.ITALY);
- fail("should throw FileNotFoundException");
- } catch (FileNotFoundException e) {
- // expected
- }
-
- SecurityManager oldsm = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
- try {
- f = new Formatter(secret.getPath(),
- Charset.defaultCharset().name(), Locale.SIMPLIFIED_CHINESE);
- fail("should throw SecurityException");
- } catch (SecurityException se) {
- // expected
- } finally {
- System.setSecurityManager(oldsm);
- }
- }
-
- /**
- * @tests java.util.Formatter#Formatter(File)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Formatter",
- args = {java.io.File.class}
- )
- public void test_ConstructorLjava_io_File() throws IOException {
- Formatter f = null;
- try {
- f = new Formatter((File) null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e1) {
- // expected
- }
-
- f = new Formatter(notExist);
- assertEquals(f.locale(), Locale.getDefault());
- f.close();
-
- f = new Formatter(fileWithContent);
- assertEquals(0, fileWithContent.length());
- f.close();
-
- // FIXME This exception will not be thrown out on linux.
- try {
- f = new Formatter(readOnly);
- fail("should throw FileNotFoundException");
- } catch (FileNotFoundException e) {
- // expected
- }
-
- SecurityManager oldsm = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
- try {
- f = new Formatter(secret);
- fail("should throw SecurityException");
- } catch (SecurityException se) {
- // expected
- } finally {
- System.setSecurityManager(oldsm);
- }
- }
-
- /**
- * @tests java.util.Formatter#Formatter(File, String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Formatter",
- args = {java.io.File.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_io_FileLjava_lang_String()
- throws IOException {
- Formatter f = null;
- try {
- f = new Formatter((File) null, Charset.defaultCharset().name());
- fail("should throw NullPointerException");
- } catch (NullPointerException e1) {
- // expected
- }
-
- f = new Formatter(notExist, Charset.defaultCharset().name());
- assertEquals(f.locale(), Locale.getDefault());
- f.close();
-
- f = new Formatter(fileWithContent, "UTF-16BE");
- assertEquals(0, fileWithContent.length());
- f.close();
-
- // FIXME This exception will not be thrown out on linux.
- try {
- f = new Formatter(readOnly, Charset.defaultCharset().name());
- fail("should throw FileNotFoundException");
- } catch (FileNotFoundException e) {
- // expected
- }
-
- SecurityManager oldsm = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
- try {
- f = new Formatter(secret, Charset.defaultCharset().name());
- fail("should throw SecurityException");
- } catch (SecurityException se) {
- // expected
- } finally {
- System.setSecurityManager(oldsm);
- }
-
- try {
- f = new Formatter(notExist, null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e2) {
- // expected
- } finally {
- if (notExist.exists()) {
- // Fail on RI on Windows, because output stream is created and
- // not closed when exception thrown
- assertTrue(notExist.delete());
- }
- }
-
- try {
- f = new Formatter(notExist, "ISO 1111-1");
- fail("should throw UnsupportedEncodingException");
- } catch (UnsupportedEncodingException e1) {
- // expected
- } finally {
- if (notExist.exists()) {
- // Fail on RI on Windows, because output stream is created and
- // not closed when exception thrown
- assertTrue(notExist.delete());
- }
- }
- }
-
- /**
- * @tests java.util.Formatter#Formatter(File, String, Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Formatter",
- args = {java.io.File.class, java.lang.String.class, java.util.Locale.class}
- )
- public void test_ConstructorLjava_io_FileLjava_lang_StringLjava_util_Locale()
- throws IOException {
- Formatter f = null;
- try {
- f = new Formatter((File) null, Charset.defaultCharset().name(),
- Locale.KOREA);
- fail("should throw NullPointerException");
- } catch (NullPointerException e1) {
- // expected
- }
-
- try {
- f = new Formatter(notExist, null, Locale.KOREA);
- fail("should throw NullPointerException");
- } catch (NullPointerException e2) {
- // expected
- }
-
- f = new Formatter(notExist, Charset.defaultCharset().name(), null);
- assertNotNull(f);
- f.close();
-
- f = new Formatter(notExist, Charset.defaultCharset().name(),
- Locale.KOREA);
- assertEquals(f.locale(), Locale.KOREA);
- f.close();
-
- try {
- f = new Formatter(notExist, "ISO 1111-1", Locale.CHINA);
- fail("should throw UnsupportedEncodingException");
- } catch (UnsupportedEncodingException e1) {
- // expected
- }
- f = new Formatter(fileWithContent.getPath(), "UTF-16BE",
- Locale.CANADA_FRENCH);
- assertEquals(0, fileWithContent.length());
- f.close();
-
- // FIXME This exception will not be thrown out on linux.
- try {
- f = new Formatter(readOnly.getPath(), Charset.defaultCharset()
- .name(), Locale.ITALY);
- fail("should throw FileNotFoundException");
- } catch (FileNotFoundException e) {
- // expected
- }
-
- SecurityManager oldsm = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
- try {
- f = new Formatter(secret.getPath(),
- Charset.defaultCharset().name(), Locale.SIMPLIFIED_CHINESE);
- fail("should throw SecurityException");
- } catch (SecurityException se) {
- // expected
- } finally {
- System.setSecurityManager(oldsm);
- }
- }
-
- /**
- * @tests java.util.Formatter#Formatter(PrintStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Formatter",
- args = {java.io.PrintStream.class}
- )
- public void test_ConstructorLjava_io_PrintStream() throws IOException {
- Formatter f = null;
- try {
- f = new Formatter((PrintStream) null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e1) {
- // expected
- }
-
- PrintStream ps = new PrintStream(notExist, "UTF-16BE");
- f = new Formatter(ps);
- assertEquals(Locale.getDefault(), f.locale());
- f.close();
- }
-
- /**
- * @tests java.util.Formatter#Formatter(OutputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Formatter",
- args = {java.io.OutputStream.class}
- )
- public void test_ConstructorLjava_io_OutputStream() throws IOException {
- Formatter f = null;
- try {
- f = new Formatter((OutputStream) null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e1) {
- // expected
- }
-
- OutputStream os = new FileOutputStream(notExist);
- f = new Formatter(os);
- assertEquals(Locale.getDefault(), f.locale());
- f.close();
- }
-
- /**
- * @tests java.util.Formatter#Formatter(OutputStream, String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Formatter",
- args = {java.io.OutputStream.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_io_OutputStreamLjava_lang_String()
- throws IOException {
- Formatter f = null;
- try {
- f = new Formatter((OutputStream) null, Charset.defaultCharset()
- .name());
- fail("should throw NullPointerException");
- } catch (NullPointerException e1) {
- // expected
- }
-
- OutputStream os = null;
- try {
- os = new FileOutputStream(notExist);
- f = new Formatter(os, null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e2) {
- // expected
- } finally {
- os.close();
- }
-
- try {
- os = new PipedOutputStream();
- f = new Formatter(os, "TMP-1111");
- fail("should throw UnsupportedEncodingException");
- } catch (UnsupportedEncodingException e1) {
- // expected
- } finally {
- os.close();
- }
-
- os = new FileOutputStream(fileWithContent);
- f = new Formatter(os, "UTF-16BE");
- assertEquals(Locale.getDefault(), f.locale());
- f.close();
- }
-
- /**
- * Test method for 'java.util.Formatter.Formatter(OutputStream, String,
- * Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Formatter",
- args = {java.io.OutputStream.class, java.lang.String.class, java.util.Locale.class}
- )
- public void test_ConstructorLjava_io_OutputStreamLjava_lang_StringLjava_util_Locale()
- throws IOException {
- Formatter f = null;
- try {
- f = new Formatter((OutputStream) null, Charset.defaultCharset()
- .name(), Locale.getDefault());
- fail("should throw NullPointerException");
- } catch (NullPointerException e1) {
- // expected
- }
-
- OutputStream os = null;
- try {
- os = new FileOutputStream(notExist);
- f = new Formatter(os, null, Locale.getDefault());
- fail("should throw NullPointerException");
- } catch (NullPointerException e2) {
- // expected
- } finally {
- os.close();
- }
-
- os = new FileOutputStream(notExist);
- f = new Formatter(os, Charset.defaultCharset().name(), null);
- f.close();
-
- try {
- os = new PipedOutputStream();
- f = new Formatter(os, "TMP-1111", Locale.getDefault());
- fail("should throw UnsupportedEncodingException");
- } catch (UnsupportedEncodingException e1) {
- // expected
- }
-
- os = new FileOutputStream(fileWithContent);
- f = new Formatter(os, "UTF-16BE", Locale.ENGLISH);
- assertEquals(Locale.ENGLISH, f.locale());
- f.close();
- }
-
- /**
- * @tests java.util.Formatter#locale()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "locale",
- args = {}
- )
- public void test_locale() {
- Formatter f = null;
- f = new Formatter((Locale) null);
- assertNull(f.locale());
- f = new Formatter(Locale.FRANCE);
- assertEquals(f.locale(), Locale.FRANCE);
-
- f.close();
- try {
- f.locale();
- fail("should throw FormatterClosedException");
- } catch (FormatterClosedException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Formatter#out()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "out",
- args = {}
- )
- public void test_out() {
- Formatter f = null;
- f = new Formatter();
- assertNotNull(f.out());
- assertTrue(f.out() instanceof StringBuilder);
- f.close();
- try {
- f.out();
- fail("should throw FormatterClosedException");
- } catch (FormatterClosedException e) {
- // expected
- }
-
- }
-
- /**
- * @tests java.util.Formatter#flush()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "flush",
- args = {}
- )
- public void test_flush() throws IOException {
- Formatter f = null;
- f = new Formatter(notExist);
- assertTrue(f instanceof Flushable);
- f.close();
- try {
- f.flush();
- fail("should throw FormatterClosedException");
- } catch (FormatterClosedException e) {
- // expected
- }
-
- f = new Formatter();
- // For destination that does not implement Flushable
- // No exception should be thrown
- f.flush();
- }
-
- /**
- * @tests java.util.Formatter#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "close",
- args = {}
- )
- public void test_close() throws IOException {
- Formatter f = new Formatter(notExist);
- assertTrue(f instanceof Closeable);
- f.close();
- // close next time will not throw exception
- f.close();
- assertNull(f.ioException());
- }
-
- /**
- * @tests java.util.Formatter#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- Formatter f = new Formatter();
- assertNotNull(f.toString());
- assertEquals(f.out().toString(), f.toString());
- f.close();
- try {
- f.toString();
- fail("should throw FormatterClosedException");
- } catch (FormatterClosedException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Formatter#ioException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ioException",
- args = {}
- )
- public void test_ioException() throws IOException {
- Formatter f = null;
- f = new Formatter(new MockDestination());
- assertNull(f.ioException());
- f.flush();
- assertNotNull(f.ioException());
- f.close();
-
- MockDestination md = new MockDestination();
- f = new Formatter(md);
- f.format("%s%s", "1", "2");
- // format stop working after IOException
- assertNotNull(f.ioException());
- assertEquals("", f.toString());
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for null parameter
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies null as a parameter.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_null() {
- Formatter f = new Formatter();
- try {
- f.format((String) null, "parameter");
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- f = new Formatter();
- f.format("hello", (Object[]) null);
- assertEquals("hello", f.toString());
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for argument index
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify IllegalFormatException, FormatterClosedException.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_ArgIndex() {
- Formatter formatter = new Formatter(Locale.US);
- formatter.format("%1$s%2$s%3$s%4$s%5$s%6$s%7$s%8$s%9$s%11$s%10$s", "1",
- "2", "3", "4", "5", "6", "7", "8", "9", "10", "11");
- assertEquals("1234567891110", formatter.toString());
-
- formatter = new Formatter(Locale.JAPAN);
- formatter.format("%0$s", "hello");
- assertEquals("hello", formatter.toString());
-
- try {
- formatter = new Formatter(Locale.US);
- formatter.format("%-1$s", "1", "2");
- fail("should throw UnknownFormatConversionException");
- } catch (UnknownFormatConversionException e) {
- // expected
- }
-
- try {
- formatter = new Formatter(Locale.US);
- formatter.format("%$s", "hello", "2");
- fail("should throw UnknownFormatConversionException");
- } catch (UnknownFormatConversionException e) {
- // expected
- }
-
- try {
- Formatter f = new Formatter(Locale.US);
- f.format("%", "string");
- fail("should throw UnknownFormatConversionException");
- } catch (UnknownFormatConversionException e) {
- // expected
- }
-
- formatter = new Formatter(Locale.FRANCE);
- formatter.format("%1$s%2$s%3$s%4$s%5$s%6$s%7$s%8$s%<s%s%s%<s", "1",
- "2", "3", "4", "5", "6", "7", "8", "9", "10", "11");
- assertEquals("123456788122", formatter.toString());
-
- formatter = new Formatter(Locale.FRANCE);
- formatter.format(
- "xx%1$s22%2$s%s%<s%5$s%<s&%7$h%2$s%8$s%<s%s%s%<ssuffix", "1",
- "2", "3", "4", "5", "6", 7, "8", "9", "10", "11");
- assertEquals("xx12221155&7288233suffix", formatter.toString());
-
- try {
- formatter.format("%<s", "hello");
- fail("should throw MissingFormatArgumentException");
- } catch (MissingFormatArgumentException e) {
- // expected
- }
-
- formatter = new Formatter(Locale.US);
- try {
- formatter.format("%123$s", "hello");
- fail("should throw MissingFormatArgumentException");
- } catch (MissingFormatArgumentException e) {
- // expected
- }
-
- formatter = new Formatter(Locale.US);
- try {
- // 2147483648 is the value of Integer.MAX_VALUE + 1
- formatter.format("%2147483648$s", "hello");
- fail("should throw MissingFormatArgumentException");
- } catch (MissingFormatArgumentException e) {
- // expected
- }
-
- try {
- // 2147483647 is the value of Integer.MAX_VALUE
- formatter.format("%2147483647$s", "hello");
- fail("should throw MissingFormatArgumentException");
- } catch (MissingFormatArgumentException e) {
- // expected
- }
-
- formatter = new Formatter(Locale.US);
- try {
- formatter.format("%s%s", "hello");
- fail("should throw MissingFormatArgumentException");
- } catch (MissingFormatArgumentException e) {
- // expected
- }
-
- formatter = new Formatter(Locale.US);
- formatter.format("$100", 100);
- assertEquals("$100", formatter.toString());
-
- formatter = new Formatter(Locale.UK);
- formatter.format("%01$s", "string");
- assertEquals("string", formatter.toString());
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for width
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_Width() {
- Formatter f = new Formatter(Locale.US);
- f.format("%1$8s", "1");
- assertEquals(" 1", f.toString());
-
- f = new Formatter(Locale.US);
- f.format("%1$-1%", "string");
- assertEquals("%", f.toString());
-
- f = new Formatter(Locale.ITALY);
- // 2147483648 is the value of Integer.MAX_VALUE + 1
- f.format("%2147483648s", "string");
- assertEquals("string", f.toString());
-
- // the value of Integer.MAX_VALUE will allocate about 4G bytes of
- // memory.
- // It may cause OutOfMemoryError, so this value is not tested
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for precision
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_Precision() {
- Formatter f = new Formatter(Locale.US);
- f.format("%.5s", "123456");
- assertEquals("12345", f.toString());
-
- f = new Formatter(Locale.US);
- // 2147483648 is the value of Integer.MAX_VALUE + 1
- f.format("%.2147483648s", "...");
- assertEquals("...", f.toString());
-
- // the value of Integer.MAX_VALUE will allocate about 4G bytes of
- // memory.
- // It may cause OutOfMemoryError, so this value is not tested
-
- f = new Formatter(Locale.US);
- f.format("%10.0b", Boolean.TRUE);
- assertEquals(" ", f.toString());
-
- f = new Formatter(Locale.US);
- f.format("%10.01s", "hello");
- assertEquals(" h", f.toString());
-
- try {
- f = new Formatter(Locale.US);
- f.format("%.s", "hello", "2");
- fail("should throw UnknownFormatConversionException");
- } catch (UnknownFormatConversionException e) {
- // expected
- }
-
- try {
- f = new Formatter(Locale.US);
- f.format("%.-5s", "123456");
- fail("should throw UnknownFormatConversionException");
- } catch (UnknownFormatConversionException e) {
- // expected
- }
-
- try {
- f = new Formatter(Locale.US);
- f.format("%1.s", "hello", "2");
- fail("should throw UnknownFormatConversionException");
- } catch (UnknownFormatConversionException e) {
- // expected
- }
-
- f = new Formatter(Locale.US);
- f.format("%5.1s", "hello");
- assertEquals(" h", f.toString());
-
- f = new Formatter(Locale.FRANCE);
- f.format("%.0s", "hello", "2");
- assertEquals("", f.toString());
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for line sperator
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalFormatFlagsException.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_LineSeparator() {
- Formatter f = null;
-
- String oldSeparator = System.getProperty("line.separator");
- System.setProperty("line.separator", "!\n");
-
- f = new Formatter(Locale.US);
- f.format("%1$n", 1);
- assertEquals("!\n", f.toString());
-
- f = new Formatter(Locale.KOREAN);
- f.format("head%1$n%2$n", 1, new Date());
- assertEquals("head!\n!\n", f.toString());
-
- f = new Formatter(Locale.US);
- f.format("%n%s", "hello");
- assertEquals("!\nhello", f.toString());
-
- System.setProperty("line.separator", oldSeparator);
-
- f = new Formatter(Locale.US);
- try {
- f.format("%-n");
- fail("should throw IllegalFormatFlagsException: %-n");
- } catch (IllegalFormatFlagsException e) {
- // expected
- }
- try {
- f.format("%+n");
- fail("should throw IllegalFormatFlagsException: %+n");
- } catch (IllegalFormatFlagsException e) {
- // expected
- }
- try {
- f.format("%#n");
- fail("should throw IllegalFormatFlagsException: %#n");
- } catch (IllegalFormatFlagsException e) {
- // expected
- }
- try {
- f.format("% n");
- fail("should throw IllegalFormatFlagsException: % n");
- } catch (IllegalFormatFlagsException e) {
- // expected
- }
- try {
- f.format("%0n");
- fail("should throw IllegalFormatFlagsException: %0n");
- } catch (IllegalFormatFlagsException e) {
- // expected
- }
- try {
- f.format("%,n");
- fail("should throw IllegalFormatFlagsException: %,n");
- } catch (IllegalFormatFlagsException e) {
- // expected
- }
- try {
- f.format("%(n");
- fail("should throw IllegalFormatFlagsException: %(n");
- } catch (IllegalFormatFlagsException e) {
- // expected
- }
-
- f = new Formatter(Locale.US);
- try {
- f.format("%4n");
- fail("should throw IllegalFormatWidthException");
- } catch (IllegalFormatWidthException e) {
- // expected
- }
-
- f = new Formatter(Locale.US);
- try {
- f.format("%-4n");
- fail("should throw IllegalFormatWidthException");
- } catch (IllegalFormatWidthException e) {
- // expected
- }
-
- f = new Formatter(Locale.US);
- try {
- f.format("%.9n");
- fail("should throw IllegalFormatPrecisionException");
- } catch (IllegalFormatPrecisionException e) {
- // expected
- }
-
- f = new Formatter(Locale.US);
- try {
- f.format("%5.9n");
- fail("should throw IllegalFormatPrecisionException");
- } catch (IllegalFormatPrecisionException e) {
- // expected
- }
-
- System.setProperty("line.separator", oldSeparator);
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for percent
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalFormatPrecisionException.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- @AndroidOnly("fails on RI. See comment below")
- public void test_formatLjava_lang_String$Ljava_lang_Object_Percent() {
- Formatter f = null;
-
- f = new Formatter(Locale.ENGLISH);
- f.format("%1$%", 100);
- assertEquals("%", f.toString());
-
- f = new Formatter(Locale.CHINA);
- f.format("%1$%%%", "hello", new Object());
- assertEquals("%%", f.toString());
-
- f = new Formatter(Locale.CHINA);
- f.format("%%%s", "hello");
- assertEquals("%hello", f.toString());
-
- f = new Formatter(Locale.US);
- try {
- f.format("%.9%");
- fail("should throw IllegalFormatPrecisionException");
- } catch (IllegalFormatPrecisionException e) {
- // expected
- }
-
- f = new Formatter(Locale.US);
- try {
- f.format("%5.9%");
- fail("should throw IllegalFormatPrecisionException");
- } catch (IllegalFormatPrecisionException e) {
- // expected
- }
-
- f = new Formatter(Locale.US);
- /*
- * fail on RI. The only flag supported for '%' is '-'. If any other flags are
- * provide, FormatFlagsConversionMismatchException shall be thrown
- */
- assertFormatFlagsConversionMismatchException(f, "%+%");
- assertFormatFlagsConversionMismatchException(f, "%#%");
- assertFormatFlagsConversionMismatchException(f, "% %");
- assertFormatFlagsConversionMismatchException(f, "%0%");
- assertFormatFlagsConversionMismatchException(f, "%,%");
- assertFormatFlagsConversionMismatchException(f, "%(%");
-
-
- f = new Formatter(Locale.KOREAN);
- f.format("%4%", 1);
-
- /* fail on RI the output string should be right justified by appending
- * spaces till the whole string is 4 chars width.
- */
- assertEquals(" %", f.toString());
-
- f = new Formatter(Locale.US);
- f.format("%-4%", 100);
- /*
- * fail on RI, throw UnknownFormatConversionException the output string
- * should be left justified by appending spaces till the whole string is
- * 4 chars width.
- */
- assertEquals("% ", f.toString());
- }
-
- private void assertFormatFlagsConversionMismatchException(Formatter f, String str) {
- try {
- f.format(str);
- fail("should throw FormatFlagsConversionMismatchException: "
- + str);
- /*
- * error on RI, throw IllegalFormatFlagsException specification
- * says FormatFlagsConversionMismatchException should be thrown
- */
- } catch (FormatFlagsConversionMismatchException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for flag
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies UnknownFormatConversionException, DuplicateFormatFlagsException.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_Flag() {
- Formatter f = new Formatter(Locale.US);
- try {
- f.format("%1$-#-8s", "something");
- fail("should throw DuplicateFormatFlagsException");
- } catch (DuplicateFormatFlagsException e) {
- // expected
- }
-
- final char[] chars = { '-', '#', '+', ' ', '0', ',', '(', '%', '<' };
- Arrays.sort(chars);
- f = new Formatter(Locale.US);
- for (char i = 0; i <= 256; i++) {
- // test 8 bit character
- if (Arrays.binarySearch(chars, i) >= 0 || Character.isDigit(i)
- || Character.isLetter(i)) {
- // Do not test 0-9, a-z, A-Z and characters in the chars array.
- // They are characters used as flags, width or conversions
- continue;
- }
- try {
- f.format("%" + i + "s", 1);
- fail("should throw UnknownFormatConversionException");
- } catch (UnknownFormatConversionException e) {
- // expected
- }
- }
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for general
- * conversion b/B
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify IllegalFormatException, FormatterClosedException.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_format_LString$LObject_GeneralConversionB() {
- final Object[][] triple = {
- { Boolean.FALSE, "%3.2b", " fa", },
- { Boolean.FALSE, "%-4.6b", "false", },
- { Boolean.FALSE, "%.2b", "fa", },
- { Boolean.TRUE, "%3.2b", " tr", },
- { Boolean.TRUE, "%-4.6b", "true", },
- { Boolean.TRUE, "%.2b", "tr", },
- { new Character('c'), "%3.2b", " tr", },
- { new Character('c'), "%-4.6b", "true", },
- { new Character('c'), "%.2b", "tr", },
- { new Byte((byte) 0x01), "%3.2b", " tr", },
- { new Byte((byte) 0x01), "%-4.6b", "true", },
- { new Byte((byte) 0x01), "%.2b", "tr", },
- { new Short((short) 0x0001), "%3.2b", " tr", },
- { new Short((short) 0x0001), "%-4.6b", "true", },
- { new Short((short) 0x0001), "%.2b", "tr", },
- { new Integer(1), "%3.2b", " tr", },
- { new Integer(1), "%-4.6b", "true", },
- { new Integer(1), "%.2b", "tr", },
- { new Float(1.1f), "%3.2b", " tr", },
- { new Float(1.1f), "%-4.6b", "true", },
- { new Float(1.1f), "%.2b", "tr", },
- { new Double(1.1d), "%3.2b", " tr", },
- { new Double(1.1d), "%-4.6b", "true", },
- { new Double(1.1d), "%.2b", "tr", },
- { "", "%3.2b", " tr", },
- { "", "%-4.6b", "true", },
- { "", "%.2b", "tr", },
- { "string content", "%3.2b", " tr", },
- { "string content", "%-4.6b", "true", },
- { "string content", "%.2b", "tr", },
- { new MockFormattable(), "%3.2b", " tr", },
- { new MockFormattable(), "%-4.6b", "true", },
- { new MockFormattable(), "%.2b", "tr", },
- { (Object) null, "%3.2b", " fa", },
- { (Object) null, "%-4.6b", "false", },
- { (Object) null, "%.2b", "fa", },
- };
-
-
- final int input = 0;
- final int pattern = 1;
- final int output = 2;
- Formatter f = null;
- for (int i = 0; i < triple.length; i++) {
- f = new Formatter(Locale.FRANCE);
- f.format((String)triple[i][pattern], triple[i][input]);
- assertEquals("triple[" + i + "]:" + triple[i][input]
- + ",pattern[" + i + "]:" + triple[i][pattern], triple[i][output], f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format(((String)triple[i][pattern]).toUpperCase(Locale.US), triple[i][input]);
- assertEquals("triple[" + i + "]:" + triple[i][input]
- + ",pattern[" + i + "]:" + triple[i][pattern], ((String)triple[i][output])
- .toUpperCase(Locale.US), f.toString());
- }
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for general
- * conversion type 's' and 'S'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify IllegalFormatException, FormatterClosedException.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_format_LString$LObject_GeneralConversionS() {
-
- final Object[][] triple = {
- { Boolean.FALSE, "%2.3s", "fal", },
- { Boolean.FALSE, "%-6.4s", "fals ", },
- { Boolean.FALSE, "%.5s", "false", },
- { Boolean.TRUE, "%2.3s", "tru", },
- { Boolean.TRUE, "%-6.4s", "true ", },
- { Boolean.TRUE, "%.5s", "true", },
- { new Character('c'), "%2.3s", " c", },
- { new Character('c'), "%-6.4s", "c ", },
- { new Character('c'), "%.5s", "c", },
- { new Byte((byte) 0x01), "%2.3s", " 1", },
- { new Byte((byte) 0x01), "%-6.4s", "1 ", },
- { new Byte((byte) 0x01), "%.5s", "1", },
- { new Short((short) 0x0001), "%2.3s", " 1", },
- { new Short((short) 0x0001), "%-6.4s", "1 ", },
- { new Short((short) 0x0001), "%.5s", "1", },
- { new Integer(1), "%2.3s", " 1", },
- { new Integer(1), "%-6.4s", "1 ", },
- { new Integer(1), "%.5s", "1", },
- { new Float(1.1f), "%2.3s", "1.1", },
- { new Float(1.1f), "%-6.4s", "1.1 ", },
- { new Float(1.1f), "%.5s", "1.1", },
- { new Double(1.1d), "%2.3s", "1.1", },
- { new Double(1.1d), "%-6.4s", "1.1 ", },
- { new Double(1.1d), "%.5s", "1.1", },
- { "", "%2.3s", " ", },
- { "", "%-6.4s", " ", },
- { "", "%.5s", "", },
- { "string content", "%2.3s", "str", },
- { "string content", "%-6.4s", "stri ", },
- { "string content", "%.5s", "strin", },
- { new MockFormattable(), "%2.3s", "customized format function width: 2 precision: 3", },
- { new MockFormattable(), "%-6.4s", "customized format function width: 6 precision: 4", },
- { new MockFormattable(), "%.5s", "customized format function width: -1 precision: 5", },
- { (Object) null, "%2.3s", "nul", },
- { (Object) null, "%-6.4s", "null ", },
- { (Object) null, "%.5s", "null", },
- };
-
-
- final int input = 0;
- final int pattern = 1;
- final int output = 2;
- Formatter f = null;
- for (int i = 0; i < triple.length; i++) {
- f = new Formatter(Locale.FRANCE);
- f.format((String)triple[i][pattern], triple[i][input]);
- assertEquals("triple[" + i + "]:" + triple[i][input]
- + ",pattern[" + i + "]:" + triple[i][pattern], triple[i][output], f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format(((String)triple[i][pattern]).toUpperCase(Locale.US), triple[i][input]);
- assertEquals("triple[" + i + "]:" + triple[i][input]
- + ",pattern[" + i + "]:" + triple[i][pattern], ((String)triple[i][output])
- .toUpperCase(Locale.US), f.toString());
- }
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for general
- * conversion type 'h' and 'H'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify IllegalFormatException, FormatterClosedException.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_format_LString$LObject_GeneralConversionH() {
-
- final Object[] input = {
- Boolean.FALSE,
- Boolean.TRUE,
- new Character('c'),
- new Byte((byte) 0x01),
- new Short((short) 0x0001),
- new Integer(1),
- new Float(1.1f),
- new Double(1.1d),
- "",
- "string content",
- new MockFormattable(),
- (Object) null,
- };
-
- Formatter f = null;
- for (int i = 0; i < input.length - 1; i++) {
- f = new Formatter(Locale.FRANCE);
- f.format("%h", input[i]);
- assertEquals("triple[" + i + "]:" + input[i],
- Integer.toHexString(input[i].hashCode()), f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format("%H", input[i]);
- assertEquals("triple[" + i + "]:" + input[i],
- Integer.toHexString(input[i].hashCode()).toUpperCase(Locale.US), f.toString());
- }
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for general
- * conversion other cases
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies FormatFlagsConversionMismatchException.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- @AndroidOnly("fails on RI. See comments below")
- public void test_formatLjava_lang_String$Ljava_lang_Object_GeneralConversionOther() {
- /*
- * In Turkish locale, the upper case of '\u0069' is '\u0130'. The
- * following test indicate that '\u0069' is coverted to upper case
- * without using the turkish locale.
- */
- Formatter f = new Formatter(new Locale("tr"));
- f.format("%S", "\u0069");
- assertEquals("\u0049", f.toString());
-
- final Object[] input = {
- Boolean.FALSE,
- Boolean.TRUE,
- new Character('c'),
- new Byte((byte) 0x01),
- new Short((short) 0x0001),
- new Integer(1),
- new Float(1.1f),
- new Double(1.1d),
- "",
- "string content",
- new MockFormattable(),
- (Object) null,
- };
- f = new Formatter(Locale.GERMAN);
- for (int i = 0; i < input.length; i++) {
- if (!(input[i] instanceof Formattable)) {
- try {
- f.format("%#s", input[i]);
- /*
- * fail on RI, spec says if the '#' flag is present and the
- * argument is not a Formattable , then a
- * FormatFlagsConversionMismatchException will be thrown.
- */
- fail("should throw FormatFlagsConversionMismatchException");
- } catch (FormatFlagsConversionMismatchException e) {
- // expected
- }
- } else {
- f.format("%#s%<-#8s", input[i]);
- assertEquals(
- "customized format function width: -1 precision: -1customized format function width: 8 precision: -1",
- f.toString());
- }
- }
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for general
- * conversion exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies exceptions.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_GeneralConversionException() {
- final String[] flagMismatch = { "%#b", "%+b", "% b", "%0b", "%,b",
- "%(b", "%#B", "%+B", "% B", "%0B", "%,B", "%(B", "%#h", "%+h",
- "% h", "%0h", "%,h", "%(h", "%#H", "%+H", "% H", "%0H", "%,H",
- "%(H", "%+s", "% s", "%0s", "%,s", "%(s", "%+S", "% S", "%0S",
- "%,S", "%(S" };
-
- Formatter f = new Formatter(Locale.US);
-
- for (int i = 0; i < flagMismatch.length; i++) {
- try {
- f.format(flagMismatch[i], "something");
- fail("should throw FormatFlagsConversionMismatchException");
- } catch (FormatFlagsConversionMismatchException e) {
- // expected
- }
- }
-
- final String[] missingWidth = { "%-b", "%-B", "%-h", "%-H", "%-s",
- "%-S", };
- for (int i = 0; i < missingWidth.length; i++) {
- try {
- f.format(missingWidth[i], "something");
- fail("should throw MissingFormatWidthException");
- } catch (MissingFormatWidthException e) {
- // expected
- }
- }
-
- // Regression test
- f = new Formatter();
- try {
- f.format("%c", (byte)-0x0001);
- fail("Should throw IllegalFormatCodePointException");
- } catch (IllegalFormatCodePointException e) {
- // expected
- }
-
- f = new Formatter();
- try {
- f.format("%c", (short)-0x0001);
- fail("Should throw IllegalFormatCodePointException");
- } catch (IllegalFormatCodePointException e) {
- // expected
- }
-
- f = new Formatter();
- try {
- f.format("%c", -0x0001);
- fail("Should throw IllegalFormatCodePointException");
- } catch (IllegalFormatCodePointException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for Character
- * conversion
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalFormatConversionException, FormatFlagsConversionMismatchException, functionality.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- @AndroidOnly("RI doesn't support 'C' format")
- public void test_formatLjava_lang_String$Ljava_lang_Object_CharacterConversion() {
- Formatter f = new Formatter(Locale.US);
- final Object[] illArgs = { Boolean.TRUE, new Float(1.1f),
- new Double(1.1d), "string content", new Float(1.1f), new Date() };
- for (int i = 0; i < illArgs.length; i++) {
- try {
- f.format("%c", illArgs[i]);
- fail("should throw IllegalFormatConversionException");
- } catch (IllegalFormatConversionException e) {
- // expected
- }
- }
-
- try {
- f.format("%c", Integer.MAX_VALUE);
- fail("should throw IllegalFormatCodePointException");
- } catch (IllegalFormatCodePointException e) {
- // expected
- }
-
- try {
- f.format("%#c", 'c');
- fail("should throw FormatFlagsConversionMismatchException");
- } catch (FormatFlagsConversionMismatchException e) {
- // expected
- }
-
- final Object[][] triple = {
- {'c', "%c", "c"},
- {'c', "%-2c", "c "},
- {'\u0123', "%c", "\u0123"},
- {'\u0123', "%-2c", "\u0123 "},
- {(byte) 0x11, "%c", "\u0011"},
- {(byte) 0x11, "%-2c", "\u0011 "},
- {(short) 0x1111, "%c", "\u1111"},
- {(short) 0x1111, "%-2c", "\u1111 "},
- {0x11, "%c", "\u0011"},
- {0x11, "%-2c", "\u0011 "},
- };
-
- final int input = 0;
- final int pattern = 1;
- final int output = 2;
- for (int i = 0; i < triple.length; i++) {
- f = new Formatter(Locale.US);
- f.format((String)triple[i][pattern], triple[i][input]);
- assertEquals(triple[i][output], f.toString());
- }
-
- f = new Formatter(Locale.US);
- f.format("%c", 0x10000);
- assertEquals(0x10000, f.toString().codePointAt(0));
-
- try {
- f.format("%2.2c", 'c');
- fail("should throw IllegalFormatPrecisionException");
- } catch (IllegalFormatPrecisionException e) {
- // expected
- }
-
- f = new Formatter(Locale.US);
- f.format("%C", 'w');
- // error on RI, throw UnknownFormatConversionException
- // RI do not support converter 'C'
- assertEquals("W", f.toString());
-
- f = new Formatter(Locale.JAPAN);
- f.format("%Ced", 0x1111);
- // error on RI, throw UnknownFormatConversionException
- // RI do not support converter 'C'
- assertEquals("\u1111ed", f.toString());
- }
-
-
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for legal
- * Byte/Short/Integer/Long conversion type 'd'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify exceptions.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_ByteShortIntegerLongConversionD() {
- final Object[][] triple = {
- { 0, "%d", "0" },
- { 0, "%10d", " 0" },
- { 0, "%-1d", "0" },
- { 0, "%+d", "+0" },
- { 0, "% d", " 0" },
- { 0, "%,d", "0" },
- { 0, "%(d", "0" },
- { 0, "%08d", "00000000" },
- { 0, "%-+,(11d", "+0 " },
- { 0, "%0 ,(11d", " 0000000000" },
-
- { (byte) 0xff, "%d", "-1" },
- { (byte) 0xff, "%10d", " -1" },
- { (byte) 0xff, "%-1d", "-1" },
- { (byte) 0xff, "%+d", "-1" },
- { (byte) 0xff, "% d", "-1" },
- { (byte) 0xff, "%,d", "-1" },
- { (byte) 0xff, "%(d", "(1)" },
- { (byte) 0xff, "%08d", "-0000001" },
- { (byte) 0xff, "%-+,(11d", "(1) " },
- { (byte) 0xff, "%0 ,(11d", "(000000001)" },
-
- { (short) 0xf123, "%d", "-3805" },
- { (short) 0xf123, "%10d", " -3805" },
- { (short) 0xf123, "%-1d", "-3805" },
- { (short) 0xf123, "%+d", "-3805" },
- { (short) 0xf123, "% d", "-3805" },
- { (short) 0xf123, "%,d", "-3.805" },
- { (short) 0xf123, "%(d", "(3805)" },
- { (short) 0xf123, "%08d", "-0003805" },
- { (short) 0xf123, "%-+,(11d", "(3.805) " },
- { (short) 0xf123, "%0 ,(11d", "(00003.805)" },
-
- { 0x123456, "%d", "1193046" },
- { 0x123456, "%10d", " 1193046" },
- { 0x123456, "%-1d", "1193046" },
- { 0x123456, "%+d", "+1193046" },
- { 0x123456, "% d", " 1193046" },
- { 0x123456, "%,d", "1.193.046" },
- { 0x123456, "%(d", "1193046" },
- { 0x123456, "%08d", "01193046" },
- { 0x123456, "%-+,(11d", "+1.193.046 " },
- { 0x123456, "%0 ,(11d", " 01.193.046" },
-
- { -3, "%d", "-3" },
- { -3, "%10d", " -3" },
- { -3, "%-1d", "-3" },
- { -3, "%+d", "-3" },
- { -3, "% d", "-3" },
- { -3, "%,d", "-3" },
- { -3, "%(d", "(3)" },
- { -3, "%08d", "-0000003" },
- { -3, "%-+,(11d", "(3) " },
- { -3, "%0 ,(11d", "(000000003)" },
-
- { 0x7654321L, "%d", "124076833" },
- { 0x7654321L, "%10d", " 124076833" },
- { 0x7654321L, "%-1d", "124076833" },
- { 0x7654321L, "%+d", "+124076833" },
- { 0x7654321L, "% d", " 124076833" },
- { 0x7654321L, "%,d", "124.076.833" },
- { 0x7654321L, "%(d", "124076833" },
- { 0x7654321L, "%08d", "124076833" },
- { 0x7654321L, "%-+,(11d", "+124.076.833" },
- { 0x7654321L, "%0 ,(11d", " 124.076.833" },
-
- { -1L, "%d", "-1" },
- { -1L, "%10d", " -1" },
- { -1L, "%-1d", "-1" },
- { -1L, "%+d", "-1" },
- { -1L, "% d", "-1" },
- { -1L, "%,d", "-1" },
- { -1L, "%(d", "(1)" },
- { -1L, "%08d", "-0000001" },
- { -1L, "%-+,(11d", "(1) " },
- { -1L, "%0 ,(11d", "(000000001)" },
- };
-
- final int input = 0;
- final int pattern = 1;
- final int output = 2;
- Formatter f;
- for (int i = 0; i < triple.length; i++) {
- f = new Formatter(Locale.GERMAN);
- f.format((String) triple[i][pattern],
- triple[i][input]);
- assertEquals("triple[" + i + "]:" + triple[i][input] + ",pattern["
- + i + "]:" + triple[i][pattern], triple[i][output], f
- .toString());
- }
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for legal
- * Byte/Short/Integer/Long conversion type 'o'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify exceptions.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_ByteShortIntegerLongConversionO() {
- final Object[][] triple = {
- { 0, "%o", "0" },
- { 0, "%-6o", "0 " },
- { 0, "%08o", "00000000" },
- { 0, "%#o", "00" },
- { 0, "%0#11o", "00000000000" },
- { 0, "%-#9o", "00 " },
-
- { (byte) 0xff, "%o", "377" },
- { (byte) 0xff, "%-6o", "377 " },
- { (byte) 0xff, "%08o", "00000377" },
- { (byte) 0xff, "%#o", "0377" },
- { (byte) 0xff, "%0#11o", "00000000377" },
- { (byte) 0xff, "%-#9o", "0377 " },
-
- { (short) 0xf123, "%o", "170443" },
- { (short) 0xf123, "%-6o", "170443" },
- { (short) 0xf123, "%08o", "00170443" },
- { (short) 0xf123, "%#o", "0170443" },
- { (short) 0xf123, "%0#11o", "00000170443" },
- { (short) 0xf123, "%-#9o", "0170443 " },
-
- { 0x123456, "%o", "4432126" },
- { 0x123456, "%-6o", "4432126" },
- { 0x123456, "%08o", "04432126" },
- { 0x123456, "%#o", "04432126" },
- { 0x123456, "%0#11o", "00004432126" },
- { 0x123456, "%-#9o", "04432126 " },
-
- { -3, "%o", "37777777775" },
- { -3, "%-6o", "37777777775" },
- { -3, "%08o", "37777777775" },
- { -3, "%#o", "037777777775" },
- { -3, "%0#11o", "037777777775" },
- { -3, "%-#9o", "037777777775" },
-
- { 0x7654321L, "%o", "731241441" },
- { 0x7654321L, "%-6o", "731241441" },
- { 0x7654321L, "%08o", "731241441" },
- { 0x7654321L, "%#o", "0731241441" },
- { 0x7654321L, "%0#11o", "00731241441" },
- { 0x7654321L, "%-#9o", "0731241441" },
-
- { -1L, "%o", "1777777777777777777777" },
- { -1L, "%-6o", "1777777777777777777777" },
- { -1L, "%08o", "1777777777777777777777" },
- { -1L, "%#o", "01777777777777777777777" },
- { -1L, "%0#11o", "01777777777777777777777" },
- { -1L, "%-#9o", "01777777777777777777777" },
- };
-
- final int input = 0;
- final int pattern = 1;
- final int output = 2;
- Formatter f;
- for (int i = 0; i < triple.length; i++) {
- f = new Formatter(Locale.ITALY);
- f.format((String) triple[i][pattern],
- triple[i][input]);
- assertEquals("triple[" + i + "]:" + triple[i][input] + ",pattern["
- + i + "]:" + triple[i][pattern], triple[i][output], f
- .toString());
- }
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for legal
- * Byte/Short/Integer/Long conversion type 'x' and 'X'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify exceptions.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_ByteShortIntegerLongConversionX() {
- final Object[][] triple = {
- { 0, "%x", "0" },
- { 0, "%-8x", "0 " },
- { 0, "%06x", "000000" },
- { 0, "%#x", "0x0" },
- { 0, "%0#12x", "0x0000000000" },
- { 0, "%-#9x", "0x0 " },
-
- { (byte) 0xff, "%x", "ff" },
- { (byte) 0xff, "%-8x", "ff " },
- { (byte) 0xff, "%06x", "0000ff" },
- { (byte) 0xff, "%#x", "0xff" },
- { (byte) 0xff, "%0#12x", "0x00000000ff" },
- { (byte) 0xff, "%-#9x", "0xff " },
-
- { (short) 0xf123, "%x", "f123" },
- { (short) 0xf123, "%-8x", "f123 " },
- { (short) 0xf123, "%06x", "00f123" },
- { (short) 0xf123, "%#x", "0xf123" },
- { (short) 0xf123, "%0#12x", "0x000000f123" },
- { (short) 0xf123, "%-#9x", "0xf123 " },
-
- { 0x123456, "%x", "123456" },
- { 0x123456, "%-8x", "123456 " },
- { 0x123456, "%06x", "123456" },
- { 0x123456, "%#x", "0x123456" },
- { 0x123456, "%0#12x", "0x0000123456" },
- { 0x123456, "%-#9x", "0x123456 " },
-
- { -3, "%x", "fffffffd" },
- { -3, "%-8x", "fffffffd" },
- { -3, "%06x", "fffffffd" },
- { -3, "%#x", "0xfffffffd" },
- { -3, "%0#12x", "0x00fffffffd" },
- { -3, "%-#9x", "0xfffffffd" },
-
- { 0x7654321L, "%x", "7654321" },
- { 0x7654321L, "%-8x", "7654321 " },
- { 0x7654321L, "%06x", "7654321" },
- { 0x7654321L, "%#x", "0x7654321" },
- { 0x7654321L, "%0#12x", "0x0007654321" },
- { 0x7654321L, "%-#9x", "0x7654321" },
-
- { -1L, "%x", "ffffffffffffffff" },
- { -1L, "%-8x", "ffffffffffffffff" },
- { -1L, "%06x", "ffffffffffffffff" },
- { -1L, "%#x", "0xffffffffffffffff" },
- { -1L, "%0#12x", "0xffffffffffffffff" },
- { -1L, "%-#9x", "0xffffffffffffffff" },
- };
-
- final int input = 0;
- final int pattern = 1;
- final int output = 2;
- Formatter f;
- for (int i = 0; i < triple.length; i++) {
- f = new Formatter(Locale.FRANCE);
- f.format((String) triple[i][pattern],
- triple[i][input]);
- assertEquals("triple[" + i + "]:" + triple[i][input] + ",pattern["
- + i + "]:" + triple[i][pattern], triple[i][output], f
- .toString());
-
- f = new Formatter(Locale.FRANCE);
- f.format((String) triple[i][pattern],
- triple[i][input]);
- assertEquals("triple[" + i + "]:" + triple[i][input] + ",pattern["
- + i + "]:" + triple[i][pattern], triple[i][output], f
- .toString());
- }
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for Date/Time
- * conversion
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- @KnownFailure("Conversion for japanese locale works improperly")
- public void test_formatLjava_lang_String$Ljava_lang_Object_DateTimeConversion() {
- Formatter f = null;
- Date now = new Date(1147327147578L);
-
- Calendar paris = Calendar.getInstance(TimeZone
- .getTimeZone("Europe/Paris"), Locale.FRANCE);
- paris.set(2006, 4, 8, 12, 0, 0);
- paris.set(Calendar.MILLISECOND, 453);
- Calendar china = Calendar.getInstance(
- TimeZone.getTimeZone("GMT-08:00"), Locale.CHINA);
- china.set(2006, 4, 8, 12, 0, 0);
- china.set(Calendar.MILLISECOND, 609);
-
- final Object[][] lowerCaseGermanTriple = {
- {0L, 'a', "Do"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'a', "So"}, //$NON-NLS-2$
- {-1000L, 'a', "Do"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'a', "Do"}, //$NON-NLS-2$
- {paris, 'a', "Mo"}, //$NON-NLS-2$
- {china, 'a', "Mo"}, //$NON-NLS-2$
- {0L, 'b', "Jan"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'b', "Aug"}, //$NON-NLS-2$
- {-1000L, 'b', "Jan"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'b', "Mai"}, //$NON-NLS-2$
- {paris, 'b', "Mai"}, //$NON-NLS-2$
- {china, 'b', "Mai"}, //$NON-NLS-2$
- {0L, 'c', "Do Jan 01 08:00:00 CST 1970"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'c', "So Aug 17 15:12:55 CST 292278994"}, //$NON-NLS-2$
- {-1000L, 'c', "Do Jan 01 07:59:59 CST 1970"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'c', "Do Mai 11 13:59:07 CST 2006"}, //$NON-NLS-2$
- {paris, 'c', "Mo Mai 08 12:00:00 CEST 2006"}, //$NON-NLS-2$
- {china, 'c', "Mo Mai 08 12:00:00 GMT-08:00 2006"}, //$NON-NLS-2$
- {0L, 'd', "01"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'd', "17"}, //$NON-NLS-2$
- {-1000L, 'd', "01"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'd', "11"}, //$NON-NLS-2$
- {paris, 'd', "08"}, //$NON-NLS-2$
- {china, 'd', "08"}, //$NON-NLS-2$
- {0L, 'e', "1"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'e', "17"}, //$NON-NLS-2$
- {-1000L, 'e', "1"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'e', "11"}, //$NON-NLS-2$
- {paris, 'e', "8"}, //$NON-NLS-2$
- {china, 'e', "8"}, //$NON-NLS-2$
- {0L, 'h', "Jan"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'h', "Aug"}, //$NON-NLS-2$
- {-1000L, 'h', "Jan"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'h', "Mai"}, //$NON-NLS-2$
- {paris, 'h', "Mai"}, //$NON-NLS-2$
- {china, 'h', "Mai"}, //$NON-NLS-2$
- {0L, 'j', "001"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'j', "229"}, //$NON-NLS-2$
- {-1000L, 'j', "001"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'j', "131"}, //$NON-NLS-2$
- {paris, 'j', "128"}, //$NON-NLS-2$
- {china, 'j', "128"}, //$NON-NLS-2$
- {0L, 'k', "8"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'k', "15"}, //$NON-NLS-2$
- {-1000L, 'k', "7"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'k', "13"}, //$NON-NLS-2$
- {paris, 'k', "12"}, //$NON-NLS-2$
- {china, 'k', "12"}, //$NON-NLS-2$
- {0L, 'l', "8"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'l', "3"}, //$NON-NLS-2$
- {-1000L, 'l', "7"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'l', "1"}, //$NON-NLS-2$
- {paris, 'l', "12"}, //$NON-NLS-2$
- {china, 'l', "12"}, //$NON-NLS-2$
- {0L, 'm', "01"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'm', "08"}, //$NON-NLS-2$
- {-1000L, 'm', "01"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'm', "05"}, //$NON-NLS-2$
- {paris, 'm', "05"}, //$NON-NLS-2$
- {china, 'm', "05"}, //$NON-NLS-2$
- {0L, 'p', "am"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'p', "pm"}, //$NON-NLS-2$
- {-1000L, 'p', "am"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'p', "pm"}, //$NON-NLS-2$
- {paris, 'p', "pm"}, //$NON-NLS-2$
- {china, 'p', "pm"}, //$NON-NLS-2$
- {0L, 'r', "08:00:00 AM"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'r', "03:12:55 PM"}, //$NON-NLS-2$
- {-1000L, 'r', "07:59:59 AM"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'r', "01:59:07 PM"}, //$NON-NLS-2$
- {paris, 'r', "12:00:00 PM"}, //$NON-NLS-2$
- {china, 'r', "12:00:00 PM"}, //$NON-NLS-2$
- {0L, 's', "0"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 's', "9223372036854775"}, //$NON-NLS-2$
- {-1000L, 's', "-1"}, //$NON-NLS-2$
- {new Date(1147327147578L), 's', "1147327147"}, //$NON-NLS-2$
- {paris, 's', "1147082400"}, //$NON-NLS-2$
- {china, 's', "1147118400"}, //$NON-NLS-2$
- {0L, 'y', "70"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'y', "94"}, //$NON-NLS-2$
- {-1000L, 'y', "70"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'y', "06"}, //$NON-NLS-2$
- {paris, 'y', "06"}, //$NON-NLS-2$
- {china, 'y', "06"}, //$NON-NLS-2$
- {0L, 'z', "+0800"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'z', "+0800"}, //$NON-NLS-2$
- {-1000L, 'z', "+0800"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'z', "+0800"}, //$NON-NLS-2$
- {paris, 'z', "+0100"}, //$NON-NLS-2$
- {china, 'z', "-0800"}, //$NON-NLS-2$
-
- };
-
- final Object[][] lowerCaseFranceTriple = {
- {0L, 'a', "jeu."}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'a', "dim."}, //$NON-NLS-2$
- {-1000L, 'a', "jeu."}, //$NON-NLS-2$
- {new Date(1147327147578L), 'a', "jeu."}, //$NON-NLS-2$
- {paris, 'a', "lun."}, //$NON-NLS-2$
- {china, 'a', "lun."}, //$NON-NLS-2$
- {0L, 'b', "janv."}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'b', "ao\u00fbt"}, //$NON-NLS-2$
- {-1000L, 'b', "janv."}, //$NON-NLS-2$
- {new Date(1147327147578L), 'b', "mai"}, //$NON-NLS-2$
- {paris, 'b', "mai"}, //$NON-NLS-2$
- {china, 'b', "mai"}, //$NON-NLS-2$
- {0L, 'c', "jeu. janv. 01 08:00:00 CST 1970"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'c', "dim. ao\u00fbt 17 15:12:55 CST 292278994"}, //$NON-NLS-2$
- {-1000L, 'c', "jeu. janv. 01 07:59:59 CST 1970"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'c', "jeu. mai 11 13:59:07 CST 2006"}, //$NON-NLS-2$
- {paris, 'c', "lun. mai 08 12:00:00 CEST 2006"}, //$NON-NLS-2$
- {china, 'c', "lun. mai 08 12:00:00 GMT-08:00 2006"}, //$NON-NLS-2$
- {0L, 'd', "01"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'd', "17"}, //$NON-NLS-2$
- {-1000L, 'd', "01"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'd', "11"}, //$NON-NLS-2$
- {paris, 'd', "08"}, //$NON-NLS-2$
- {china, 'd', "08"}, //$NON-NLS-2$
- {0L, 'e', "1"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'e', "17"}, //$NON-NLS-2$
- {-1000L, 'e', "1"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'e', "11"}, //$NON-NLS-2$
- {paris, 'e', "8"}, //$NON-NLS-2$
- {china, 'e', "8"}, //$NON-NLS-2$
- {0L, 'h', "janv."}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'h', "ao\u00fbt"}, //$NON-NLS-2$
- {-1000L, 'h', "janv."}, //$NON-NLS-2$
- {new Date(1147327147578L), 'h', "mai"}, //$NON-NLS-2$
- {paris, 'h', "mai"}, //$NON-NLS-2$
- {china, 'h', "mai"}, //$NON-NLS-2$
- {0L, 'j', "001"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'j', "229"}, //$NON-NLS-2$
- {-1000L, 'j', "001"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'j', "131"}, //$NON-NLS-2$
- {paris, 'j', "128"}, //$NON-NLS-2$
- {china, 'j', "128"}, //$NON-NLS-2$
- {0L, 'k', "8"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'k', "15"}, //$NON-NLS-2$
- {-1000L, 'k', "7"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'k', "13"}, //$NON-NLS-2$
- {paris, 'k', "12"}, //$NON-NLS-2$
- {china, 'k', "12"}, //$NON-NLS-2$
- {0L, 'l', "8"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'l', "3"}, //$NON-NLS-2$
- {-1000L, 'l', "7"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'l', "1"}, //$NON-NLS-2$
- {paris, 'l', "12"}, //$NON-NLS-2$
- {china, 'l', "12"}, //$NON-NLS-2$
- {0L, 'm', "01"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'm', "08"}, //$NON-NLS-2$
- {-1000L, 'm', "01"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'm', "05"}, //$NON-NLS-2$
- {paris, 'm', "05"}, //$NON-NLS-2$
- {china, 'm', "05"}, //$NON-NLS-2$
- {0L, 'p', "am"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'p', "pm"}, //$NON-NLS-2$
- {-1000L, 'p', "am"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'p', "pm"}, //$NON-NLS-2$
- {paris, 'p', "pm"}, //$NON-NLS-2$
- {china, 'p', "pm"}, //$NON-NLS-2$
- {0L, 'r', "08:00:00 AM"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'r', "03:12:55 PM"}, //$NON-NLS-2$
- {-1000L, 'r', "07:59:59 AM"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'r', "01:59:07 PM"}, //$NON-NLS-2$
- {paris, 'r', "12:00:00 PM"}, //$NON-NLS-2$
- {china, 'r', "12:00:00 PM"}, //$NON-NLS-2$
- {0L, 's', "0"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 's', "9223372036854775"}, //$NON-NLS-2$
- {-1000L, 's', "-1"}, //$NON-NLS-2$
- {new Date(1147327147578L), 's', "1147327147"}, //$NON-NLS-2$
- {paris, 's', "1147082400"}, //$NON-NLS-2$
- {china, 's', "1147118400"}, //$NON-NLS-2$
- {0L, 'y', "70"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'y', "94"}, //$NON-NLS-2$
- {-1000L, 'y', "70"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'y', "06"}, //$NON-NLS-2$
- {paris, 'y', "06"}, //$NON-NLS-2$
- {china, 'y', "06"}, //$NON-NLS-2$
- {0L, 'z', "+0800"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'z', "+0800"}, //$NON-NLS-2$
- {-1000L, 'z', "+0800"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'z', "+0800"}, //$NON-NLS-2$
- {paris, 'z', "+0100"}, //$NON-NLS-2$
- {china, 'z', "-0800"}, //$NON-NLS-2$
-
- };
-
- final Object[][] lowerCaseJapanTriple = {
- {0L, 'a', "\u6728"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'a', "\u65e5"}, //$NON-NLS-2$
- {-1000L, 'a', "\u6728"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'a', "\u6728"}, //$NON-NLS-2$
- {paris, 'a', "\u6708"}, //$NON-NLS-2$
- {china, 'a', "\u6708"}, //$NON-NLS-2$
- {0L, 'b', "1"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'b', "8"}, //$NON-NLS-2$
- {-1000L, 'b', "1"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'b', "5"}, //$NON-NLS-2$
- {paris, 'b', "5"}, //$NON-NLS-2$
- {china, 'b', "5"}, //$NON-NLS-2$
- {0L, 'c', "\u6728 1 01 08:00:00 CST 1970"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'c', "\u65e5 8 17 15:12:55 CST 292278994"}, //$NON-NLS-2$
- {-1000L, 'c', "\u6728 1 01 07:59:59 CST 1970"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'c', "\u6728 5 11 13:59:07 CST 2006"}, //$NON-NLS-2$
- {paris, 'c', "\u6708 5 08 12:00:00 CEST 2006"}, //$NON-NLS-2$
- {china, 'c', "\u6708 5 08 12:00:00 GMT-08:00 2006"}, //$NON-NLS-2$
- {0L, 'd', "01"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'd', "17"}, //$NON-NLS-2$
- {-1000L, 'd', "01"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'd', "11"}, //$NON-NLS-2$
- {paris, 'd', "08"}, //$NON-NLS-2$
- {china, 'd', "08"}, //$NON-NLS-2$
- {0L, 'e', "1"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'e', "17"}, //$NON-NLS-2$
- {-1000L, 'e', "1"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'e', "11"}, //$NON-NLS-2$
- {paris, 'e', "8"}, //$NON-NLS-2$
- {china, 'e', "8"}, //$NON-NLS-2$
- {0L, 'h', "1"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'h', "8"}, //$NON-NLS-2$
- {-1000L, 'h', "1"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'h', "5"}, //$NON-NLS-2$
- {paris, 'h', "5"}, //$NON-NLS-2$
- {china, 'h', "5"}, //$NON-NLS-2$
- {0L, 'j', "001"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'j', "229"}, //$NON-NLS-2$
- {-1000L, 'j', "001"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'j', "131"}, //$NON-NLS-2$
- {paris, 'j', "128"}, //$NON-NLS-2$
- {china, 'j', "128"}, //$NON-NLS-2$
- {0L, 'k', "8"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'k', "15"}, //$NON-NLS-2$
- {-1000L, 'k', "7"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'k', "13"}, //$NON-NLS-2$
- {paris, 'k', "12"}, //$NON-NLS-2$
- {china, 'k', "12"}, //$NON-NLS-2$
- {0L, 'l', "8"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'l', "3"}, //$NON-NLS-2$
- {-1000L, 'l', "7"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'l', "1"}, //$NON-NLS-2$
- {paris, 'l', "12"}, //$NON-NLS-2$
- {china, 'l', "12"}, //$NON-NLS-2$
- {0L, 'm', "01"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'm', "08"}, //$NON-NLS-2$
- {-1000L, 'm', "01"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'm', "05"}, //$NON-NLS-2$
- {paris, 'm', "05"}, //$NON-NLS-2$
- {china, 'm', "05"}, //$NON-NLS-2$
- {0L, 'p', "\u5348\u524d"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'p', "\u5348\u5f8c"}, //$NON-NLS-2$
- {-1000L, 'p', "\u5348\u524d"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'p', "\u5348\u5f8c"}, //$NON-NLS-2$
- {paris, 'p', "\u5348\u5f8c"}, //$NON-NLS-2$
- {china, 'p', "\u5348\u5f8c"}, //$NON-NLS-2$
- {0L, 'r', "08:00:00 \u5348\u524d"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'r', "03:12:55 \u5348\u5f8c"}, //$NON-NLS-2$
- {-1000L, 'r', "07:59:59 \u5348\u524d"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'r', "01:59:07 \u5348\u5f8c"}, //$NON-NLS-2$
- {paris, 'r', "12:00:00 \u5348\u5f8c"}, //$NON-NLS-2$
- {china, 'r', "12:00:00 \u5348\u5f8c"}, //$NON-NLS-2$
- {0L, 's', "0"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 's', "9223372036854775"}, //$NON-NLS-2$
- {-1000L, 's', "-1"}, //$NON-NLS-2$
- {new Date(1147327147578L), 's', "1147327147"}, //$NON-NLS-2$
- {paris, 's', "1147082400"}, //$NON-NLS-2$
- {china, 's', "1147118400"}, //$NON-NLS-2$
- {0L, 'y', "70"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'y', "94"}, //$NON-NLS-2$
- {-1000L, 'y', "70"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'y', "06"}, //$NON-NLS-2$
- {paris, 'y', "06"}, //$NON-NLS-2$
- {china, 'y', "06"}, //$NON-NLS-2$
- {0L, 'z', "+0800"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'z', "+0800"}, //$NON-NLS-2$
- {-1000L, 'z', "+0800"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'z', "+0800"}, //$NON-NLS-2$
- {paris, 'z', "+0100"}, //$NON-NLS-2$
- {china, 'z', "-0800"}, //$NON-NLS-2$
- };
-
- final int input = 0;
- final int pattern = 1;
- final int output = 2;
- for (int i = 0; i < 90; i++) {
- // go through legal conversion
- String formatSpecifier = "%t" + lowerCaseGermanTriple[i][pattern]; //$NON-NLS-2$
- String formatSpecifierUpper = "%T" + lowerCaseGermanTriple[i][pattern]; //$NON-NLS-2$
- // test '%t'
- f = new Formatter(Locale.GERMAN);
- f.format(formatSpecifier, lowerCaseGermanTriple[i][input]);
- assertEquals("Format pattern: " + formatSpecifier //$NON-NLS-2$
- + " Argument: " + lowerCaseGermanTriple[i][pattern], //$NON-NLS-2$
- lowerCaseGermanTriple[i][output], f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format(Locale.FRANCE, formatSpecifier, lowerCaseFranceTriple[i][input]);
- assertEquals("Format pattern: " + formatSpecifier //$NON-NLS-2$
- + " Argument: " + lowerCaseFranceTriple[i][input], //$NON-NLS-2$
- lowerCaseFranceTriple[i][output], f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format(Locale.JAPAN, formatSpecifier, lowerCaseJapanTriple[i][input]);
- assertEquals("Format pattern: " + formatSpecifier //$NON-NLS-2$
- + " Argument: " + lowerCaseJapanTriple[i][input], //$NON-NLS-2$
- lowerCaseJapanTriple[i][output], f.toString());
-
- // test '%T'
- f = new Formatter(Locale.GERMAN);
- f.format(formatSpecifierUpper, lowerCaseGermanTriple[i][input]);
- assertEquals("Format pattern: " + formatSpecifierUpper //$NON-NLS-2$
- + " Argument: " + lowerCaseGermanTriple[i][input], //$NON-NLS-2$
- ((String)lowerCaseGermanTriple[i][output])
- .toUpperCase(Locale.US), f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format(Locale.FRANCE, formatSpecifierUpper, lowerCaseFranceTriple[i][input]);
- assertEquals("Format pattern: " + formatSpecifierUpper //$NON-NLS-2$
- + " Argument: " + lowerCaseFranceTriple[i][input], //$NON-NLS-2$
- ((String)lowerCaseFranceTriple[i][output])
- .toUpperCase(Locale.US), f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format(Locale.JAPAN, formatSpecifierUpper, lowerCaseJapanTriple[i][input]);
- assertEquals("Format pattern: " + formatSpecifierUpper //$NON-NLS-2$
- + " Argument: " + lowerCaseJapanTriple[i][input], //$NON-NLS-2$
- ((String)lowerCaseJapanTriple[i][output])
- .toUpperCase(Locale.US), f.toString());
- }
-
- final Object[][] upperCaseGermanTriple = {
- {0L, 'A', "Donnerstag"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'A', "Sonntag"}, //$NON-NLS-2$
- {-1000L, 'A', "Donnerstag"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'A', "Donnerstag"}, //$NON-NLS-2$
- {paris, 'A', "Montag"}, //$NON-NLS-2$
- {china, 'A', "Montag"}, //$NON-NLS-2$
- {0L, 'B', "Januar"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'B', "August"}, //$NON-NLS-2$
- {-1000L, 'B', "Januar"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'B', "Mai"}, //$NON-NLS-2$
- {paris, 'B', "Mai"}, //$NON-NLS-2$
- {china, 'B', "Mai"}, //$NON-NLS-2$
- {0L, 'C', "19"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'C', "2922789"}, //$NON-NLS-2$
- {-1000L, 'C', "19"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'C', "20"}, //$NON-NLS-2$
- {paris, 'C', "20"}, //$NON-NLS-2$
- {china, 'C', "20"}, //$NON-NLS-2$
- {0L, 'D', "01/01/70"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'D', "08/17/94"}, //$NON-NLS-2$
- {-1000L, 'D', "01/01/70"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'D', "05/11/06"}, //$NON-NLS-2$
- {paris, 'D', "05/08/06"}, //$NON-NLS-2$
- {china, 'D', "05/08/06"}, //$NON-NLS-2$
- {0L, 'F', "1970-01-01"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'F', "292278994-08-17"}, //$NON-NLS-2$
- {-1000L, 'F', "1970-01-01"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'F', "2006-05-11"}, //$NON-NLS-2$
- {paris, 'F', "2006-05-08"}, //$NON-NLS-2$
- {china, 'F', "2006-05-08"}, //$NON-NLS-2$
- {0L, 'H', "08"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'H', "15"}, //$NON-NLS-2$
- {-1000L, 'H', "07"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'H', "13"}, //$NON-NLS-2$
- {paris, 'H', "12"}, //$NON-NLS-2$
- {china, 'H', "12"}, //$NON-NLS-2$
- {0L, 'I', "08"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'I', "03"}, //$NON-NLS-2$
- {-1000L, 'I', "07"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'I', "01"}, //$NON-NLS-2$
- {paris, 'I', "12"}, //$NON-NLS-2$
- {china, 'I', "12"}, //$NON-NLS-2$
- {0L, 'L', "000"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'L', "807"}, //$NON-NLS-2$
- {-1000L, 'L', "000"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'L', "578"}, //$NON-NLS-2$
- {paris, 'L', "453"}, //$NON-NLS-2$
- {china, 'L', "609"}, //$NON-NLS-2$
- {0L, 'M', "00"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'M', "12"}, //$NON-NLS-2$
- {-1000L, 'M', "59"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'M', "59"}, //$NON-NLS-2$
- {paris, 'M', "00"}, //$NON-NLS-2$
- {china, 'M', "00"}, //$NON-NLS-2$
- {0L, 'N', "000000000"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'N', "807000000"}, //$NON-NLS-2$
- {-1000L, 'N', "000000000"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'N', "578000000"}, //$NON-NLS-2$
- {paris, 'N', "609000000"}, //$NON-NLS-2$
- {china, 'N', "609000000"}, //$NON-NLS-2$
- {0L, 'Q', "0"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'Q', "9223372036854775807"}, //$NON-NLS-2$
- {-1000L, 'Q', "-1000"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'Q', "1147327147578"}, //$NON-NLS-2$
- {paris, 'Q', "1147082400453"}, //$NON-NLS-2$
- {china, 'Q', "1147118400609"}, //$NON-NLS-2$
- {0L, 'R', "08:00"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'R', "15:12"}, //$NON-NLS-2$
- {-1000L, 'R', "07:59"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'R', "13:59"}, //$NON-NLS-2$
- {paris, 'R', "12:00"}, //$NON-NLS-2$
- {china, 'R', "12:00"}, //$NON-NLS-2$
- {0L, 'S', "00"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'S', "55"}, //$NON-NLS-2$
- {-1000L, 'S', "59"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'S', "07"}, //$NON-NLS-2$
- {paris, 'S', "00"}, //$NON-NLS-2$
- {china, 'S', "00"}, //$NON-NLS-2$
- {0L, 'T', "08:00:00"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'T', "15:12:55"}, //$NON-NLS-2$
- {-1000L, 'T', "07:59:59"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'T', "13:59:07"}, //$NON-NLS-2$
- {paris, 'T', "12:00:00"}, //$NON-NLS-2$
- {china, 'T', "12:00:00"}, //$NON-NLS-2$
- {0L, 'Y', "1970"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'Y', "292278994"}, //$NON-NLS-2$
- {-1000L, 'Y', "1970"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'Y', "2006"}, //$NON-NLS-2$
- {paris, 'Y', "2006"}, //$NON-NLS-2$
- {china, 'Y', "2006"}, //$NON-NLS-2$
- {0L, 'Z', "CST"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'Z', "CST"}, //$NON-NLS-2$
- {-1000L, 'Z', "CST"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'Z', "CST"}, //$NON-NLS-2$
- {paris, 'Z', "CEST"}, //$NON-NLS-2$
- {china, 'Z', "GMT-08:00"}, //$NON-NLS-2$
-
- };
-
- final Object[][] upperCaseFranceTriple = {
- {0L, 'A', "jeudi"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'A', "dimanche"}, //$NON-NLS-2$
- {-1000L, 'A', "jeudi"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'A', "jeudi"}, //$NON-NLS-2$
- {paris, 'A', "lundi"}, //$NON-NLS-2$
- {china, 'A', "lundi"}, //$NON-NLS-2$
- {0L, 'B', "janvier"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'B', "ao\u00fbt"}, //$NON-NLS-2$
- {-1000L, 'B', "janvier"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'B', "mai"}, //$NON-NLS-2$
- {paris, 'B', "mai"}, //$NON-NLS-2$
- {china, 'B', "mai"}, //$NON-NLS-2$
- {0L, 'C', "19"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'C', "2922789"}, //$NON-NLS-2$
- {-1000L, 'C', "19"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'C', "20"}, //$NON-NLS-2$
- {paris, 'C', "20"}, //$NON-NLS-2$
- {china, 'C', "20"}, //$NON-NLS-2$
- {0L, 'D', "01/01/70"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'D', "08/17/94"}, //$NON-NLS-2$
- {-1000L, 'D', "01/01/70"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'D', "05/11/06"}, //$NON-NLS-2$
- {paris, 'D', "05/08/06"}, //$NON-NLS-2$
- {china, 'D', "05/08/06"}, //$NON-NLS-2$
- {0L, 'F', "1970-01-01"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'F', "292278994-08-17"}, //$NON-NLS-2$
- {-1000L, 'F', "1970-01-01"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'F', "2006-05-11"}, //$NON-NLS-2$
- {paris, 'F', "2006-05-08"}, //$NON-NLS-2$
- {china, 'F', "2006-05-08"}, //$NON-NLS-2$
- {0L, 'H', "08"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'H', "15"}, //$NON-NLS-2$
- {-1000L, 'H', "07"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'H', "13"}, //$NON-NLS-2$
- {paris, 'H', "12"}, //$NON-NLS-2$
- {china, 'H', "12"}, //$NON-NLS-2$
- {0L, 'I', "08"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'I', "03"}, //$NON-NLS-2$
- {-1000L, 'I', "07"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'I', "01"}, //$NON-NLS-2$
- {paris, 'I', "12"}, //$NON-NLS-2$
- {china, 'I', "12"}, //$NON-NLS-2$
- {0L, 'L', "000"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'L', "807"}, //$NON-NLS-2$
- {-1000L, 'L', "000"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'L', "578"}, //$NON-NLS-2$
- {paris, 'L', "453"}, //$NON-NLS-2$
- {china, 'L', "609"}, //$NON-NLS-2$
- {0L, 'M', "00"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'M', "12"}, //$NON-NLS-2$
- {-1000L, 'M', "59"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'M', "59"}, //$NON-NLS-2$
- {paris, 'M', "00"}, //$NON-NLS-2$
- {china, 'M', "00"}, //$NON-NLS-2$
- {0L, 'N', "000000000"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'N', "807000000"}, //$NON-NLS-2$
- {-1000L, 'N', "000000000"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'N', "578000000"}, //$NON-NLS-2$
- {paris, 'N', "453000000"}, //$NON-NLS-2$
- {china, 'N', "468000000"}, //$NON-NLS-2$
- {0L, 'Q', "0"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'Q', "9223372036854775807"}, //$NON-NLS-2$
- {-1000L, 'Q', "-1000"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'Q', "1147327147578"}, //$NON-NLS-2$
- {paris, 'Q', "1147082400453"}, //$NON-NLS-2$
- {china, 'Q', "1147118400609"}, //$NON-NLS-2$
- {0L, 'R', "08:00"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'R', "15:12"}, //$NON-NLS-2$
- {-1000L, 'R', "07:59"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'R', "13:59"}, //$NON-NLS-2$
- {paris, 'R', "12:00"}, //$NON-NLS-2$
- {china, 'R', "12:00"}, //$NON-NLS-2$
- {0L, 'S', "00"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'S', "55"}, //$NON-NLS-2$
- {-1000L, 'S', "59"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'S', "07"}, //$NON-NLS-2$
- {paris, 'S', "00"}, //$NON-NLS-2$
- {china, 'S', "00"}, //$NON-NLS-2$
- {0L, 'T', "08:00:00"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'T', "15:12:55"}, //$NON-NLS-2$
- {-1000L, 'T', "07:59:59"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'T', "13:59:07"}, //$NON-NLS-2$
- {paris, 'T', "12:00:00"}, //$NON-NLS-2$
- {china, 'T', "12:00:00"}, //$NON-NLS-2$
- {0L, 'Y', "1970"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'Y', "292278994"}, //$NON-NLS-2$
- {-1000L, 'Y', "1970"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'Y', "2006"}, //$NON-NLS-2$
- {paris, 'Y', "2006"}, //$NON-NLS-2$
- {china, 'Y', "2006"}, //$NON-NLS-2$
- {0L, 'Z', "CST"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'Z', "CST"}, //$NON-NLS-2$
- {-1000L, 'Z', "CST"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'Z', "CST"}, //$NON-NLS-2$
- {paris, 'Z', "CEST"}, //$NON-NLS-2$
- {china, 'Z', "GMT-08:00"}, //$NON-NLS-2$
-
- };
-
- final Object[][] upperCaseJapanTriple = {
- {0L, 'A', "\u6728\u66dc\u65e5"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'A', "\u65e5\u66dc\u65e5"}, //$NON-NLS-2$
- {-1000L, 'A', "\u6728\u66dc\u65e5"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'A', "\u6728\u66dc\u65e5"}, //$NON-NLS-2$
- {paris, 'A', "\u6708\u66dc\u65e5"}, //$NON-NLS-2$
- {china, 'A', "\u6708\u66dc\u65e5"}, //$NON-NLS-2$
- {0L, 'B', "1\u6708"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'B', "8\u6708"}, //$NON-NLS-2$
- {-1000L, 'B', "1\u6708"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'B', "5\u6708"}, //$NON-NLS-2$
- {paris, 'B', "5\u6708"}, //$NON-NLS-2$
- {china, 'B', "5\u6708"}, //$NON-NLS-2$
- {0L, 'C', "19"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'C', "2922789"}, //$NON-NLS-2$
- {-1000L, 'C', "19"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'C', "20"}, //$NON-NLS-2$
- {paris, 'C', "20"}, //$NON-NLS-2$
- {china, 'C', "20"}, //$NON-NLS-2$
- {0L, 'D', "01/01/70"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'D', "08/17/94"}, //$NON-NLS-2$
- {-1000L, 'D', "01/01/70"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'D', "05/11/06"}, //$NON-NLS-2$
- {paris, 'D', "05/08/06"}, //$NON-NLS-2$
- {china, 'D', "05/08/06"}, //$NON-NLS-2$
- {0L, 'F', "1970-01-01"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'F', "292278994-08-17"}, //$NON-NLS-2$
- {-1000L, 'F', "1970-01-01"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'F', "2006-05-11"}, //$NON-NLS-2$
- {paris, 'F', "2006-05-08"}, //$NON-NLS-2$
- {china, 'F', "2006-05-08"}, //$NON-NLS-2$
- {0L, 'H', "08"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'H', "15"}, //$NON-NLS-2$
- {-1000L, 'H', "07"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'H', "13"}, //$NON-NLS-2$
- {paris, 'H', "12"}, //$NON-NLS-2$
- {china, 'H', "12"}, //$NON-NLS-2$
- {0L, 'I', "08"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'I', "03"}, //$NON-NLS-2$
- {-1000L, 'I', "07"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'I', "01"}, //$NON-NLS-2$
- {paris, 'I', "12"}, //$NON-NLS-2$
- {china, 'I', "12"}, //$NON-NLS-2$
- {0L, 'L', "000"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'L', "807"}, //$NON-NLS-2$
- {-1000L, 'L', "000"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'L', "578"}, //$NON-NLS-2$
- {paris, 'L', "453"}, //$NON-NLS-2$
- {china, 'L', "609"}, //$NON-NLS-2$
- {0L, 'M', "00"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'M', "12"}, //$NON-NLS-2$
- {-1000L, 'M', "59"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'M', "59"}, //$NON-NLS-2$
- {paris, 'M', "00"}, //$NON-NLS-2$
- {china, 'M', "00"}, //$NON-NLS-2$
- {0L, 'N', "000000000"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'N', "807000000"}, //$NON-NLS-2$
- {-1000L, 'N', "000000000"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'N', "578000000"}, //$NON-NLS-2$
- {paris, 'N', "453000000"}, //$NON-NLS-2$
- {china, 'N', "468000000"}, //$NON-NLS-2$
- {0L, 'Q', "0"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'Q', "9223372036854775807"}, //$NON-NLS-2$
- {-1000L, 'Q', "-1000"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'Q', "1147327147578"}, //$NON-NLS-2$
- {paris, 'Q', "1147082400453"}, //$NON-NLS-2$
- {china, 'Q', "1147118400609"}, //$NON-NLS-2$
- {0L, 'R', "08:00"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'R', "15:12"}, //$NON-NLS-2$
- {-1000L, 'R', "07:59"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'R', "13:59"}, //$NON-NLS-2$
- {paris, 'R', "12:00"}, //$NON-NLS-2$
- {china, 'R', "12:00"}, //$NON-NLS-2$
- {0L, 'S', "00"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'S', "55"}, //$NON-NLS-2$
- {-1000L, 'S', "59"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'S', "07"}, //$NON-NLS-2$
- {paris, 'S', "00"}, //$NON-NLS-2$
- {china, 'S', "00"}, //$NON-NLS-2$
- {0L, 'T', "08:00:00"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'T', "15:12:55"}, //$NON-NLS-2$
- {-1000L, 'T', "07:59:59"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'T', "13:59:07"}, //$NON-NLS-2$
- {paris, 'T', "12:00:00"}, //$NON-NLS-2$
- {china, 'T', "12:00:00"}, //$NON-NLS-2$
- {0L, 'Y', "1970"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'Y', "292278994"}, //$NON-NLS-2$
- {-1000L, 'Y', "1970"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'Y', "2006"}, //$NON-NLS-2$
- {paris, 'Y', "2006"}, //$NON-NLS-2$
- {china, 'Y', "2006"}, //$NON-NLS-2$
- {0L, 'Z', "CST"}, //$NON-NLS-2$
- {Long.MAX_VALUE, 'Z', "CST"}, //$NON-NLS-2$
- {-1000L, 'Z', "CST"}, //$NON-NLS-2$
- {new Date(1147327147578L), 'Z', "CST"}, //$NON-NLS-2$
- {paris, 'Z', "CEST"}, //$NON-NLS-2$
- {china, 'Z', "GMT-08:00"}, //$NON-NLS-2$
- };
-
-
- for (int i = 0; i < 90; i++) {
- String formatSpecifier = "%t" + upperCaseGermanTriple[i][pattern]; //$NON-NLS-2$
- String formatSpecifierUpper = "%T" + upperCaseGermanTriple[i][pattern]; //$NON-NLS-2$
- if ((Character)upperCaseGermanTriple[i][pattern] == 'N') {
- // result can't be predicted on RI, so skip this test
- continue;
- }
- // test '%t'
- f = new Formatter(Locale.JAPAN);
- f.format(formatSpecifier, upperCaseJapanTriple[i][input]);
- assertEquals("Format pattern: " + formatSpecifier //$NON-NLS-2$
- + " Argument: " + upperCaseJapanTriple[i][input], //$NON-NLS-2$
- upperCaseJapanTriple[i][output], f.toString());
-
- f = new Formatter(Locale.JAPAN);
- f.format(Locale.GERMAN, formatSpecifier, upperCaseGermanTriple[i][input]);
- assertEquals("Format pattern: " + formatSpecifier //$NON-NLS-2$
- + " Argument: " + upperCaseGermanTriple[i][input], //$NON-NLS-2$
- upperCaseGermanTriple[i][output], f.toString());
-
- f = new Formatter(Locale.JAPAN);
- f.format(Locale.FRANCE, formatSpecifier, upperCaseFranceTriple[i][input]);
- assertEquals("Format pattern: " + formatSpecifier //$NON-NLS-2$
- + " Argument: " + upperCaseFranceTriple[i][input], //$NON-NLS-2$
- upperCaseFranceTriple[i][output], f.toString());
-
- // test '%T'
- f = new Formatter(Locale.GERMAN);
- f.format(formatSpecifierUpper, upperCaseGermanTriple[i][input]);
- assertEquals("Format pattern: " + formatSpecifierUpper //$NON-NLS-2$
- + " Argument: " + upperCaseGermanTriple[i][input], //$NON-NLS-2$
- ((String)upperCaseGermanTriple[i][output])
- .toUpperCase(Locale.US), f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format(Locale.JAPAN, formatSpecifierUpper, upperCaseJapanTriple[i][input]);
- assertEquals("Format pattern: " + formatSpecifierUpper //$NON-NLS-2$
- + " Argument: " + upperCaseJapanTriple[i][input], //$NON-NLS-2$
- ((String)upperCaseJapanTriple[i][output])
- .toUpperCase(Locale.US), f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format(Locale.FRANCE, formatSpecifierUpper, upperCaseFranceTriple[i][input]);
- assertEquals("Format pattern: " + formatSpecifierUpper //$NON-NLS-2$
- + " Argument: " + upperCaseFranceTriple[i][input], //$NON-NLS-2$
- ((String)upperCaseFranceTriple[i][output])
- .toUpperCase(Locale.US), f.toString());
- }
-
- f = new Formatter(Locale.US);
- f.format("%-10ta", now); //$NON-NLS-2$
- assertEquals("Thu ", f.toString()); //$NON-NLS-2$
-
- f = new Formatter(Locale.US);
- f.format("%10000000000000000000000000000000001ta", now); //$NON-NLS-2$
- assertEquals("Thu", f.toString().trim()); //$NON-NLS-2$
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for null argment for
- * Byte/Short/Integer/Long/BigInteger conversion
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies null as the second parameter.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_ByteShortIntegerLongNullConversion() {
-
- Formatter f = new Formatter(Locale.FRANCE);
- f.format("%d%<o%<x%<5X", (Integer) null);
- assertEquals("nullnullnull NULL", f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format("%d%<#03o %<0#4x%<6X", (Long) null);
- assertEquals("nullnull null NULL", f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format("%(+,07d%<o %<x%<6X", (Byte) null);
- assertEquals(" nullnull null NULL", f.toString());
-
- f = new Formatter(Locale.ITALY);
- f.format("%(+,07d%<o %<x%<0#6X", (Short) null);
- assertEquals(" nullnull null NULL", f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format("%(+,-7d%<( o%<+(x %<( 06X", (BigInteger) null);
- assertEquals("null nullnull NULL", f.toString());
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for legal
- * BigInteger conversion type 'd'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify IllegalFormatException, FormatterClosedException.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$LBigInteger() {
- final Object[][] tripleD = {
- {new BigInteger("123456789012345678901234567890"), "%d", "123456789012345678901234567890"}, //$NON-NLS-2$
- {new BigInteger("123456789012345678901234567890"), "%10d", "123456789012345678901234567890"}, //$NON-NLS-2$
- {new BigInteger("123456789012345678901234567890"), "%-1d", "123456789012345678901234567890"}, //$NON-NLS-2$
- {new BigInteger("123456789012345678901234567890"), "%+d", "+123456789012345678901234567890"}, //$NON-NLS-2$
- {new BigInteger("123456789012345678901234567890"), "% d", " 123456789012345678901234567890"}, //$NON-NLS-2$
- {new BigInteger("123456789012345678901234567890"), "%,d", "123.456.789.012.345.678.901.234.567.890"}, //$NON-NLS-2$
- {new BigInteger("123456789012345678901234567890"), "%(d", "123456789012345678901234567890"}, //$NON-NLS-2$
- {new BigInteger("123456789012345678901234567890"), "%08d", "123456789012345678901234567890"}, //$NON-NLS-2$
- {new BigInteger("123456789012345678901234567890"), "%-+,(11d", "+123.456.789.012.345.678.901.234.567.890"}, //$NON-NLS-2$
- {new BigInteger("123456789012345678901234567890"), "%0 ,(11d", " 123.456.789.012.345.678.901.234.567.890"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%d", "-9876543210987654321098765432100000"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%10d", "-9876543210987654321098765432100000"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%-1d", "-9876543210987654321098765432100000"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%+d", "-9876543210987654321098765432100000"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "% d", "-9876543210987654321098765432100000"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%,d", "-9.876.543.210.987.654.321.098.765.432.100.000"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%(d", "(9876543210987654321098765432100000)"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%08d", "-9876543210987654321098765432100000"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%-+,(11d", "(9.876.543.210.987.654.321.098.765.432.100.000)"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%0 ,(11d", "(9.876.543.210.987.654.321.098.765.432.100.000)"}, //$NON-NLS-2$
- };
-
- final int input = 0;
- final int pattern = 1;
- final int output = 2;
- Formatter f;
- for (int i = 0; i < tripleD.length; i++) {
- f = new Formatter(Locale.GERMAN);
- f.format((String) tripleD[i][pattern],
- tripleD[i][input]);
- assertEquals("triple[" + i + "]:" + tripleD[i][input] + ",pattern["
- + i + "]:" + tripleD[i][pattern], tripleD[i][output], f
- .toString());
-
- }
-
- final Object[][] tripleO = {
- {new BigInteger("123456789012345678901234567890"), "%o", "143564417755415637016711617605322"}, //$NON-NLS-2$
- {new BigInteger("123456789012345678901234567890"), "%-6o", "143564417755415637016711617605322"}, //$NON-NLS-2$
- {new BigInteger("123456789012345678901234567890"), "%08o", "143564417755415637016711617605322"}, //$NON-NLS-2$
- {new BigInteger("123456789012345678901234567890"), "%#o", "0143564417755415637016711617605322"}, //$NON-NLS-2$
- {new BigInteger("123456789012345678901234567890"), "%0#11o", "0143564417755415637016711617605322"}, //$NON-NLS-2$
- {new BigInteger("123456789012345678901234567890"), "%-#9o", "0143564417755415637016711617605322"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%o", "-36336340043453651353467270113157312240"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%-6o", "-36336340043453651353467270113157312240"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%08o", "-36336340043453651353467270113157312240"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%#o", "-036336340043453651353467270113157312240"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%0#11o", "-036336340043453651353467270113157312240"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%-#9o", "-036336340043453651353467270113157312240"}, //$NON-NLS-2$
- };
- for (int i = 0; i < tripleO.length; i++) {
- f = new Formatter(Locale.ITALY);
- f.format((String) tripleO[i][pattern],
- tripleO[i][input]);
- assertEquals("triple[" + i + "]:" + tripleO[i][input] + ",pattern["
- + i + "]:" + tripleO[i][pattern], tripleO[i][output], f
- .toString());
-
- }
-
- final Object[][] tripleX = {
- {new BigInteger("123456789012345678901234567890"), "%x", "18ee90ff6c373e0ee4e3f0ad2"}, //$NON-NLS-2$
- {new BigInteger("123456789012345678901234567890"), "%-8x", "18ee90ff6c373e0ee4e3f0ad2"}, //$NON-NLS-2$
- {new BigInteger("123456789012345678901234567890"), "%06x", "18ee90ff6c373e0ee4e3f0ad2"}, //$NON-NLS-2$
- {new BigInteger("123456789012345678901234567890"), "%#x", "0x18ee90ff6c373e0ee4e3f0ad2"}, //$NON-NLS-2$
- {new BigInteger("123456789012345678901234567890"), "%0#12x", "0x18ee90ff6c373e0ee4e3f0ad2"}, //$NON-NLS-2$
- {new BigInteger("123456789012345678901234567890"), "%-#9x", "0x18ee90ff6c373e0ee4e3f0ad2"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%x", "-1e6f380472bd4bae6eb8259bd94a0"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%-8x", "-1e6f380472bd4bae6eb8259bd94a0"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%06x", "-1e6f380472bd4bae6eb8259bd94a0"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%#x", "-0x1e6f380472bd4bae6eb8259bd94a0"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%0#12x", "-0x1e6f380472bd4bae6eb8259bd94a0"}, //$NON-NLS-2$
- {new BigInteger("-9876543210987654321098765432100000"), "%-#9x", "-0x1e6f380472bd4bae6eb8259bd94a0"}, //$NON-NLS-2$
- };
-
- for (int i = 0; i < tripleX.length; i++) {
- f = new Formatter(Locale.FRANCE);
- f.format((String) tripleX[i][pattern],
- tripleX[i][input]);
- assertEquals("triple[" + i + "]:" + tripleX[i][input] + ",pattern["
- + i + "]:" + tripleX[i][pattern], tripleX[i][output], f
- .toString());
-
- }
-
- f = new Formatter(Locale.GERMAN);
- f.format("%(+,-7d%<( o%<+(x %<( 06X", (BigInteger) null);
- assertEquals("null nullnull NULL", f.toString());
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for padding of
- * BigInteger conversion
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies boundary conditions.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_BigIntegerPaddingConversion() {
- Formatter f = null;
-
- BigInteger bigInt = new BigInteger("123456789012345678901234567890");
- f = new Formatter(Locale.GERMAN);
- f.format("%32d", bigInt);
- assertEquals(" 123456789012345678901234567890", f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format("%+32x", bigInt);
- assertEquals(" +18ee90ff6c373e0ee4e3f0ad2", f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format("% 32o", bigInt);
- assertEquals(" 143564417755415637016711617605322", f.toString());
-
- BigInteger negBigInt = new BigInteger(
- "-1234567890123456789012345678901234567890");
- f = new Formatter(Locale.GERMAN);
- f.format("%( 040X", negBigInt);
- assertEquals("(000003A0C92075C0DBF3B8ACBC5F96CE3F0AD2)", f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format("%+(045d", negBigInt);
- assertEquals("(0001234567890123456789012345678901234567890)", f
- .toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format("%+,-(60d", negBigInt);
- assertEquals(
- "(1.234.567.890.123.456.789.012.345.678.901.234.567.890) ",
- f.toString());
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for BigInteger
- * conversion exception
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies exceptions.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_BigIntegerConversionException() {
- Formatter f = null;
-
- final String[] flagsConversionMismatches = { "%#d", "%,o", "%,x", "%,X" };
- for (int i = 0; i < flagsConversionMismatches.length; i++) {
- try {
- f = new Formatter(Locale.CHINA);
- f.format(flagsConversionMismatches[i], new BigInteger("1"));
- fail("should throw FormatFlagsConversionMismatchException");
- } catch (FormatFlagsConversionMismatchException e) {
- // expected
- }
- }
-
- final String[] missingFormatWidths = { "%-0d", "%0d", "%-d", "%-0o",
- "%0o", "%-o", "%-0x", "%0x", "%-x", "%-0X", "%0X", "%-X" };
- for (int i = 0; i < missingFormatWidths.length; i++) {
- try {
- f = new Formatter(Locale.KOREA);
- f.format(missingFormatWidths[i], new BigInteger("1"));
- fail("should throw MissingFormatWidthException");
- } catch (MissingFormatWidthException e) {
- // expected
- }
- }
-
- final String[] illFlags = { "%+ d", "%-08d", "%+ o", "%-08o", "%+ x",
- "%-08x", "%+ X", "%-08X" };
- for (int i = 0; i < illFlags.length; i++) {
- try {
- f = new Formatter(Locale.CANADA);
- f.format(illFlags[i], new BigInteger("1"));
- fail("should throw IllegalFormatFlagsException");
- } catch (IllegalFormatFlagsException e) {
- // expected
- }
- }
-
- final String[] precisionExceptions = { "%.4d", "%2.5o", "%8.6x",
- "%11.17X" };
- for (int i = 0; i < precisionExceptions.length; i++) {
- try {
- f = new Formatter(Locale.US);
- f.format(precisionExceptions[i], new BigInteger("1"));
- fail("should throw IllegalFormatPrecisionException");
- } catch (IllegalFormatPrecisionException e) {
- // expected
- }
- }
-
- f = new Formatter(Locale.US);
- try {
- f.format("%D", new BigInteger("1"));
- fail("should throw UnknownFormatConversionException");
- } catch (UnknownFormatConversionException e) {
- // expected
- }
-
- f = new Formatter(Locale.US);
- try {
- f.format("%O", new BigInteger("1"));
- fail("should throw UnknownFormatConversionException");
- } catch (UnknownFormatConversionException e) {
- // expected
- }
-
- try {
- f = new Formatter();
- f.format("%010000000000000000000000000000000001d", new BigInteger(
- "1"));
- fail("should throw MissingFormatWidthException");
- } catch (MissingFormatWidthException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for BigInteger
- * exception throwing order
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies exceptions.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_BigIntegerExceptionOrder() {
- Formatter f = null;
- BigInteger big = new BigInteger("100");
-
- /*
- * Order summary: UnknownFormatConversionException >
- * MissingFormatWidthException > IllegalFormatFlagsException >
- * IllegalFormatPrecisionException > IllegalFormatConversionException >
- * FormatFlagsConversionMismatchException
- *
- */
- f = new Formatter(Locale.US);
- try {
- // compare IllegalFormatConversionException and
- // FormatFlagsConversionMismatchException
- f.format("%(o", false);
- fail("should throw IllegalFormatConversionException");
- } catch (IllegalFormatConversionException e) {
- // expected
- }
-
- try {
- // compare IllegalFormatPrecisionException and
- // IllegalFormatConversionException
- f.format("%.4o", false);
- fail("should throw IllegalFormatPrecisionException");
- } catch (IllegalFormatPrecisionException e) {
- // expected
- }
-
- try {
- // compare IllegalFormatFlagsException and
- // IllegalFormatPrecisionException
- f.format("%+ .4o", big);
- fail("should throw IllegalFormatFlagsException");
- } catch (IllegalFormatFlagsException e) {
- // expected
- }
-
- try {
- // compare MissingFormatWidthException and
- // IllegalFormatFlagsException
- f.format("%+ -o", big);
- fail("should throw MissingFormatWidthException");
- } catch (MissingFormatWidthException e) {
- // expected
- }
-
- try {
- // compare UnknownFormatConversionException and
- // MissingFormatWidthException
- f.format("%-O", big);
- fail("should throw UnknownFormatConversionException");
- } catch (UnknownFormatConversionException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for Float/Double
- * conversion type 'e' and 'E'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify exceptions.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- @KnownFailure("Formatting of Double.MIN_VALUE works improperly")
- @AndroidOnly("last case fails on RI. See comment below")
- public void test_formatLjava_lang_String$Ljava_lang_Object_FloatConversionE() {
- Formatter f = null;
- final Object[][] tripleE = {
- {0f, "%e", "0.000000e+00"},
- {0f, "%#.0e", "0.e+00"},
- {0f, "%#- (9.8e", " 0.00000000e+00"},
- {0f, "%#+0(8.4e", "+0.0000e+00"},
- {0f, "%-+(1.6e", "+0.000000e+00"},
- {0f, "% 0(12e", " 0.000000e+00"},
-
- {101f, "%e", "1.010000e+02"},
- {101f, "%#.0e", "1.e+02"},
- {101f, "%#- (9.8e", " 1.01000000e+02"},
- {101f, "%#+0(8.4e", "+1.0100e+02"},
- {101f, "%-+(1.6e", "+1.010000e+02"},
- {101f, "% 0(12e", " 1.010000e+02"},
-
- {1.f, "%e", "1.000000e+00"},
- {1.f, "%#.0e", "1.e+00"},
- {1.f, "%#- (9.8e", " 1.00000000e+00"},
- {1.f, "%#+0(8.4e", "+1.0000e+00"},
- {1.f, "%-+(1.6e", "+1.000000e+00"},
- {1.f, "% 0(12e", " 1.000000e+00"},
-
- {-98f, "%e", "-9.800000e+01"},
- {-98f, "%#.0e", "-1.e+02"},
- {-98f, "%#- (9.8e", "(9.80000000e+01)"},
- {-98f, "%#+0(8.4e", "(9.8000e+01)"},
- {-98f, "%-+(1.6e", "(9.800000e+01)"},
- {-98f, "% 0(12e", "(9.800000e+01)"},
-
- {1.23f, "%e", "1.230000e+00"},
- {1.23f, "%#.0e", "1.e+00"},
- {1.23f, "%#- (9.8e", " 1.23000002e+00"},
- {1.23f, "%#+0(8.4e", "+1.2300e+00"},
- {1.23f, "%-+(1.6e", "+1.230000e+00"},
- {1.23f, "% 0(12e", " 1.230000e+00"},
-
- {34.1234567f, "%e", "3.412346e+01"},
- {34.1234567f, "%#.0e", "3.e+01"},
- {34.1234567f, "%#- (9.8e", " 3.41234550e+01"},
- {34.1234567f, "%#+0(8.4e", "+3.4123e+01"},
- {34.1234567f, "%-+(1.6e", "+3.412346e+01"},
- {34.1234567f, "% 0(12e", " 3.412346e+01"},
-
- {-.12345f, "%e", "-1.234500e-01"},
- {-.12345f, "%#.0e", "-1.e-01"},
- {-.12345f, "%#- (9.8e", "(1.23450004e-01)"},
- {-.12345f, "%#+0(8.4e", "(1.2345e-01)"},
- {-.12345f, "%-+(1.6e", "(1.234500e-01)"},
- {-.12345f, "% 0(12e", "(1.234500e-01)"},
-
- {-9876.1234567f, "%e", "-9.876123e+03"},
- {-9876.1234567f, "%#.0e", "-1.e+04"},
- {-9876.1234567f, "%#- (9.8e", "(9.87612305e+03)"},
- {-9876.1234567f, "%#+0(8.4e", "(9.8761e+03)"},
- {-9876.1234567f, "%-+(1.6e", "(9.876123e+03)"},
- {-9876.1234567f, "% 0(12e", "(9.876123e+03)"},
-
- {Float.MAX_VALUE, "%e", "3.402823e+38"},
- {Float.MAX_VALUE, "%#.0e", "3.e+38"},
- {Float.MAX_VALUE, "%#- (9.8e", " 3.40282347e+38"},
- {Float.MAX_VALUE, "%#+0(8.4e", "+3.4028e+38"},
- {Float.MAX_VALUE, "%-+(1.6e", "+3.402823e+38"},
- {Float.MAX_VALUE, "% 0(12e", " 3.402823e+38"},
-
- {Float.MIN_VALUE, "%e", "1.401298e-45"},
- {Float.MIN_VALUE, "%#.0e", "1.e-45"},
- {Float.MIN_VALUE, "%#- (9.8e", " 1.40129846e-45"},
- {Float.MIN_VALUE, "%#+0(8.4e", "+1.4013e-45"},
- {Float.MIN_VALUE, "%-+(1.6e", "+1.401298e-45"},
- {Float.MIN_VALUE, "% 0(12e", " 1.401298e-45"},
-
- {Float.NaN, "%e", "NaN"},
- {Float.NaN, "%#.0e", "NaN"},
- {Float.NaN, "%#- (9.8e", "NaN "},
- {Float.NaN, "%#+0(8.4e", " NaN"},
- {Float.NaN, "%-+(1.6e", "NaN"},
- {Float.NaN, "% 0(12e", " NaN"},
-
-
- {Float.NEGATIVE_INFINITY, "%e", "-Infinity"},
- {Float.NEGATIVE_INFINITY, "%#.0e", "-Infinity"},
- {Float.NEGATIVE_INFINITY, "%#- (9.8e", "(Infinity)"},
- {Float.NEGATIVE_INFINITY, "%#+0(8.4e", "(Infinity)"},
- {Float.NEGATIVE_INFINITY, "%-+(1.6e", "(Infinity)"},
- {Float.NEGATIVE_INFINITY, "% 0(12e", " (Infinity)"},
-
- {Float.NEGATIVE_INFINITY, "%e", "-Infinity"},
- {Float.NEGATIVE_INFINITY, "%#.0e", "-Infinity"},
- {Float.NEGATIVE_INFINITY, "%#- (9.8e", "(Infinity)"},
- {Float.NEGATIVE_INFINITY, "%#+0(8.4e", "(Infinity)"},
- {Float.NEGATIVE_INFINITY, "%-+(1.6e", "(Infinity)"},
- {Float.NEGATIVE_INFINITY, "% 0(12e", " (Infinity)"},
-
- {0d, "%e", "0.000000e+00"},
- {0d, "%#.0e", "0.e+00"},
- {0d, "%#- (9.8e", " 0.00000000e+00"},
- {0d, "%#+0(8.4e", "+0.0000e+00"},
- {0d, "%-+(1.6e", "+0.000000e+00"},
- {0d, "% 0(12e", " 0.000000e+00"},
-
- {1d, "%e", "1.000000e+00"},
- {1d, "%#.0e", "1.e+00"},
- {1d, "%#- (9.8e", " 1.00000000e+00"},
- {1d, "%#+0(8.4e", "+1.0000e+00"},
- {1d, "%-+(1.6e", "+1.000000e+00"},
- {1d, "% 0(12e", " 1.000000e+00"},
-
- {-1d, "%e", "-1.000000e+00"},
- {-1d, "%#.0e", "-1.e+00"},
- {-1d, "%#- (9.8e", "(1.00000000e+00)"},
- {-1d, "%#+0(8.4e", "(1.0000e+00)"},
- {-1d, "%-+(1.6e", "(1.000000e+00)"},
- {-1d, "% 0(12e", "(1.000000e+00)"},
-
-
- {.00000001d, "%e", "1.000000e-08"},
- {.00000001d, "%#.0e", "1.e-08"},
- {.00000001d, "%#- (9.8e", " 1.00000000e-08"},
- {.00000001d, "%#+0(8.4e", "+1.0000e-08"},
- {.00000001d, "%-+(1.6e", "+1.000000e-08"},
- {.00000001d, "% 0(12e", " 1.000000e-08"},
-
- {9122.10d, "%e", "9.122100e+03"},
- {9122.10d, "%#.0e", "9.e+03"},
- {9122.10d, "%#- (9.8e", " 9.12210000e+03"},
- {9122.10d, "%#+0(8.4e", "+9.1221e+03"},
- {9122.10d, "%-+(1.6e", "+9.122100e+03"},
- {9122.10d, "% 0(12e", " 9.122100e+03"},
-
- {0.1d, "%e", "1.000000e-01"},
- {0.1d, "%#.0e", "1.e-01"},
- {0.1d, "%#- (9.8e", " 1.00000000e-01"},
- {0.1d, "%#+0(8.4e", "+1.0000e-01"},
- {0.1d, "%-+(1.6e", "+1.000000e-01"},
- {0.1d, "% 0(12e", " 1.000000e-01"},
-
- {-2.d, "%e", "-2.000000e+00"},
- {-2.d, "%#.0e", "-2.e+00"},
- {-2.d, "%#- (9.8e", "(2.00000000e+00)"},
- {-2.d, "%#+0(8.4e", "(2.0000e+00)"},
- {-2.d, "%-+(1.6e", "(2.000000e+00)"},
- {-2.d, "% 0(12e", "(2.000000e+00)"},
-
- {-.39d, "%e", "-3.900000e-01"},
- {-.39d, "%#.0e", "-4.e-01"},
- {-.39d, "%#- (9.8e", "(3.90000000e-01)"},
- {-.39d, "%#+0(8.4e", "(3.9000e-01)"},
- {-.39d, "%-+(1.6e", "(3.900000e-01)"},
- {-.39d, "% 0(12e", "(3.900000e-01)"},
-
- {-1234567890.012345678d, "%e", "-1.234568e+09"},
- {-1234567890.012345678d, "%#.0e", "-1.e+09"},
- {-1234567890.012345678d, "%#- (9.8e", "(1.23456789e+09)"},
- {-1234567890.012345678d, "%#+0(8.4e", "(1.2346e+09)"},
- {-1234567890.012345678d, "%-+(1.6e", "(1.234568e+09)"},
- {-1234567890.012345678d, "% 0(12e", "(1.234568e+09)"},
-
- {Double.MAX_VALUE, "%e", "1.797693e+308"},
- {Double.MAX_VALUE, "%#.0e", "2.e+308"},
- {Double.MAX_VALUE, "%#- (9.8e", " 1.79769313e+308"},
- {Double.MAX_VALUE, "%#+0(8.4e", "+1.7977e+308"},
- {Double.MAX_VALUE, "%-+(1.6e", "+1.797693e+308"},
- {Double.MAX_VALUE, "% 0(12e", " 1.797693e+308"},
-
- {Double.MIN_VALUE, "%e", "4.900000e-324"},
- {Double.MIN_VALUE, "%#.0e", "5.e-324"},
- {Double.MIN_VALUE, "%#- (9.8e", " 4.90000000e-324"},
- {Double.MIN_VALUE, "%#+0(8.4e", "+4.9000e-324"},
- {Double.MIN_VALUE, "%-+(1.6e", "+4.900000e-324"},
- {Double.MIN_VALUE, "% 0(12e", " 4.900000e-324"},
-
- {Double.NaN, "%e", "NaN"},
- {Double.NaN, "%#.0e", "NaN"},
- {Double.NaN, "%#- (9.8e", "NaN "},
- {Double.NaN, "%#+0(8.4e", " NaN"},
- {Double.NaN, "%-+(1.6e", "NaN"},
- {Double.NaN, "% 0(12e", " NaN"},
-
- {Double.NEGATIVE_INFINITY, "%e", "-Infinity"},
- {Double.NEGATIVE_INFINITY, "%#.0e", "-Infinity"},
- {Double.NEGATIVE_INFINITY, "%#- (9.8e", "(Infinity)"},
- {Double.NEGATIVE_INFINITY, "%#+0(8.4e", "(Infinity)"},
- {Double.NEGATIVE_INFINITY, "%-+(1.6e", "(Infinity)"},
- {Double.NEGATIVE_INFINITY, "% 0(12e", " (Infinity)"},
-
- {Double.POSITIVE_INFINITY, "%e", "Infinity"},
- {Double.POSITIVE_INFINITY, "%#.0e", "Infinity"},
- {Double.POSITIVE_INFINITY, "%#- (9.8e", " Infinity"},
- {Double.POSITIVE_INFINITY, "%#+0(8.4e", "+Infinity"},
- {Double.POSITIVE_INFINITY, "%-+(1.6e", "+Infinity"},
- {Double.POSITIVE_INFINITY, "% 0(12e", " Infinity"},
- };
- final int input = 0;
- final int pattern = 1;
- final int output = 2;
- for (int i = 0; i < tripleE.length; i++) {
- f = new Formatter(Locale.US);
- f.format((String)tripleE[i][pattern], tripleE[i][input]);
- assertEquals("triple[" + i + "]:" + tripleE[i][input] + ",pattern["
- + i + "]:" + tripleE[i][pattern],
- tripleE[i][output], f.toString());
-
- // test for conversion type 'E'
- f = new Formatter(Locale.US);
- f.format(((String)tripleE[i][pattern]).toUpperCase(), tripleE[i][input]);
- assertEquals("triple[" + i + "]:" + tripleE[i][input] + ",pattern["
- + i + "]:" + tripleE[i][pattern], ((String)tripleE[i][output])
- .toUpperCase(Locale.UK), f.toString());
- }
-
- f = new Formatter(Locale.GERMAN);
- f.format("%e", 1001f);
- /*
- * fail on RI, spec says 'e' requires the output to be formatted in
- * general scientific notation and the localization algorithm is
- * applied. But RI format this case to 1.001000e+03, which does not
- * conform to the German Locale
- */
- assertEquals("1,001000e+03", f.toString());
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for Float/Double
- * conversion type 'g' and 'G'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify exceptions.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- @KnownFailure("Formatting of Double.MIN_VALUE works improperly")
- @AndroidOnly("last case fails on RI. See comment below")
- public void test_formatLjava_lang_String$Ljava_lang_Object_FloatConversionG() {
- Formatter f = null;
- final Object[][] tripleG = {
- {1001f, "%g", "1001.00"},
- {1001f, "%- (,9.8g", " 1,001.0000"},
- {1001f, "%+0(,8.4g", "+001,001"},
- {1001f, "%-+(,1.6g", "+1,001.00"},
- {1001f, "% 0(,12.0g", " 0000001e+03"},
-
- {1.f, "%g", "1.00000"},
- {1.f, "%- (,9.8g", " 1.0000000"},
- {1.f, "%+0(,8.4g", "+001.000"},
- {1.f, "%-+(,1.6g", "+1.00000"},
- {1.f, "% 0(,12.0g", " 00000000001"},
-
- {-98f, "%g", "-98.0000"},
- {-98f, "%- (,9.8g", "(98.000000)"},
- {-98f, "%+0(,8.4g", "(098.00)"},
- {-98f, "%-+(,1.6g", "(98.0000)"},
- {-98f, "% 0(,12.0g", "(000001e+02)"},
-
- {0.000001f, "%g", "1.00000e-06"},
- {0.000001f, "%- (,9.8g", " 1.0000000e-06"},
- {0.000001f, "%+0(,8.4g", "+1.000e-06"},
- {0.000001f, "%-+(,1.6g", "+1.00000e-06"},
- {0.000001f, "% 0(,12.0g", " 0000001e-06"},
-
- {345.1234567f, "%g", "345.123"},
- {345.1234567f, "%- (,9.8g", " 345.12344"},
- {345.1234567f, "%+0(,8.4g", "+00345.1"},
- {345.1234567f, "%-+(,1.6g", "+345.123"},
- {345.1234567f, "% 0(,12.0g", " 0000003e+02"},
-
- {-.00000012345f, "%g", "-1.23450e-07"},
- {-.00000012345f, "%- (,9.8g", "(1.2344999e-07)"},
- {-.00000012345f, "%+0(,8.4g", "(1.234e-07)"},
- {-.00000012345f, "%-+(,1.6g", "(1.23450e-07)"},
- {-.00000012345f, "% 0(,12.0g", "(000001e-07)"},
-
- {-987.1234567f, "%g", "-987.123"},
- {-987.1234567f, "%- (,9.8g", "(987.12347)"},
- {-987.1234567f, "%+0(,8.4g", "(0987.1)"},
- {-987.1234567f, "%-+(,1.6g", "(987.123)"},
- {-987.1234567f, "% 0(,12.0g", "(000001e+03)"},
-
- {Float.MAX_VALUE, "%g", "3.40282e+38"},
- {Float.MAX_VALUE, "%- (,9.8g", " 3.4028235e+38"},
- {Float.MAX_VALUE, "%+0(,8.4g", "+3.403e+38"},
- {Float.MAX_VALUE, "%-+(,1.6g", "+3.40282e+38"},
- {Float.MAX_VALUE, "% 0(,12.0g", " 0000003e+38"},
-
- {Float.MIN_VALUE, "%g", "1.40130e-45"},
- {Float.MIN_VALUE, "%- (,9.8g", " 1.4012985e-45"},
- {Float.MIN_VALUE, "%+0(,8.4g", "+1.401e-45"},
- {Float.MIN_VALUE, "%-+(,1.6g", "+1.40130e-45"},
- {Float.MIN_VALUE, "% 0(,12.0g", " 0000001e-45"},
-
- {Float.NaN, "%g", "NaN"},
- {Float.NaN, "%- (,9.8g", "NaN "},
- {Float.NaN, "%+0(,8.4g", " NaN"},
- {Float.NaN, "%-+(,1.6g", "NaN"},
- {Float.NaN, "% 0(,12.0g", " NaN"},
-
- {Float.NEGATIVE_INFINITY, "%g", "-Infinity"},
- {Float.NEGATIVE_INFINITY, "%- (,9.8g", "(Infinity)"},
- {Float.NEGATIVE_INFINITY, "%+0(,8.4g", "(Infinity)"},
- {Float.NEGATIVE_INFINITY, "%-+(,1.6g", "(Infinity)"},
- {Float.NEGATIVE_INFINITY, "% 0(,12.0g", " (Infinity)"},
-
- {Float.POSITIVE_INFINITY, "%g", "Infinity"},
- {Float.POSITIVE_INFINITY, "%- (,9.8g", " Infinity"},
- {Float.POSITIVE_INFINITY, "%+0(,8.4g", "+Infinity"},
- {Float.POSITIVE_INFINITY, "%-+(,1.6g", "+Infinity"},
- {Float.POSITIVE_INFINITY, "% 0(,12.0g", " Infinity"},
-
- {1d, "%g", "1.00000"},
- {1d, "%- (,9.8g", " 1.0000000"},
- {1d, "%+0(,8.4g", "+001.000"},
- {1d, "%-+(,1.6g", "+1.00000"},
- {1d, "% 0(,12.0g", " 00000000001"},
-
- {-1d, "%g", "-1.00000"},
- {-1d, "%- (,9.8g", "(1.0000000)"},
- {-1d, "%+0(,8.4g", "(01.000)"},
- {-1d, "%-+(,1.6g", "(1.00000)"},
- {-1d, "% 0(,12.0g", "(0000000001)"},
-
- {.00000001d, "%g", "1.00000e-08"},
- {.00000001d, "%- (,9.8g", " 1.0000000e-08"},
- {.00000001d, "%+0(,8.4g", "+1.000e-08"},
- {.00000001d, "%-+(,1.6g", "+1.00000e-08"},
- {.00000001d, "% 0(,12.0g", " 0000001e-08"},
-
- {1912.10d, "%g", "1912.10"},
- {1912.10d, "%- (,9.8g", " 1,912.1000"},
- {1912.10d, "%+0(,8.4g", "+001,912"},
- {1912.10d, "%-+(,1.6g", "+1,912.10"},
- {1912.10d, "% 0(,12.0g", " 0000002e+03"},
-
- {0.1d, "%g", "0.100000"},
- {0.1d, "%- (,9.8g", " 0.10000000"},
- {0.1d, "%+0(,8.4g", "+00.1000"},
- {0.1d, "%-+(,1.6g", "+0.100000"},
- {0.1d, "% 0(,12.0g", " 000000000.1"},
-
- {-2.d, "%g", "-2.00000"},
- {-2.d, "%- (,9.8g", "(2.0000000)"},
- {-2.d, "%+0(,8.4g", "(02.000)"},
- {-2.d, "%-+(,1.6g", "(2.00000)"},
- {-2.d, "% 0(,12.0g", "(0000000002)"},
-
- {-.00039d, "%g", "-0.000390000"},
- {-.00039d, "%- (,9.8g", "(0.00039000000)"},
- {-.00039d, "%+0(,8.4g", "(0.0003900)"},
- {-.00039d, "%-+(,1.6g", "(0.000390000)"},
- {-.00039d, "% 0(,12.0g", "(00000.0004)"},
-
- {-1234567890.012345678d, "%g", "-1.23457e+09"},
- {-1234567890.012345678d, "%- (,9.8g", "(1.2345679e+09)"},
- {-1234567890.012345678d, "%+0(,8.4g", "(1.235e+09)"},
- {-1234567890.012345678d, "%-+(,1.6g", "(1.23457e+09)"},
- {-1234567890.012345678d, "% 0(,12.0g", "(000001e+09)"},
-
- {Double.MAX_VALUE, "%g", "1.79769e+308"},
- {Double.MAX_VALUE, "%- (,9.8g", " 1.7976931e+308"},
- {Double.MAX_VALUE, "%+0(,8.4g", "+1.798e+308"},
- {Double.MAX_VALUE, "%-+(,1.6g", "+1.79769e+308"},
- {Double.MAX_VALUE, "% 0(,12.0g", " 000002e+308"},
-
- {Double.MIN_VALUE, "%g", "4.90000e-324"},
- {Double.MIN_VALUE, "%- (,9.8g", " 4.9000000e-324"},
- {Double.MIN_VALUE, "%+0(,8.4g", "+4.900e-324"},
- {Double.MIN_VALUE, "%-+(,1.6g", "+4.90000e-324"},
- {Double.MIN_VALUE, "% 0(,12.0g", " 000005e-324"},
-
- {Double.NaN, "%g", "NaN"},
- {Double.NaN, "%- (,9.8g", "NaN "},
- {Double.NaN, "%+0(,8.4g", " NaN"},
- {Double.NaN, "%-+(,1.6g", "NaN"},
- {Double.NaN, "% 0(,12.0g", " NaN"},
-
- {Double.NEGATIVE_INFINITY, "%g", "-Infinity"},
- {Double.NEGATIVE_INFINITY, "%- (,9.8g", "(Infinity)"},
- {Double.NEGATIVE_INFINITY, "%+0(,8.4g", "(Infinity)"},
- {Double.NEGATIVE_INFINITY, "%-+(,1.6g", "(Infinity)"},
- {Double.NEGATIVE_INFINITY, "% 0(,12.0g", " (Infinity)"},
-
- {Double.POSITIVE_INFINITY, "%g", "Infinity"},
- {Double.POSITIVE_INFINITY, "%- (,9.8g", " Infinity"},
- {Double.POSITIVE_INFINITY, "%+0(,8.4g", "+Infinity"},
- {Double.POSITIVE_INFINITY, "%-+(,1.6g", "+Infinity"},
- {Double.POSITIVE_INFINITY, "% 0(,12.0g", " Infinity"},
-
- };
- final int input = 0;
- final int pattern = 1;
- final int output = 2;
- for (int i = 0; i < tripleG.length; i++) {
-
- f = new Formatter(Locale.US);
- f.format((String)tripleG[i][pattern], tripleG[i][input]);
- assertEquals("triple[" + i + "]:" + tripleG[i][input] + ",pattern["
- + i + "]:" + tripleG[i][pattern],
- tripleG[i][output], f.toString());
-
- // test for conversion type 'G'
- f = new Formatter(Locale.US);
- f.format(((String)tripleG[i][pattern]).toUpperCase(), tripleG[i][input]);
- assertEquals("triple[" + i + "]:" + tripleG[i][input] + ",pattern["
- + i + "]:" + tripleG[i][pattern], ((String)tripleG[i][output])
- .toUpperCase(Locale.UK), f.toString());
- }
-
- f = new Formatter(Locale.US);
- f.format("%.5g", 0f);
- assertEquals("0.0000", f.toString());
-
- f = new Formatter(Locale.US);
- f.format("%.0g", 0f);
- /*
- * fail on RI, spec says if the precision is 0, then it is taken to be
- * 1. but RI throws ArrayIndexOutOfBoundsException.
- */
- assertEquals("0", f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format("%g", 1001f);
- /*
- * fail on RI, spec says 'g' requires the output to be formatted in
- * general scientific notation and the localization algorithm is
- * applied. But RI format this case to 1001.00, which does not conform
- * to the German Locale
- */
- assertEquals("1001,00", f.toString());
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for Float/Double
- * conversion type 'g' and 'G' overflow
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify exceptions.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_FloatConversionG_Overflow() {
- Formatter f = new Formatter();
- f.format("%g", 999999.5);
- assertEquals("1.00000e+06", f.toString());
-
- f = new Formatter();
- f.format("%g", 99999.5);
- assertEquals("99999.5", f.toString());
-
- f = new Formatter();
- f.format("%.4g", 99.95);
- assertEquals("99.95", f.toString());
-
- f = new Formatter();
- f.format("%g", 99.95);
- assertEquals("99.9500", f.toString());
-
- f = new Formatter();
- f.format("%g", 0.9);
- assertEquals("0.900000", f.toString());
-
- f = new Formatter();
- f.format("%.0g", 0.000095);
- assertEquals("0.0001", f.toString());
-
- f = new Formatter();
- f.format("%g", 0.0999999);
- assertEquals("0.0999999", f.toString());
-
- f = new Formatter();
- f.format("%g", 0.00009);
- assertEquals("9.00000e-05", f.toString());
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for Float/Double
- * conversion type 'f'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify exceptions.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- @KnownFailure("Formatting of Float.MAX_VALUE works improperly")
- public void test_formatLjava_lang_String$Ljava_lang_Object_FloatConversionF() {
- Formatter f = null;
-
- final Object[][] tripleF = {
- {0f, "%f", "0,000000"},
- {0f, "%#.3f", "0,000"},
- {0f, "%,5f", "0,000000"},
- {0f, "%- (12.0f", " 0 "},
- {0f, "%#+0(1.6f", "+0,000000"},
- {0f, "%-+(8.4f", "+0,0000 "},
- {0f, "% 0#(9.8f", " 0,00000000"},
-
- {1234f, "%f", "1234,000000"},
- {1234f, "%#.3f", "1234,000"},
- {1234f, "%,5f", "1.234,000000"},
- {1234f, "%- (12.0f", " 1234 "},
- {1234f, "%#+0(1.6f", "+1234,000000"},
- {1234f, "%-+(8.4f", "+1234,0000"},
- {1234f, "% 0#(9.8f", " 1234,00000000"},
-
- {1.f, "%f", "1,000000"},
- {1.f, "%#.3f", "1,000"},
- {1.f, "%,5f", "1,000000"},
- {1.f, "%- (12.0f", " 1 "},
- {1.f, "%#+0(1.6f", "+1,000000"},
- {1.f, "%-+(8.4f", "+1,0000 "},
- {1.f, "% 0#(9.8f", " 1,00000000"},
-
- {-98f, "%f", "-98,000000"},
- {-98f, "%#.3f", "-98,000"},
- {-98f, "%,5f", "-98,000000"},
- {-98f, "%- (12.0f", "(98) "},
- {-98f, "%#+0(1.6f", "(98,000000)"},
- {-98f, "%-+(8.4f", "(98,0000)"},
- {-98f, "% 0#(9.8f", "(98,00000000)"},
-
- {0.000001f, "%f", "0,000001"},
- {0.000001f, "%#.3f", "0,000"},
- {0.000001f, "%,5f", "0,000001"},
- {0.000001f, "%- (12.0f", " 0 "},
- {0.000001f, "%#+0(1.6f", "+0,000001"},
- {0.000001f, "%-+(8.4f", "+0,0000 "},
- {0.000001f, "% 0#(9.8f", " 0,00000100"},
-
- {345.1234567f, "%f", "345,123444"},
- {345.1234567f, "%#.3f", "345,123"},
- {345.1234567f, "%,5f", "345,123444"},
- {345.1234567f, "%- (12.0f", " 345 "},
- {345.1234567f, "%#+0(1.6f", "+345,123444"},
- {345.1234567f, "%-+(8.4f", "+345,1234"},
- {345.1234567f, "% 0#(9.8f", " 345,12344360"},
-
- {-.00000012345f, "%f", "-0,000000"},
- {-.00000012345f, "%#.3f", "-0,000"},
- {-.00000012345f, "%,5f", "-0,000000"},
- {-.00000012345f, "%- (12.0f", "(0) "},
- {-.00000012345f, "%#+0(1.6f", "(0,000000)"},
- {-.00000012345f, "%-+(8.4f", "(0,0000)"},
- {-.00000012345f, "% 0#(9.8f", "(0,00000012)"},
-
- {-987654321.1234567f, "%f", "-987654336,000000"},
- {-987654321.1234567f, "%#.3f", "-987654336,000"},
- {-987654321.1234567f, "%,5f", "-987.654.336,000000"},
- {-987654321.1234567f, "%- (12.0f", "(987654336) "},
- {-987654321.1234567f, "%#+0(1.6f", "(987654336,000000)"},
- {-987654321.1234567f, "%-+(8.4f", "(987654336,0000)"},
- {-987654321.1234567f, "% 0#(9.8f", "(987654336,00000000)"},
-
- {Float.MAX_VALUE, "%f", "340282346638528860000000000000000000000,000000"},
- {Float.MAX_VALUE, "%#.3f", "340282346638528860000000000000000000000,000"},
- {Float.MAX_VALUE, "%,5f", "340.282.346.638.528.860.000.000.000.000.000.000.000,000000"},
- {Float.MAX_VALUE, "%- (12.0f", " 340282346638528860000000000000000000000"},
- {Float.MAX_VALUE, "%#+0(1.6f", "+340282346638528860000000000000000000000,000000"},
- {Float.MAX_VALUE, "%-+(8.4f", "+340282346638528860000000000000000000000,0000"},
- {Float.MAX_VALUE, "% 0#(9.8f", " 340282346638528860000000000000000000000,00000000"},
-
- {Float.MIN_VALUE, "%f", "0,000000"},
- {Float.MIN_VALUE, "%#.3f", "0,000"},
- {Float.MIN_VALUE, "%,5f", "0,000000"},
- {Float.MIN_VALUE, "%- (12.0f", " 0 "},
- {Float.MIN_VALUE, "%#+0(1.6f", "+0,000000"},
- {Float.MIN_VALUE, "%-+(8.4f", "+0,0000 "},
- {Float.MIN_VALUE, "% 0#(9.8f", " 0,00000000"},
-
- {Float.NaN, "%f", "NaN"},
- {Float.NaN, "%#.3f", "NaN"},
- {Float.NaN, "%,5f", " NaN"},
- {Float.NaN, "%- (12.0f", "NaN "},
- {Float.NaN, "%#+0(1.6f", "NaN"},
- {Float.NaN, "%-+(8.4f", "NaN "},
- {Float.NaN, "% 0#(9.8f", " NaN"},
-
- {Float.NEGATIVE_INFINITY, "%f", "-Infinity"},
- {Float.NEGATIVE_INFINITY, "%#.3f", "-Infinity"},
- {Float.NEGATIVE_INFINITY, "%,5f", "-Infinity"},
- {Float.NEGATIVE_INFINITY, "%- (12.0f", "(Infinity) "},
- {Float.NEGATIVE_INFINITY, "%#+0(1.6f", "(Infinity)"},
- {Float.NEGATIVE_INFINITY, "%-+(8.4f", "(Infinity)"},
- {Float.NEGATIVE_INFINITY, "% 0#(9.8f", "(Infinity)"},
-
- {Float.POSITIVE_INFINITY, "%f", "Infinity"},
- {Float.POSITIVE_INFINITY, "%#.3f", "Infinity"},
- {Float.POSITIVE_INFINITY, "%,5f", "Infinity"},
- {Float.POSITIVE_INFINITY, "%- (12.0f", " Infinity "},
- {Float.POSITIVE_INFINITY, "%#+0(1.6f", "+Infinity"},
- {Float.POSITIVE_INFINITY, "%-+(8.4f", "+Infinity"},
- {Float.POSITIVE_INFINITY, "% 0#(9.8f", " Infinity"},
-
-
- {0d, "%f", "0,000000"},
- {0d, "%#.3f", "0,000"},
- {0d, "%,5f", "0,000000"},
- {0d, "%- (12.0f", " 0 "},
- {0d, "%#+0(1.6f", "+0,000000"},
- {0d, "%-+(8.4f", "+0,0000 "},
- {0d, "% 0#(9.8f", " 0,00000000"},
-
- {1d, "%f", "1,000000"},
- {1d, "%#.3f", "1,000"},
- {1d, "%,5f", "1,000000"},
- {1d, "%- (12.0f", " 1 "},
- {1d, "%#+0(1.6f", "+1,000000"},
- {1d, "%-+(8.4f", "+1,0000 "},
- {1d, "% 0#(9.8f", " 1,00000000"},
-
- {-1d, "%f", "-1,000000"},
- {-1d, "%#.3f", "-1,000"},
- {-1d, "%,5f", "-1,000000"},
- {-1d, "%- (12.0f", "(1) "},
- {-1d, "%#+0(1.6f", "(1,000000)"},
- {-1d, "%-+(8.4f", "(1,0000)"},
- {-1d, "% 0#(9.8f", "(1,00000000)"},
-
- {.00000001d, "%f", "0,000000"},
- {.00000001d, "%#.3f", "0,000"},
- {.00000001d, "%,5f", "0,000000"},
- {.00000001d, "%- (12.0f", " 0 "},
- {.00000001d, "%#+0(1.6f", "+0,000000"},
- {.00000001d, "%-+(8.4f", "+0,0000 "},
- {.00000001d, "% 0#(9.8f", " 0,00000001"},
-
- {1000.10d, "%f", "1000,100000"},
- {1000.10d, "%#.3f", "1000,100"},
- {1000.10d, "%,5f", "1.000,100000"},
- {1000.10d, "%- (12.0f", " 1000 "},
- {1000.10d, "%#+0(1.6f", "+1000,100000"},
- {1000.10d, "%-+(8.4f", "+1000,1000"},
- {1000.10d, "% 0#(9.8f", " 1000,10000000"},
-
- {0.1d, "%f", "0,100000"},
- {0.1d, "%#.3f", "0,100"},
- {0.1d, "%,5f", "0,100000"},
- {0.1d, "%- (12.0f", " 0 "},
- {0.1d, "%#+0(1.6f", "+0,100000"},
- {0.1d, "%-+(8.4f", "+0,1000 "},
- {0.1d, "% 0#(9.8f", " 0,10000000"},
-
- {-2.d, "%f", "-2,000000"},
- {-2.d, "%#.3f", "-2,000"},
- {-2.d, "%,5f", "-2,000000"},
- {-2.d, "%- (12.0f", "(2) "},
- {-2.d, "%#+0(1.6f", "(2,000000)"},
- {-2.d, "%-+(8.4f", "(2,0000)"},
- {-2.d, "% 0#(9.8f", "(2,00000000)"},
-
- {-.00009d, "%f", "-0,000090"},
- {-.00009d, "%#.3f", "-0,000"},
- {-.00009d, "%,5f", "-0,000090"},
- {-.00009d, "%- (12.0f", "(0) "},
- {-.00009d, "%#+0(1.6f", "(0,000090)"},
- {-.00009d, "%-+(8.4f", "(0,0001)"},
- {-.00009d, "% 0#(9.8f", "(0,00009000)"},
-
- {-1234567890.012345678d, "%f", "-1234567890,012346"},
- {-1234567890.012345678d, "%#.3f", "-1234567890,012"},
- {-1234567890.012345678d, "%,5f", "-1.234.567.890,012346"},
- {-1234567890.012345678d, "%- (12.0f", "(1234567890)"},
- {-1234567890.012345678d, "%#+0(1.6f", "(1234567890,012346)"},
- {-1234567890.012345678d, "%-+(8.4f", "(1234567890,0123)"},
- {-1234567890.012345678d, "% 0#(9.8f", "(1234567890,01234580)"},
-
- {Double.MAX_VALUE, "%f", "179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,000000"},
- {Double.MAX_VALUE, "%#.3f", "179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,000"},
- {Double.MAX_VALUE, "%,5f", "179.769.313.486.231.570.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000.000,000000"},
- {Double.MAX_VALUE, "%- (12.0f", " 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"},
- {Double.MAX_VALUE, "%#+0(1.6f", "+179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,000000"},
- {Double.MAX_VALUE, "%-+(8.4f", "+179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,0000"},
- {Double.MAX_VALUE, "% 0#(9.8f", " 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,00000000"},
-
- {Double.MIN_VALUE, "%f", "0,000000"},
- {Double.MIN_VALUE, "%#.3f", "0,000"},
- {Double.MIN_VALUE, "%,5f", "0,000000"},
- {Double.MIN_VALUE, "%- (12.0f", " 0 "},
- {Double.MIN_VALUE, "%#+0(1.6f", "+0,000000"},
- {Double.MIN_VALUE, "%-+(8.4f", "+0,0000 "},
- {Double.MIN_VALUE, "% 0#(9.8f", " 0,00000000"},
-
- {Double.NaN, "%f", "NaN"},
- {Double.NaN, "%#.3f", "NaN"},
- {Double.NaN, "%,5f", " NaN"},
- {Double.NaN, "%- (12.0f", "NaN "},
- {Double.NaN, "%#+0(1.6f", "NaN"},
- {Double.NaN, "%-+(8.4f", "NaN "},
- {Double.NaN, "% 0#(9.8f", " NaN"},
-
- {Double.POSITIVE_INFINITY, "%f", "Infinity"},
- {Double.POSITIVE_INFINITY, "%#.3f", "Infinity"},
- {Double.POSITIVE_INFINITY, "%,5f", "Infinity"},
- {Double.POSITIVE_INFINITY, "%- (12.0f", " Infinity "},
- {Double.POSITIVE_INFINITY, "%#+0(1.6f", "+Infinity"},
- {Double.POSITIVE_INFINITY, "%-+(8.4f", "+Infinity"},
- {Double.POSITIVE_INFINITY, "% 0#(9.8f", " Infinity"},
-
- {Double.NEGATIVE_INFINITY, "%f", "-Infinity"},
- {Double.NEGATIVE_INFINITY, "%#.3f", "-Infinity"},
- {Double.NEGATIVE_INFINITY, "%,5f", "-Infinity"},
- {Double.NEGATIVE_INFINITY, "%- (12.0f", "(Infinity) "},
- {Double.NEGATIVE_INFINITY, "%#+0(1.6f", "(Infinity)"},
- {Double.NEGATIVE_INFINITY, "%-+(8.4f", "(Infinity)"},
- {Double.NEGATIVE_INFINITY, "% 0#(9.8f", "(Infinity)"},
- };
- final int input = 0;
- final int pattern = 1;
- final int output = 2;
- for (int i = 0; i < tripleF.length; i++) {
- f = new Formatter(Locale.GERMAN);
- f.format((String)tripleF[i][pattern], tripleF[i][input]);
- assertEquals("triple[" + i + "]:" + tripleF[i][input] + ",pattern["
- + i + "]:" + tripleF[i][pattern],
- tripleF[i][output], f.toString());
- }
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for Float/Double
- * conversion type 'a' and 'A'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify exceptions.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_FloatConversionA() {
- Formatter f = null;
- final Object[][] tripleA = {
- {-0f, "%a", "-0x0.0p0"},
- {-0f, "%#.3a", "-0x0.000p0"},
- {-0f, "%5a", "-0x0.0p0"},
- {-0f, "%- 12.0a", "-0x0.0p0 "},
- {-0f, "%#+01.6a", "-0x0.000000p0"},
- {-0f, "%-+8.4a", "-0x0.0000p0"},
-
- {0f, "%a", "0x0.0p0"},
- {0f, "%#.3a", "0x0.000p0"},
- {0f, "%5a", "0x0.0p0"},
- {0f, "%- 12.0a", " 0x0.0p0 "},
- {0f, "%#+01.6a", "+0x0.000000p0"},
- {0f, "%-+8.4a", "+0x0.0000p0"},
-
- {1234f, "%a", "0x1.348p10"},
- {1234f, "%#.3a", "0x1.348p10"},
- {1234f, "%5a", "0x1.348p10"},
- {1234f, "%- 12.0a", " 0x1.3p10 "},
- {1234f, "%#+01.6a", "+0x1.348000p10"},
- {1234f, "%-+8.4a", "+0x1.3480p10"},
-
- {1.f, "%a", "0x1.0p0"},
- {1.f, "%#.3a", "0x1.000p0"},
- {1.f, "%5a", "0x1.0p0"},
- {1.f, "%- 12.0a", " 0x1.0p0 "},
- {1.f, "%#+01.6a", "+0x1.000000p0"},
- {1.f, "%-+8.4a", "+0x1.0000p0"},
-
- {-98f, "%a", "-0x1.88p6"},
- {-98f, "%#.3a", "-0x1.880p6"},
- {-98f, "%5a", "-0x1.88p6"},
- {-98f, "%- 12.0a", "-0x1.8p6 "},
- {-98f, "%#+01.6a", "-0x1.880000p6"},
- {-98f, "%-+8.4a", "-0x1.8800p6"},
-
- {345.1234567f, "%a", "0x1.591f9ap8"},
- {345.1234567f, "%5a", "0x1.591f9ap8"},
- {345.1234567f, "%#+01.6a", "+0x1.591f9ap8"},
-
- {-987654321.1234567f, "%a", "-0x1.d6f346p29"},
- {-987654321.1234567f, "%#.3a", "-0x1.d6fp29"},
- {-987654321.1234567f, "%5a", "-0x1.d6f346p29"},
- {-987654321.1234567f, "%- 12.0a", "-0x1.dp29 "},
- {-987654321.1234567f, "%#+01.6a", "-0x1.d6f346p29"},
- {-987654321.1234567f, "%-+8.4a", "-0x1.d6f3p29"},
-
- {Float.MAX_VALUE, "%a", "0x1.fffffep127"},
- {Float.MAX_VALUE, "%5a", "0x1.fffffep127"},
- {Float.MAX_VALUE, "%#+01.6a", "+0x1.fffffep127"},
-
- {Float.NaN, "%a", "NaN"},
- {Float.NaN, "%#.3a", "NaN"},
- {Float.NaN, "%5a", " NaN"},
- {Float.NaN, "%- 12.0a", "NaN "},
- {Float.NaN, "%#+01.6a", "NaN"},
- {Float.NaN, "%-+8.4a", "NaN "},
-
- {Float.NEGATIVE_INFINITY, "%a", "-Infinity"},
- {Float.NEGATIVE_INFINITY, "%#.3a", "-Infinity"},
- {Float.NEGATIVE_INFINITY, "%5a", "-Infinity"},
- {Float.NEGATIVE_INFINITY, "%- 12.0a", "-Infinity "},
- {Float.NEGATIVE_INFINITY, "%#+01.6a", "-Infinity"},
- {Float.NEGATIVE_INFINITY, "%-+8.4a", "-Infinity"},
-
- {Float.POSITIVE_INFINITY, "%a", "Infinity"},
- {Float.POSITIVE_INFINITY, "%#.3a", "Infinity"},
- {Float.POSITIVE_INFINITY, "%5a", "Infinity"},
- {Float.POSITIVE_INFINITY, "%- 12.0a", " Infinity "},
- {Float.POSITIVE_INFINITY, "%#+01.6a", "+Infinity"},
- {Float.POSITIVE_INFINITY, "%-+8.4a", "+Infinity"},
-
- {-0d, "%a", "-0x0.0p0"},
- {-0d, "%#.3a", "-0x0.000p0"},
- {-0d, "%5a", "-0x0.0p0"},
- {-0d, "%- 12.0a", "-0x0.0p0 "},
- {-0d, "%#+01.6a", "-0x0.000000p0"},
- {-0d, "%-+8.4a", "-0x0.0000p0"},
-
- {0d, "%a", "0x0.0p0"},
- {0d, "%#.3a", "0x0.000p0"},
- {0d, "%5a", "0x0.0p0"},
- {0d, "%- 12.0a", " 0x0.0p0 "},
- {0d, "%#+01.6a", "+0x0.000000p0"},
- {0d, "%-+8.4a", "+0x0.0000p0"},
-
- {1d, "%a", "0x1.0p0"},
- {1d, "%#.3a", "0x1.000p0"},
- {1d, "%5a", "0x1.0p0"},
- {1d, "%- 12.0a", " 0x1.0p0 "},
- {1d, "%#+01.6a", "+0x1.000000p0"},
- {1d, "%-+8.4a", "+0x1.0000p0"},
-
- {-1d, "%a", "-0x1.0p0"},
- {-1d, "%#.3a", "-0x1.000p0"},
- {-1d, "%5a", "-0x1.0p0"},
- {-1d, "%- 12.0a", "-0x1.0p0 "},
- {-1d, "%#+01.6a", "-0x1.000000p0"},
- {-1d, "%-+8.4a", "-0x1.0000p0"},
-
- {.00000001d, "%a", "0x1.5798ee2308c3ap-27"},
- {.00000001d, "%5a", "0x1.5798ee2308c3ap-27"},
- {.00000001d, "%- 12.0a", " 0x1.5p-27 "},
- {.00000001d, "%#+01.6a", "+0x1.5798eep-27"},
-
- {1000.10d, "%a", "0x1.f40cccccccccdp9"},
- {1000.10d, "%5a", "0x1.f40cccccccccdp9"},
- {1000.10d, "%- 12.0a", " 0x1.fp9 "},
-
- {0.1d, "%a", "0x1.999999999999ap-4"},
- {0.1d, "%5a", "0x1.999999999999ap-4"},
-
- {-2.d, "%a", "-0x1.0p1"},
- {-2.d, "%#.3a", "-0x1.000p1"},
- {-2.d, "%5a", "-0x1.0p1"},
- {-2.d, "%- 12.0a", "-0x1.0p1 "},
- {-2.d, "%#+01.6a", "-0x1.000000p1"},
- {-2.d, "%-+8.4a", "-0x1.0000p1"},
-
- {-.00009d, "%a", "-0x1.797cc39ffd60fp-14"},
- {-.00009d, "%5a", "-0x1.797cc39ffd60fp-14"},
-
- {-1234567890.012345678d, "%a", "-0x1.26580b480ca46p30"},
- {-1234567890.012345678d, "%5a", "-0x1.26580b480ca46p30"},
- {-1234567890.012345678d, "%- 12.0a", "-0x1.2p30 "},
- {-1234567890.012345678d, "%#+01.6a", "-0x1.26580bp30"},
- {-1234567890.012345678d, "%-+8.4a", "-0x1.2658p30"},
-
- {Double.MAX_VALUE, "%a", "0x1.fffffffffffffp1023"},
- {Double.MAX_VALUE, "%5a", "0x1.fffffffffffffp1023"},
-
- {Double.MIN_VALUE, "%a", "0x0.0000000000001p-1022"},
- {Double.MIN_VALUE, "%5a", "0x0.0000000000001p-1022"},
-
- {Double.NaN, "%a", "NaN"},
- {Double.NaN, "%#.3a", "NaN"},
- {Double.NaN, "%5a", " NaN"},
- {Double.NaN, "%- 12.0a", "NaN "},
- {Double.NaN, "%#+01.6a", "NaN"},
- {Double.NaN, "%-+8.4a", "NaN "},
-
- {Double.NEGATIVE_INFINITY, "%a", "-Infinity"},
- {Double.NEGATIVE_INFINITY, "%#.3a", "-Infinity"},
- {Double.NEGATIVE_INFINITY, "%5a", "-Infinity"},
- {Double.NEGATIVE_INFINITY, "%- 12.0a", "-Infinity "},
- {Double.NEGATIVE_INFINITY, "%#+01.6a", "-Infinity"},
- {Double.NEGATIVE_INFINITY, "%-+8.4a", "-Infinity"},
-
- {Double.POSITIVE_INFINITY, "%a", "Infinity"},
- {Double.POSITIVE_INFINITY, "%#.3a", "Infinity"},
- {Double.POSITIVE_INFINITY, "%5a", "Infinity"},
- {Double.POSITIVE_INFINITY, "%- 12.0a", " Infinity "},
- {Double.POSITIVE_INFINITY, "%#+01.6a", "+Infinity"},
- {Double.POSITIVE_INFINITY, "%-+8.4a", "+Infinity"},
-
- };
- final int input = 0;
- final int pattern = 1;
- final int output = 2;
- for (int i = 0; i < tripleA.length; i++) {
- f = new Formatter(Locale.UK);
- f.format((String)tripleA[i][pattern], tripleA[i][input]);
- assertEquals("triple[" + i + "]:" + tripleA[i][input] + ",pattern["
- + i + "]:" + tripleA[i][pattern],
- tripleA[i][output], f.toString());
-
- // test for conversion type 'A'
- f = new Formatter(Locale.UK);
- f.format(((String)tripleA[i][pattern]).toUpperCase(), tripleA[i][input]);
- assertEquals("triple[" + i + "]:" + tripleA[i][input] + ",pattern["
- + i + "]:" + tripleA[i][pattern], ((String)tripleA[i][output])
- .toUpperCase(Locale.UK), f.toString());
- }
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for BigDecimal
- * conversion type 'e' and 'E'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify IllegalFormatException, FormatterClosedException.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- @KnownFailure("Formatting of BigDecimal lost precission sometimes")
- public void test_formatLjava_lang_String$Ljava_lang_Object_BigDecimalConversionE() {
- Formatter f = null;
- final Object[][] tripleE = {
- {BigDecimal.ZERO, "%e", "0.000000e+00"},
- {BigDecimal.ZERO, "%#.0e", "0.e+00"},
- {BigDecimal.ZERO, "%# 9.8e", " 0.00000000e+00"},
- {BigDecimal.ZERO, "%#+0(8.4e", "+0.0000e+00"},
- {BigDecimal.ZERO, "%-+17.6e", "+0.000000e+00 "},
- {BigDecimal.ZERO, "% 0(20e", " 00000000.000000e+00"},
-
- {BigDecimal.ONE, "%e", "1.000000e+00"},
- {BigDecimal.ONE, "%#.0e", "1.e+00"},
- {BigDecimal.ONE, "%# 9.8e", " 1.00000000e+00"},
- {BigDecimal.ONE, "%#+0(8.4e", "+1.0000e+00"},
- {BigDecimal.ONE, "%-+17.6e", "+1.000000e+00 "},
- {BigDecimal.ONE, "% 0(20e", " 00000001.000000e+00"},
-
- {BigDecimal.TEN, "%e", "1.000000e+01"},
- {BigDecimal.TEN, "%#.0e", "1.e+01"},
- {BigDecimal.TEN, "%# 9.8e", " 1.00000000e+01"},
- {BigDecimal.TEN, "%#+0(8.4e", "+1.0000e+01"},
- {BigDecimal.TEN, "%-+17.6e", "+1.000000e+01 "},
- {BigDecimal.TEN, "% 0(20e", " 00000001.000000e+01"},
-
- {new BigDecimal(-1), "%e", "-1.000000e+00"},
- {new BigDecimal(-1), "%#.0e", "-1.e+00"},
- {new BigDecimal(-1), "%# 9.8e", "-1.00000000e+00"},
- {new BigDecimal(-1), "%#+0(8.4e", "(1.0000e+00)"},
- {new BigDecimal(-1), "%-+17.6e", "-1.000000e+00 "},
- {new BigDecimal(-1), "% 0(20e", "(0000001.000000e+00)"},
-
- {new BigDecimal("5.000E999"), "%e", "5.000000e+999"},
- {new BigDecimal("5.000E999"), "%#.0e", "5.e+999"},
- {new BigDecimal("5.000E999"), "%# 9.8e", " 5.00000000e+999"},
- {new BigDecimal("5.000E999"), "%#+0(8.4e", "+5.0000e+999"},
- {new BigDecimal("5.000E999"), "%-+17.6e", "+5.000000e+999 "},
- {new BigDecimal("5.000E999"), "% 0(20e", " 0000005.000000e+999"},
-
- {new BigDecimal("-5.000E999"), "%e", "-5.000000e+999"},
- {new BigDecimal("-5.000E999"), "%#.0e", "-5.e+999"},
- {new BigDecimal("-5.000E999"), "%# 9.8e", "-5.00000000e+999"},
- {new BigDecimal("-5.000E999"), "%#+0(8.4e", "(5.0000e+999)"},
- {new BigDecimal("-5.000E999"), "%-+17.6e", "-5.000000e+999 "},
- {new BigDecimal("-5.000E999"), "% 0(20e", "(000005.000000e+999)"},
- };
- final int input = 0;
- final int pattern = 1;
- final int output = 2;
- for (int i = 0; i < tripleE.length; i++) {
- f = new Formatter(Locale.US);
- f.format((String)tripleE[i][pattern], tripleE[i][input]);
- assertEquals("triple[" + i + "]:" + tripleE[i][input] + ",pattern["
- + i + "]:" + tripleE[i][pattern],
- tripleE[i][output], f.toString());
-
- // test for conversion type 'E'
- f = new Formatter(Locale.US);
- f.format(((String)tripleE[i][pattern]).toUpperCase(), tripleE[i][input]);
- assertEquals("triple[" + i + "]:" + tripleE[i][input] + ",pattern["
- + i + "]:" + tripleE[i][pattern], ((String)tripleE[i][output])
- .toUpperCase(Locale.US), f.toString());
- }
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for BigDecimal
- * conversion type 'g' and 'G'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify IllegalFormatException, FormatterClosedException.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- @KnownFailure("Formatting of BigDecimal lost precission sometimes")
- @AndroidOnly("last case fails on RI. See comment below")
- public void test_formatLjava_lang_String$Ljava_lang_Object_BigDecimalConversionG() {
- Formatter f = null;
- final Object[][] tripleG = {
- {BigDecimal.ZERO, "%g", "0.00000"},
- {BigDecimal.ZERO, "%.5g", "0.0000"},
- {BigDecimal.ZERO, "%- (,9.8g", " 0.0000000"},
- {BigDecimal.ZERO, "%+0(,8.4g", "+000.000"},
- {BigDecimal.ZERO, "%-+10.6g", "+0.00000 "},
- {BigDecimal.ZERO, "% 0(,12.0g", " 00000000000"},
- {BigDecimal.ONE, "%g", "1.00000"},
- {BigDecimal.ONE, "%.5g", "1.0000"},
- {BigDecimal.ONE, "%- (,9.8g", " 1.0000000"},
- {BigDecimal.ONE, "%+0(,8.4g", "+001.000"},
- {BigDecimal.ONE, "%-+10.6g", "+1.00000 "},
- {BigDecimal.ONE, "% 0(,12.0g", " 00000000001"},
-
- {new BigDecimal(-1), "%g", "-1.00000"},
- {new BigDecimal(-1), "%.5g", "-1.0000"},
- {new BigDecimal(-1), "%- (,9.8g", "(1.0000000)"},
- {new BigDecimal(-1), "%+0(,8.4g", "(01.000)"},
- {new BigDecimal(-1), "%-+10.6g", "-1.00000 "},
- {new BigDecimal(-1), "% 0(,12.0g", "(0000000001)"},
-
- {new BigDecimal(-0.000001), "%g", "-1.00000e-06"},
- {new BigDecimal(-0.000001), "%.5g", "-1.0000e-06"},
- {new BigDecimal(-0.000001), "%- (,9.8g", "(1.0000000e-06)"},
- {new BigDecimal(-0.000001), "%+0(,8.4g", "(1.000e-06)"},
- {new BigDecimal(-0.000001), "%-+10.6g", "-1.00000e-06"},
- {new BigDecimal(-0.000001), "% 0(,12.0g", "(000001e-06)"},
-
- {new BigDecimal(0.0002), "%g", "0.000200000"},
- {new BigDecimal(0.0002), "%.5g", "0.00020000"},
- {new BigDecimal(0.0002), "%- (,9.8g", " 0.00020000000"},
- {new BigDecimal(0.0002), "%+0(,8.4g", "+0.0002000"},
- {new BigDecimal(0.0002), "%-+10.6g", "+0.000200000"},
- {new BigDecimal(0.0002), "% 0(,12.0g", " 000000.0002"},
-
- {new BigDecimal(-0.003), "%g", "-0.00300000"},
- {new BigDecimal(-0.003), "%.5g", "-0.0030000"},
- {new BigDecimal(-0.003), "%- (,9.8g", "(0.0030000000)"},
- {new BigDecimal(-0.003), "%+0(,8.4g", "(0.003000)"},
- {new BigDecimal(-0.003), "%-+10.6g", "-0.00300000"},
- {new BigDecimal(-0.003), "% 0(,12.0g", "(000000.003)"},
-
- {new BigDecimal("5.000E999"), "%g", "5.00000e+999"},
- {new BigDecimal("5.000E999"), "%.5g", "5.0000e+999"},
- {new BigDecimal("5.000E999"), "%- (,9.8g", " 5.0000000e+999"},
- {new BigDecimal("5.000E999"), "%+0(,8.4g", "+5.000e+999"},
- {new BigDecimal("5.000E999"), "%-+10.6g", "+5.00000e+999"},
- {new BigDecimal("5.000E999"), "% 0(,12.0g", " 000005e+999"},
-
- {new BigDecimal("-5.000E999"), "%g", "-5.00000e+999"},
- {new BigDecimal("-5.000E999"), "%.5g", "-5.0000e+999"},
- {new BigDecimal("-5.000E999"), "%- (,9.8g", "(5.0000000e+999)"},
- {new BigDecimal("-5.000E999"), "%+0(,8.4g", "(5.000e+999)"},
- {new BigDecimal("-5.000E999"), "%-+10.6g", "-5.00000e+999"},
- {new BigDecimal("-5.000E999"), "% 0(,12.0g", "(00005e+999)"},
- };
- final int input = 0;
- final int pattern = 1;
- final int output = 2;
- for (int i = 0; i < tripleG.length; i++) {
- f = new Formatter(Locale.US);
- f.format((String)tripleG[i][pattern], tripleG[i][input]);
- assertEquals("triple[" + i + "]:" + tripleG[i][input] + ",pattern["
- + i + "]:" + tripleG[i][pattern],
- tripleG[i][output], f.toString());
-
- // test for conversion type 'G'
- f = new Formatter(Locale.US);
- f.format(((String)tripleG[i][pattern]).toUpperCase(), tripleG[i][input]);
- assertEquals("triple[" + i + "]:" + tripleG[i][input] + ",pattern["
- + i + "]:" + tripleG[i][pattern], ((String)tripleG[i][output])
- .toUpperCase(Locale.US), f.toString());
- }
-
- f = new Formatter(Locale.GERMAN);
- f.format("%- (,9.6g", new BigDecimal("4E6"));
- /*
- * fail on RI, spec says 'g' requires the output to be formatted in
- * general scientific notation and the localization algorithm is
- * applied. But RI format this case to 4.00000e+06, which does not
- * conform to the German Locale
- */
- assertEquals(" 4,00000e+06", f.toString());
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for BigDecimal
- * conversion type 'f'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify IllegalFormatException, FormatterClosedException.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- @AndroidOnly("last case fails on RI. See comment below")
- public void test_formatLjava_lang_String$Ljava_lang_Object_BigDecimalConversionF() {
-
- Formatter f = null;
- final int input = 0;
- final int pattern = 1;
- final int output = 2;
- final Object[][] tripleF = {
- {BigDecimal.ZERO, "%f", "0.000000"},
- {BigDecimal.ZERO, "%#.3f", "0.000"},
- {BigDecimal.ZERO, "%#,5f", "0.000000"},
- {BigDecimal.ZERO, "%- #(12.0f", " 0. "},
- {BigDecimal.ZERO, "%#+0(1.6f", "+0.000000"},
- {BigDecimal.ZERO, "%-+(8.4f", "+0.0000 "},
- {BigDecimal.ZERO, "% 0#(9.8f", " 0.00000000"},
- {BigDecimal.ONE, "%f", "1.000000"},
- {BigDecimal.ONE, "%#.3f", "1.000"},
- {BigDecimal.ONE, "%#,5f", "1.000000"},
- {BigDecimal.ONE, "%- #(12.0f", " 1. "},
- {BigDecimal.ONE, "%#+0(1.6f", "+1.000000"},
- {BigDecimal.ONE, "%-+(8.4f", "+1.0000 "},
- {BigDecimal.ONE, "% 0#(9.8f", " 1.00000000"},
- {BigDecimal.TEN, "%f", "10.000000"},
- {BigDecimal.TEN, "%#.3f", "10.000"},
- {BigDecimal.TEN, "%#,5f", "10.000000"},
- {BigDecimal.TEN, "%- #(12.0f", " 10. "},
- {BigDecimal.TEN, "%#+0(1.6f", "+10.000000"},
- {BigDecimal.TEN, "%-+(8.4f", "+10.0000"},
- {BigDecimal.TEN, "% 0#(9.8f", " 10.00000000"},
- {new BigDecimal(-1), "%f", "-1.000000"},
- {new BigDecimal(-1), "%#.3f", "-1.000"},
- {new BigDecimal(-1), "%#,5f", "-1.000000"},
- {new BigDecimal(-1), "%- #(12.0f", "(1.) "},
- {new BigDecimal(-1), "%#+0(1.6f", "(1.000000)"},
- {new BigDecimal(-1), "%-+(8.4f", "(1.0000)"},
- {new BigDecimal(-1), "% 0#(9.8f", "(1.00000000)"},
- {new BigDecimal("9999999999999999999999999999999999999999999"), "%f", "9999999999999999999999999999999999999999999.000000"},
- {new BigDecimal("9999999999999999999999999999999999999999999"), "%#.3f", "9999999999999999999999999999999999999999999.000"},
- {new BigDecimal("9999999999999999999999999999999999999999999"), "%#,5f", "9,999,999,999,999,999,999,999,999,999,999,999,999,999,999.000000"},
- {new BigDecimal("9999999999999999999999999999999999999999999"), "%- #(12.0f", " 9999999999999999999999999999999999999999999."},
- {new BigDecimal("9999999999999999999999999999999999999999999"), "%#+0(1.6f", "+9999999999999999999999999999999999999999999.000000"},
- {new BigDecimal("9999999999999999999999999999999999999999999"), "%-+(8.4f", "+9999999999999999999999999999999999999999999.0000"},
- {new BigDecimal("9999999999999999999999999999999999999999999"), "% 0#(9.8f", " 9999999999999999999999999999999999999999999.00000000"},
- {new BigDecimal("-9999999999999999999999999999999999999999999"), "%f", "-9999999999999999999999999999999999999999999.000000"},
- {new BigDecimal("-9999999999999999999999999999999999999999999"), "%#.3f", "-9999999999999999999999999999999999999999999.000"},
- {new BigDecimal("-9999999999999999999999999999999999999999999"), "%#,5f", "-9,999,999,999,999,999,999,999,999,999,999,999,999,999,999.000000"},
- {new BigDecimal("-9999999999999999999999999999999999999999999"), "%- #(12.0f", "(9999999999999999999999999999999999999999999.)"},
- {new BigDecimal("-9999999999999999999999999999999999999999999"), "%#+0(1.6f", "(9999999999999999999999999999999999999999999.000000)"},
- {new BigDecimal("-9999999999999999999999999999999999999999999"), "%-+(8.4f", "(9999999999999999999999999999999999999999999.0000)"},
- {new BigDecimal("-9999999999999999999999999999999999999999999"), "% 0#(9.8f", "(9999999999999999999999999999999999999999999.00000000)"},
- };
- for (int i = 0; i < tripleF.length; i++) {
- f = new Formatter(Locale.US);
- f.format((String)tripleF[i][pattern], tripleF[i][input]);
- assertEquals("triple[" + i + "]:" + tripleF[i][input] + ",pattern["
- + i + "]:" + tripleF[i][pattern], tripleF[i][output], f.toString());
- }
-
- f = new Formatter(Locale.US);
- f.format("%f", new BigDecimal("5.0E9"));
- // error on RI
- // RI throw ArrayIndexOutOfBoundsException
- assertEquals("5000000000.000000", f.toString());
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for exceptions in
- * Float/Double/BigDecimal conversion type 'e', 'E', 'g', 'G', 'f', 'a', 'A'
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies exceptions.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_FloatDoubleBigDecimalConversionException() {
- Formatter f = null;
-
- final char[] conversions = { 'e', 'E', 'g', 'G', 'f', 'a', 'A' };
- final Object[] illArgs = { false, (byte) 1, (short) 2, 3, (long) 4,
- new BigInteger("5"), new Character('c'), new Object(),
- new Date() };
- for (int i = 0; i < illArgs.length; i++) {
- for (int j = 0; j < conversions.length; j++) {
- try {
- f = new Formatter(Locale.UK);
- f.format("%" + conversions[j], illArgs[i]);
- fail("should throw IllegalFormatConversionException");
- } catch (IllegalFormatConversionException e) {
- // expected
- }
- }
- }
-
- try {
- f = new Formatter(Locale.UK);
- f.format("%a", new BigDecimal(1));
- fail("should throw IllegalFormatConversionException");
- } catch (IllegalFormatConversionException e) {
- // expected
- }
-
- try {
- f = new Formatter(Locale.UK);
- f.format("%A", new BigDecimal(1));
- fail("should throw IllegalFormatConversionException");
- } catch (IllegalFormatConversionException e) {
- // expected
- }
-
- final String[] flagsConversionMismatches = { "%,e", "%,E", "%#g",
- "%#G", "%,a", "%,A", "%(a", "%(A" };
- for (int i = 0; i < flagsConversionMismatches.length; i++) {
- try {
- f = new Formatter(Locale.CHINA);
- f.format(flagsConversionMismatches[i], new BigDecimal(1));
- fail("should throw FormatFlagsConversionMismatchException");
- } catch (FormatFlagsConversionMismatchException e) {
- // expected
- }
- try {
- f = new Formatter(Locale.JAPAN);
- f.format(flagsConversionMismatches[i], (BigDecimal) null);
- fail("should throw FormatFlagsConversionMismatchException");
- } catch (FormatFlagsConversionMismatchException e) {
- // expected
- }
- }
-
- final String[] missingFormatWidths = { "%-0e", "%0e", "%-e", "%-0E",
- "%0E", "%-E", "%-0g", "%0g", "%-g", "%-0G", "%0G", "%-G",
- "%-0f", "%0f", "%-f", "%-0a", "%0a", "%-a", "%-0A", "%0A",
- "%-A" };
- for (int i = 0; i < missingFormatWidths.length; i++) {
- try {
- f = new Formatter(Locale.KOREA);
- f.format(missingFormatWidths[i], 1f);
- fail("should throw MissingFormatWidthException");
- } catch (MissingFormatWidthException e) {
- // expected
- }
-
- try {
- f = new Formatter(Locale.KOREA);
- f.format(missingFormatWidths[i], (Float) null);
- fail("should throw MissingFormatWidthException");
- } catch (MissingFormatWidthException e) {
- // expected
- }
- }
-
- final String[] illFlags = { "%+ e", "%+ E", "%+ g", "%+ G", "%+ f",
- "%+ a", "%+ A", "%-03e", "%-03E", "%-03g", "%-03G", "%-03f",
- "%-03a", "%-03A" };
- for (int i = 0; i < illFlags.length; i++) {
- try {
- f = new Formatter(Locale.CANADA);
- f.format(illFlags[i], 1.23d);
- fail("should throw IllegalFormatFlagsException");
- } catch (IllegalFormatFlagsException e) {
- // expected
- }
-
- try {
- f = new Formatter(Locale.CANADA);
- f.format(illFlags[i], (Double) null);
- fail("should throw IllegalFormatFlagsException");
- } catch (IllegalFormatFlagsException e) {
- // expected
- }
- }
-
- f = new Formatter(Locale.US);
- try {
- f.format("%F", 1);
- fail("should throw UnknownFormatConversionException");
- } catch (UnknownFormatConversionException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for
- * Float/Double/BigDecimal exception throwing order
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies exceptions.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_FloatDoubleBigDecimalExceptionOrder() {
- Formatter f = null;
-
- /*
- * Summary: UnknownFormatConversionException >
- * MissingFormatWidthException > IllegalFormatFlagsException >
- * FormatFlagsConversionMismatchException >
- * IllegalFormatConversionException
- *
- */
- try {
- // compare FormatFlagsConversionMismatchException and
- // IllegalFormatConversionException
- f = new Formatter(Locale.US);
- f.format("%,e", (byte) 1);
- fail("should throw FormatFlagsConversionMismatchException");
- } catch (FormatFlagsConversionMismatchException e) {
- // expected
- }
-
- try {
- // compare IllegalFormatFlagsException and
- // FormatFlagsConversionMismatchException
- f = new Formatter(Locale.US);
- f.format("%+ ,e", 1f);
- fail("should throw IllegalFormatFlagsException");
- } catch (IllegalFormatFlagsException e) {
- // expected
- }
-
- try {
- // compare MissingFormatWidthException and
- // IllegalFormatFlagsException
- f = new Formatter(Locale.US);
- f.format("%+ -e", 1f);
- fail("should throw MissingFormatWidthException");
- } catch (MissingFormatWidthException e) {
- // expected
- }
-
- try {
- // compare UnknownFormatConversionException and
- // MissingFormatWidthException
- f = new Formatter(Locale.US);
- f.format("%-F", 1f);
- fail("should throw UnknownFormatConversionException");
- } catch (UnknownFormatConversionException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for BigDecimal
- * exception throwing order
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies exceptions.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_BigDecimalExceptionOrder() {
- Formatter f = null;
- BigDecimal bd = new BigDecimal("1.0");
-
- /*
- * Summary: UnknownFormatConversionException >
- * MissingFormatWidthException > IllegalFormatFlagsException >
- * FormatFlagsConversionMismatchException >
- * IllegalFormatConversionException
- *
- */
- try {
- // compare FormatFlagsConversionMismatchException and
- // IllegalFormatConversionException
- f = new Formatter(Locale.US);
- f.format("%,e", (byte) 1);
- fail("should throw FormatFlagsConversionMismatchException");
- } catch (FormatFlagsConversionMismatchException e) {
- // expected
- }
-
- try {
- // compare IllegalFormatFlagsException and
- // FormatFlagsConversionMismatchException
- f = new Formatter(Locale.US);
- f.format("%+ ,e", bd);
- fail("should throw IllegalFormatFlagsException");
- } catch (IllegalFormatFlagsException e) {
- // expected
- }
-
- try {
- // compare MissingFormatWidthException and
- // IllegalFormatFlagsException
- f = new Formatter(Locale.US);
- f.format("%+ -e", bd);
- fail("should throw MissingFormatWidthException");
- } catch (MissingFormatWidthException e) {
- // expected
- }
-
- // compare UnknownFormatConversionException and
- // MissingFormatWidthException
- try {
- f = new Formatter(Locale.US);
- f.format("%-F", bd);
- fail("should throw UnknownFormatConversionException");
- } catch (UnknownFormatConversionException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Formatter#format(String, Object...) for null argment for
- * Float/Double/BigDecimal conversion
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies null as the second parameter.",
- method = "format",
- args = {java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_lang_String$Ljava_lang_Object_FloatDoubleBigDecimalNullConversion() {
- Formatter f = null;
-
- // test (Float)null
- f = new Formatter(Locale.FRANCE);
- f.format("%#- (9.0e", (Float) null);
- assertEquals(" ", f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format("%-+(1.6E", (Float) null);
- assertEquals("NULL", f.toString());
-
- f = new Formatter(Locale.UK);
- f.format("%+0(,8.4g", (Float) null);
- assertEquals(" null", f.toString());
-
- f = new Formatter(Locale.FRANCE);
- f.format("%- (9.8G", (Float) null);
- assertEquals("NULL ", f.toString());
-
- f = new Formatter(Locale.FRANCE);
- f.format("%- (12.1f", (Float) null);
- assertEquals("n ", f.toString());
-
- f = new Formatter(Locale.FRANCE);
- f.format("% .4a", (Float) null);
- assertEquals("null", f.toString());
-
- f = new Formatter(Locale.FRANCE);
- f.format("%06A", (Float) null);
- assertEquals(" NULL", f.toString());
-
- // test (Double)null
- f = new Formatter(Locale.GERMAN);
- f.format("%- (9e", (Double) null);
- assertEquals("null ", f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format("%#-+(1.6E", (Double) null);
- assertEquals("NULL", f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format("%+0(6.4g", (Double) null);
- assertEquals(" null", f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format("%- (,5.8G", (Double) null);
- assertEquals("NULL ", f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format("% (.4f", (Double) null);
- assertEquals("null", f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format("%#.6a", (Double) null);
- assertEquals("null", f.toString());
-
- f = new Formatter(Locale.GERMAN);
- f.format("% 2.5A", (Double) null);
- assertEquals("NULL", f.toString());
-
- // test (BigDecimal)null
- f = new Formatter(Locale.UK);
- f.format("%#- (6.2e", (BigDecimal) null);
- assertEquals("nu ", f.toString());
-
- f = new Formatter(Locale.UK);
- f.format("%-+(1.6E", (BigDecimal) null);
- assertEquals("NULL", f.toString());
-
- f = new Formatter(Locale.UK);
- f.format("%+-(,5.3g", (BigDecimal) null);
- assertEquals("nul ", f.toString());
-
- f = new Formatter(Locale.UK);
- f.format("%0 3G", (BigDecimal) null);
- assertEquals("NULL", f.toString());
-
- f = new Formatter(Locale.UK);
- f.format("%0 (9.0G", (BigDecimal) null);
- assertEquals(" ", f.toString());
-
- f = new Formatter(Locale.UK);
- f.format("% (.5f", (BigDecimal) null);
- assertEquals("null", f.toString());
-
- f = new Formatter(Locale.UK);
- f.format("%06a", (BigDecimal) null);
- assertEquals(" null", f.toString());
-
- f = new Formatter(Locale.UK);
- f.format("% .5A", (BigDecimal) null);
- assertEquals("NULL", f.toString());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Check locale specific functionality, not all formatter functional.Formatter functionality well checked under above tests.",
- method = "format",
- args = {java.util.Locale.class, java.lang.String.class, java.lang.Object[].class}
- )
- public void test_formatLjava_util_LocaleLjava_lang_StringLjava_lang_Object$() {
- Double val = new Double(3.14);
- Calendar cal = Calendar.getInstance();
- Formatter fLoc = null;
- Formatter fNoL = null;
- cal.set(2008, Calendar.SEPTEMBER, 23, 18, 30);
-
- fLoc = new Formatter(Locale.GERMAN);
- fNoL = new Formatter(Locale.GERMAN);
- fLoc.format(Locale.US, "%f", val);
- fNoL.format("%f", val);
- assertFalse(fLoc.toString().equals(fNoL.toString()));
-
- fLoc = new Formatter(Locale.FRANCE);
- fNoL = new Formatter(Locale.FRANCE);
- fLoc.format(Locale.US, "%f", val);
- fNoL.format("%f", val);
- assertFalse(fLoc.toString().equals(fNoL.toString()));
-
- fLoc = new Formatter(Locale.US);
- fNoL = new Formatter(Locale.US);
- fLoc.format(Locale.US, "%f", val);
- fNoL.format("%f", val);
- assertTrue(fLoc.toString().equals(fNoL.toString()));
-
- fLoc = new Formatter(Locale.GERMAN);
- fNoL = new Formatter(Locale.GERMAN);
- fLoc.format(Locale.US, "%tA %tB %td %tT", cal, cal, cal, cal);
- fNoL.format("%tA %tB %td %tT", cal, cal, cal, cal);
- assertFalse(fLoc.toString().equals(fNoL.toString()));
-
- fLoc = new Formatter(Locale.FRANCE);
- fNoL = new Formatter(Locale.FRANCE);
- fLoc.format(Locale.US, "%tA %tB %td %tT", cal, cal, cal, cal);
- fNoL.format("%tA %tB %td %tT", cal, cal, cal, cal);
- assertFalse(fLoc.toString().equals(fNoL.toString()));
-
- fLoc = new Formatter(Locale.US);
- fNoL = new Formatter(Locale.US);
- fLoc.format(Locale.US, "%tA %tB %td %tT", cal, cal, cal, cal);
- fNoL.format("%tA %tB %td %tT", cal, cal, cal, cal);
- assertTrue(fLoc.toString().equals(fNoL.toString()));
-
- final String[] illFlags = { "%+ e", "%+ E", "%+ g", "%+ G", "%+ f",
- "%+ a", "%+ A", "%-03e", "%-03E", "%-03g", "%-03G", "%-03f",
- "%-03a", "%-03A" };
- for (int i = 0; i < illFlags.length; i++) {
- try {
- fLoc = new Formatter(Locale.US);
- fLoc.format(Locale.FRANCE, illFlags[i], 1.23d);
- fail("should throw IllegalFormatFlagsException");
- } catch (IllegalFormatFlagsException e) {
- // expected
- }
-
- try {
- fLoc = new Formatter(Locale.CANADA);
- fLoc.format(Locale.GERMAN, illFlags[i], (Double) null);
- fail("should throw IllegalFormatFlagsException");
- } catch (IllegalFormatFlagsException e) {
- // expected
- }
- }
-
- fLoc.close();
-
- try {
- fLoc.format(Locale.GERMAN, "%f", val);
- } catch (FormatterClosedException e) {
- //expected
- }
- }
-
- /**
- * Setup resource files for testing
- */
- protected void setUp() throws IOException {
- notExist = File.createTempFile("notexist", null);
- notExist.delete();
-
- fileWithContent = File.createTempFile("filewithcontent", null);
- BufferedOutputStream bw = new BufferedOutputStream(
- new FileOutputStream(fileWithContent));
- bw.write(1);// write something into the file
- bw.close();
-
- readOnly = File.createTempFile("readonly", null);
- readOnly.setReadOnly();
-
- secret = File.createTempFile("secret", null);
-
- defaultTimeZone = TimeZone.getDefault();
- TimeZone cst = TimeZone.getTimeZone("Asia/Shanghai");
- TimeZone.setDefault(cst);
- }
-
- /**
- * Delete the resource files if they exist
- */
- protected void tearDown() {
- if (notExist.exists()) {
- notExist.delete();
- }
-
- if (fileWithContent.exists()) {
- fileWithContent.delete();
- }
- if (readOnly.exists()) {
- readOnly.delete();
- }
- if (secret.exists()) {
- secret.delete();
- }
-
- TimeZone.setDefault(defaultTimeZone);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/GregorianCalendarTest.java b/luni/src/test/java/tests/api/java/util/GregorianCalendarTest.java
deleted file mode 100644
index 76026bf..0000000
--- a/luni/src/test/java/tests/api/java/util/GregorianCalendarTest.java
+++ /dev/null
@@ -1,952 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.KnownFailure;
-
-import java.util.BitSet;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.Locale;
-import java.util.SimpleTimeZone;
-import java.util.TimeZone;
-import java.util.Vector;
-
-
-@TestTargetClass(GregorianCalendar.class)
-public class GregorianCalendarTest extends junit.framework.TestCase {
-
- /**
- * @tests java.util.GregorianCalendar#GregorianCalendar()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "GregorianCalendar",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.GregorianCalendar()
- assertTrue("Constructed incorrect calendar", (new GregorianCalendar()
- .isLenient()));
- }
-
- /**
- * @tests java.util.GregorianCalendar#GregorianCalendar(int, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "GregorianCalendar",
- args = {int.class, int.class, int.class}
- )
- public void test_ConstructorIII() {
- // Test for method java.util.GregorianCalendar(int, int, int)
- GregorianCalendar gc = new GregorianCalendar(1972, Calendar.OCTOBER, 13);
- assertEquals("Incorrect calendar constructed 1",
- 1972, gc.get(Calendar.YEAR));
- assertTrue("Incorrect calendar constructed 2",
- gc.get(Calendar.MONTH) == Calendar.OCTOBER);
- assertEquals("Incorrect calendar constructed 3", 13, gc
- .get(Calendar.DAY_OF_MONTH));
- assertTrue("Incorrect calendar constructed 4", gc.getTimeZone().equals(
- TimeZone.getDefault()));
- }
-
- /**
- * @tests java.util.GregorianCalendar#GregorianCalendar(int, int, int, int,
- * int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "GregorianCalendar",
- args = {int.class, int.class, int.class, int.class, int.class}
- )
- public void test_ConstructorIIIII() {
- // Test for method java.util.GregorianCalendar(int, int, int, int, int)
- GregorianCalendar gc = new GregorianCalendar(1972, Calendar.OCTOBER,
- 13, 19, 9);
- assertEquals("Incorrect calendar constructed",
- 1972, gc.get(Calendar.YEAR));
- assertTrue("Incorrect calendar constructed",
- gc.get(Calendar.MONTH) == Calendar.OCTOBER);
- assertEquals("Incorrect calendar constructed", 13, gc
- .get(Calendar.DAY_OF_MONTH));
- assertEquals("Incorrect calendar constructed", 7, gc.get(Calendar.HOUR));
- assertEquals("Incorrect calendar constructed",
- 1, gc.get(Calendar.AM_PM));
- assertEquals("Incorrect calendar constructed",
- 9, gc.get(Calendar.MINUTE));
- assertTrue("Incorrect calendar constructed", gc.getTimeZone().equals(
- TimeZone.getDefault()));
-
- //Regression for HARMONY-998
- gc = new GregorianCalendar(1900, 0, 0, 0, Integer.MAX_VALUE);
- assertEquals("Incorrect calendar constructed",
- 5983, gc.get(Calendar.YEAR));
- }
-
- /**
- * @tests java.util.GregorianCalendar#GregorianCalendar(int, int, int, int,
- * int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "GregorianCalendar",
- args = {int.class, int.class, int.class, int.class, int.class, int.class}
- )
- public void test_ConstructorIIIIII() {
- // Test for method java.util.GregorianCalendar(int, int, int, int, int,
- // int)
- GregorianCalendar gc = new GregorianCalendar(1972, Calendar.OCTOBER,
- 13, 19, 9, 59);
- assertEquals("Incorrect calendar constructed",
- 1972, gc.get(Calendar.YEAR));
- assertTrue("Incorrect calendar constructed",
- gc.get(Calendar.MONTH) == Calendar.OCTOBER);
- assertEquals("Incorrect calendar constructed", 13, gc
- .get(Calendar.DAY_OF_MONTH));
- assertEquals("Incorrect calendar constructed", 7, gc.get(Calendar.HOUR));
- assertEquals("Incorrect calendar constructed",
- 1, gc.get(Calendar.AM_PM));
- assertEquals("Incorrect calendar constructed",
- 9, gc.get(Calendar.MINUTE));
- assertEquals("Incorrect calendar constructed",
- 59, gc.get(Calendar.SECOND));
- assertTrue("Incorrect calendar constructed", gc.getTimeZone().equals(
- TimeZone.getDefault()));
- }
-
- /**
- * @tests java.util.GregorianCalendar#GregorianCalendar(java.util.Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "GregorianCalendar",
- args = {java.util.Locale.class}
- )
- public void test_ConstructorLjava_util_Locale() {
- // Test for method java.util.GregorianCalendar(java.util.Locale)
- Date date = new Date();
- GregorianCalendar gcUS = new GregorianCalendar(Locale.US);
- gcUS.setTime(date);
- GregorianCalendar gcUS2 = new GregorianCalendar(Locale.US);
- gcUS2.setTime(date);
- GregorianCalendar gcFrance = new GregorianCalendar(Locale.FRANCE);
- gcFrance.setTime(date);
- assertTrue("Locales not created correctly", gcUS.equals(gcUS2));
- assertFalse("Locales not created correctly", gcUS.equals(gcFrance));
- }
-
- /**
- * @tests java.util.GregorianCalendar#GregorianCalendar(java.util.TimeZone)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "GregorianCalendar",
- args = {java.util.TimeZone.class}
- )
- public void test_ConstructorLjava_util_TimeZone() {
- // Test for method java.util.GregorianCalendar(java.util.TimeZone)
- Date date = new Date();
- TimeZone.getDefault();
- GregorianCalendar gc1 = new GregorianCalendar(TimeZone
- .getTimeZone("EST"));
- gc1.setTime(date);
- GregorianCalendar gc2 = new GregorianCalendar(TimeZone
- .getTimeZone("CST"));
- gc2.setTime(date);
-
- assertFalse(gc1.equals(gc2));
-
- gc1 = new GregorianCalendar(TimeZone
- .getTimeZone("GMT+2"));
- gc1.setTime(date);
- gc2 = new GregorianCalendar(TimeZone
- .getTimeZone("GMT+1"));
- gc2.setTime(date);
- assertTrue("Incorrect calendar returned",
- gc1.get(Calendar.HOUR) == ((gc2.get(Calendar.HOUR) + 1) % 12));
-
- // Regression test for HARMONY-2961
- SimpleTimeZone timezone = new SimpleTimeZone(-3600 * 24 * 1000 * 2,
- "GMT");
- GregorianCalendar gc = new GregorianCalendar(timezone);
- }
-
- /**
- * @tests java.util.GregorianCalendar#GregorianCalendar(java.util.TimeZone,
- * java.util.Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "GregorianCalendar",
- args = {java.util.TimeZone.class, java.util.Locale.class}
- )
- @KnownFailure("same objects for different locales are not considered equal")
- public void test_ConstructorLjava_util_TimeZoneLjava_util_Locale() {
- // Test for method java.util.GregorianCalendar(java.util.TimeZone,
- // java.util.Locale)
- Date date = new Date();
- TimeZone.getDefault();
- GregorianCalendar gc1 = new GregorianCalendar(TimeZone
- .getTimeZone("EST"), Locale.US);
- gc1.setTime(date);
- GregorianCalendar gc2 = new GregorianCalendar(TimeZone
- .getTimeZone("EST"), Locale.US);
- gc2.setTime(date);
- GregorianCalendar gc3 = new GregorianCalendar(TimeZone
- .getTimeZone("CST"), Locale.FRANCE);
- gc3.setTime(date);
- assertTrue(gc1.equals(gc2));
- assertFalse(gc2.equals(gc3));
- assertFalse(gc3.equals(gc1));
-
- gc1 = new GregorianCalendar(TimeZone
- .getTimeZone("GMT+2"), Locale.US);
- gc1.setTime(date);
- gc3 = new GregorianCalendar(TimeZone
- .getTimeZone("GMT+1"), Locale.FRANCE);
- gc3.setTime(date);
- // CST is 1 hour before EST, add 1 to the CST time and convert to 0-12
- // value
- assertTrue("Incorrect calendar returned",
- gc1.get(Calendar.HOUR) == ((gc3.get(Calendar.HOUR) + 1) % 12));
- }
-
- /**
- * @tests java.util.GregorianCalendar#add(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "add",
- args = {int.class, int.class}
- )
- public void test_addII() {
- // Test for method void java.util.GregorianCalendar.add(int, int)
- GregorianCalendar gc1 = new GregorianCalendar(1998, 11, 6);
- gc1.add(GregorianCalendar.YEAR, 1);
- assertEquals("Add failed to Increment",
- 1999, gc1.get(GregorianCalendar.YEAR));
-
- gc1 = new GregorianCalendar(1999, Calendar.JULY, 31);
- gc1.add(Calendar.MONTH, 7);
- assertEquals("Wrong result year 1", 2000, gc1.get(Calendar.YEAR));
- assertTrue("Wrong result month 1",
- gc1.get(Calendar.MONTH) == Calendar.FEBRUARY);
- assertEquals("Wrong result date 1", 29, gc1.get(Calendar.DATE));
-
- gc1.add(Calendar.YEAR, -1);
- assertEquals("Wrong result year 2", 1999, gc1.get(Calendar.YEAR));
- assertTrue("Wrong result month 2",
- gc1.get(Calendar.MONTH) == Calendar.FEBRUARY);
- assertEquals("Wrong result date 2", 28, gc1.get(Calendar.DATE));
-
- gc1 = new GregorianCalendar(TimeZone.getTimeZone("EST"));
- gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
- gc1.add(Calendar.MILLISECOND, 24 * 60 * 60 * 1000);
-
- assertEquals("Wrong time after MILLISECOND change", 16, gc1
- .get(Calendar.HOUR_OF_DAY));
- gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
- gc1.add(Calendar.SECOND, 24 * 60 * 60);
- assertEquals("Wrong time after SECOND change", 16, gc1
- .get(Calendar.HOUR_OF_DAY));
- gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
- gc1.add(Calendar.MINUTE, 24 * 60);
- assertEquals("Wrong time after MINUTE change", 16, gc1
- .get(Calendar.HOUR_OF_DAY));
- gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
- gc1.add(Calendar.HOUR, 24);
- assertEquals("Wrong time after HOUR change", 16, gc1
- .get(Calendar.HOUR_OF_DAY));
- gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
- gc1.add(Calendar.HOUR_OF_DAY, 24);
- assertEquals("Wrong time after HOUR_OF_DAY change", 16, gc1
- .get(Calendar.HOUR_OF_DAY));
-
- gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
- gc1.add(Calendar.AM_PM, 2);
- assertEquals("Wrong time after AM_PM change", 16, gc1
- .get(Calendar.HOUR_OF_DAY));
- gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
- gc1.add(Calendar.DATE, 1);
- assertEquals("Wrong time after DATE change", 16, gc1
- .get(Calendar.HOUR_OF_DAY));
- gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
- gc1.add(Calendar.DAY_OF_YEAR, 1);
- assertEquals("Wrong time after DAY_OF_YEAR change", 16, gc1
- .get(Calendar.HOUR_OF_DAY));
- gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
- gc1.add(Calendar.DAY_OF_WEEK, 1);
- assertEquals("Wrong time after DAY_OF_WEEK change", 16, gc1
- .get(Calendar.HOUR_OF_DAY));
- gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
- gc1.add(Calendar.WEEK_OF_YEAR, 1);
- assertEquals("Wrong time after WEEK_OF_YEAR change", 16, gc1
- .get(Calendar.HOUR_OF_DAY));
- gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
- gc1.add(Calendar.WEEK_OF_MONTH, 1);
- assertEquals("Wrong time after WEEK_OF_MONTH change", 16, gc1
- .get(Calendar.HOUR_OF_DAY));
- gc1.set(1999, Calendar.APRIL, 3, 16, 0); // day before DST change
- gc1.add(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
- assertEquals("Wrong time after DAY_OF_WEEK_IN_MONTH change", 16, gc1
- .get(Calendar.HOUR_OF_DAY));
-
- gc1.clear();
- gc1.set(2000, Calendar.APRIL, 1, 23, 0);
- gc1.add(Calendar.DATE, 1);
- assertTrue("Wrong time after DATE change near DST boundary", gc1
- .get(Calendar.MONTH) == Calendar.APRIL
- && gc1.get(Calendar.DATE) == 2
- && gc1.get(Calendar.HOUR_OF_DAY) == 23);
- }
-
- /**
- * @tests java.util.GregorianCalendar#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean
- // java.util.GregorianCalendar.equals(java.lang.Object)
- GregorianCalendar gc1 = new GregorianCalendar(1998, 11, 6);
- GregorianCalendar gc2 = new GregorianCalendar(2000, 11, 6);
- GregorianCalendar gc3 = new GregorianCalendar(1998, 11, 6);
- assertTrue("Equality check failed", gc1.equals(gc3));
- assertTrue("Equality check failed", !gc1.equals(gc2));
- gc3.setGregorianChange(new Date());
- assertTrue("Different gregorian change", !gc1.equals(gc3));
- }
-
- /**
- * @tests java.util.GregorianCalendar#getActualMaximum(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getActualMaximum",
- args = {int.class}
- )
- public void test_getActualMaximumI() {
- // Test for method int java.util.GregorianCalendar.getActualMaximum(int)
- GregorianCalendar gc1 = new GregorianCalendar(1900, 1, 1);
- GregorianCalendar gc2 = new GregorianCalendar(1996, 1, 1);
- GregorianCalendar gc3 = new GregorianCalendar(1997, 1, 1);
- GregorianCalendar gc4 = new GregorianCalendar(2000, 1, 1);
- GregorianCalendar gc5 = new GregorianCalendar(2000, 9, 9);
- GregorianCalendar gc6 = new GregorianCalendar(2000, 3, 3);
- assertEquals("Wrong actual maximum value for DAY_OF_MONTH for Feb 1900",
- 28, gc1.getActualMaximum(Calendar.DAY_OF_MONTH));
- assertEquals("Wrong actual maximum value for DAY_OF_MONTH for Feb 1996",
- 29, gc2.getActualMaximum(Calendar.DAY_OF_MONTH));
- assertEquals("Wrong actual maximum value for DAY_OF_MONTH for Feb 1998",
- 28, gc3.getActualMaximum(Calendar.DAY_OF_MONTH));
- assertEquals("Wrong actual maximum value for DAY_OF_MONTH for Feb 2000",
- 29, gc4.getActualMaximum(Calendar.DAY_OF_MONTH));
- assertEquals("Wrong actual maximum value for DAY_OF_MONTH for Oct 2000",
- 31, gc5.getActualMaximum(Calendar.DAY_OF_MONTH));
- assertEquals("Wrong actual maximum value for DAY_OF_MONTH for Apr 2000",
- 30, gc6.getActualMaximum(Calendar.DAY_OF_MONTH));
- assertTrue("Wrong actual maximum value for MONTH", gc1
- .getActualMaximum(Calendar.MONTH) == Calendar.DECEMBER);
- assertEquals("Wrong actual maximum value for HOUR_OF_DAY", 23, gc1
- .getActualMaximum(Calendar.HOUR_OF_DAY));
- assertEquals("Wrong actual maximum value for HOUR", 11, gc1
- .getActualMaximum(Calendar.HOUR));
- assertEquals("Wrong actual maximum value for DAY_OF_WEEK_IN_MONTH", 4, gc6
- .getActualMaximum(Calendar.DAY_OF_WEEK_IN_MONTH));
-
-
- // Regression test for harmony 2954
- Date date = new Date(Date.parse("Jan 15 00:00:01 GMT 2000"));
- GregorianCalendar gc = new GregorianCalendar();
- gc.setTimeInMillis(Date.parse("Dec 15 00:00:01 GMT 1582"));
- assertEquals(355, gc.getActualMaximum(Calendar.DAY_OF_YEAR));
- gc.setGregorianChange(date);
- gc.setTimeInMillis(Date.parse("Jan 16 00:00:01 GMT 2000"));
- assertEquals(353, gc.getActualMaximum(Calendar.DAY_OF_YEAR));
-
- //Regression test for HARMONY-3004
- gc = new GregorianCalendar(1900, 7, 1);
- String[] ids = TimeZone.getAvailableIDs();
- for (int i = 0; i < ids.length; i++) {
- TimeZone tz = TimeZone.getTimeZone(ids[i]);
- gc.setTimeZone(tz);
- for (int j = 1900; j < 2000; j++) {
- gc.set(Calendar.YEAR, j);
- assertEquals(7200000, gc.getActualMaximum(Calendar.DST_OFFSET));
- }
- }
- }
-
- /**
- * @tests java.util.GregorianCalendar#getActualMinimum(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getActualMinimum",
- args = {int.class}
- )
- public void test_getActualMinimumI() {
- // Test for method int java.util.GregorianCalendar.getActualMinimum(int)
- GregorianCalendar gc1 = new GregorianCalendar(1900, 1, 1);
- new GregorianCalendar(1996, 1, 1);
- new GregorianCalendar(1997, 1, 1);
- new GregorianCalendar(2000, 1, 1);
- new GregorianCalendar(2000, 9, 9);
- GregorianCalendar gc6 = new GregorianCalendar(2000, 3, 3);
- assertEquals("Wrong actual minimum value for DAY_OF_MONTH for Feb 1900",
- 1, gc1.getActualMinimum(Calendar.DAY_OF_MONTH));
- assertTrue("Wrong actual minimum value for MONTH", gc1
- .getActualMinimum(Calendar.MONTH) == Calendar.JANUARY);
- assertEquals("Wrong actual minimum value for HOUR_OF_DAY", 0, gc1
- .getActualMinimum(Calendar.HOUR_OF_DAY));
- assertEquals("Wrong actual minimum value for HOUR", 0, gc1
- .getActualMinimum(Calendar.HOUR));
- assertEquals("Wrong actual minimum value for DAY_OF_WEEK_IN_MONTH", 1, gc6
- .getActualMinimum(Calendar.DAY_OF_WEEK_IN_MONTH));
- }
-
- /**
- * @tests java.util.GregorianCalendar#getGreatestMinimum(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getGreatestMinimum",
- args = {int.class}
- )
- public void test_getGreatestMinimumI() {
- // Test for method int
- // java.util.GregorianCalendar.getGreatestMinimum(int)
- GregorianCalendar gc = new GregorianCalendar();
- assertEquals("Wrong greatest minimum value for DAY_OF_MONTH", 1, gc
- .getGreatestMinimum(Calendar.DAY_OF_MONTH));
- assertTrue("Wrong greatest minimum value for MONTH", gc
- .getGreatestMinimum(Calendar.MONTH) == Calendar.JANUARY);
- assertEquals("Wrong greatest minimum value for HOUR_OF_DAY", 0, gc
- .getGreatestMinimum(Calendar.HOUR_OF_DAY));
- assertEquals("Wrong greatest minimum value for HOUR", 0, gc
- .getGreatestMinimum(Calendar.HOUR));
-
- BitSet result = new BitSet();
- int[] min = { 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, -46800000,
- 0 };
- for (int i = 0; i < min.length; i++) {
- if (gc.getGreatestMinimum(i) != min[i])
- result.set(i);
- }
- assertTrue("Wrong greatest min for " + result, result.length() == 0);
- }
-
- /**
- * @tests java.util.GregorianCalendar#getGregorianChange()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getGregorianChange",
- args = {}
- )
- public void test_getGregorianChange() {
- // Test for method java.util.Date
- // java.util.GregorianCalendar.getGregorianChange()
- GregorianCalendar gc = new GregorianCalendar();
- GregorianCalendar returnedChange = new GregorianCalendar(TimeZone
- .getTimeZone("EST"));
- returnedChange.setTime(gc.getGregorianChange());
- assertEquals("Returned incorrect year",
- 1582, returnedChange.get(Calendar.YEAR));
- assertTrue("Returned incorrect month", returnedChange
- .get(Calendar.MONTH) == Calendar.OCTOBER);
- assertEquals("Returned incorrect day of month", 4, returnedChange
- .get(Calendar.DAY_OF_MONTH));
- }
-
- /**
- * @tests java.util.GregorianCalendar#getLeastMaximum(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLeastMaximum",
- args = {int.class}
- )
- public void test_getLeastMaximumI() {
- // Test for method int java.util.GregorianCalendar.getLeastMaximum(int)
- GregorianCalendar gc = new GregorianCalendar();
- assertEquals("Wrong least maximum value for DAY_OF_MONTH", 28, gc
- .getLeastMaximum(Calendar.DAY_OF_MONTH));
- assertTrue("Wrong least maximum value for MONTH", gc
- .getLeastMaximum(Calendar.MONTH) == Calendar.DECEMBER);
- assertEquals("Wrong least maximum value for HOUR_OF_DAY", 23, gc
- .getLeastMaximum(Calendar.HOUR_OF_DAY));
- assertEquals("Wrong least maximum value for HOUR", 11, gc
- .getLeastMaximum(Calendar.HOUR));
-
- BitSet result = new BitSet();
- Vector values = new Vector();
- int[] max = { 1, 292269054, 11, 50, 3, 28, 355, 7, 3, 1, 11, 23, 59,
- 59, 999, 50400000, 1200000 };
- for (int i = 0; i < max.length; i++) {
- if (gc.getLeastMaximum(i) != max[i]) {
- result.set(i);
- values.add(new Integer(gc.getLeastMaximum(i)));
- }
- }
- assertTrue("Wrong least max for " + result + " = " + values, result
- .length() == 0);
-
- // Regression test for harmony-2947
- Date date = new Date(Date.parse("Jan 1 00:00:01 GMT 2000"));
- gc = new GregorianCalendar();
- gc.setGregorianChange(date);
- gc.setTime(date);
- assertEquals(gc.getActualMaximum(Calendar.WEEK_OF_YEAR), gc
- .getLeastMaximum(Calendar.WEEK_OF_YEAR));
- }
-
- /**
- * @tests java.util.GregorianCalendar#getMaximum(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMaximum",
- args = {int.class}
- )
- public void test_getMaximumI() {
- // Test for method int java.util.GregorianCalendar.getMaximum(int)
- GregorianCalendar gc = new GregorianCalendar();
- assertEquals("Wrong maximum value for DAY_OF_MONTH", 31, gc
- .getMaximum(Calendar.DAY_OF_MONTH));
- assertTrue("Wrong maximum value for MONTH", gc
- .getMaximum(Calendar.MONTH) == Calendar.DECEMBER);
- assertEquals("Wrong maximum value for HOUR_OF_DAY", 23, gc
- .getMaximum(Calendar.HOUR_OF_DAY));
- assertEquals("Wrong maximum value for HOUR",
- 11, gc.getMaximum(Calendar.HOUR));
-
- BitSet result = new BitSet();
- Vector values = new Vector();
- int[] max = { 1, 292278994, 11, 53, 6, 31, 366, 7, 6, 1, 11, 23, 59,
- 59, 999, 50400000, 7200000 };
- for (int i = 0; i < max.length; i++) {
- if (gc.getMaximum(i) != max[i]) {
- result.set(i);
- values.add(new Integer(gc.getMaximum(i)));
- }
- }
- assertTrue("Wrong max for " + result + " = " + values,
- result.length() == 0);
- }
-
- /**
- * @tests java.util.GregorianCalendar#getMinimum(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMinimum",
- args = {int.class}
- )
- public void test_getMinimumI() {
- // Test for method int java.util.GregorianCalendar.getMinimum(int)
- GregorianCalendar gc = new GregorianCalendar();
- assertEquals("Wrong minimum value for DAY_OF_MONTH", 1, gc
- .getMinimum(Calendar.DAY_OF_MONTH));
- assertTrue("Wrong minimum value for MONTH", gc
- .getMinimum(Calendar.MONTH) == Calendar.JANUARY);
- assertEquals("Wrong minimum value for HOUR_OF_DAY", 0, gc
- .getMinimum(Calendar.HOUR_OF_DAY));
- assertEquals("Wrong minimum value for HOUR",
- 0, gc.getMinimum(Calendar.HOUR));
-
- BitSet result = new BitSet();
- int[] min = { 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, -46800000,
- 0 };
- for (int i = 0; i < min.length; i++) {
- if (gc.getMinimum(i) != min[i])
- result.set(i);
- }
- assertTrue("Wrong min for " + result, result.length() == 0);
- }
-
- /**
- * @tests java.util.GregorianCalendar#isLeapYear(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isLeapYear",
- args = {int.class}
- )
- public void test_isLeapYearI() {
- // Test for method boolean java.util.GregorianCalendar.isLeapYear(int)
- GregorianCalendar gc = new GregorianCalendar(1998, 11, 6);
- assertTrue("Returned incorrect value for leap year", !gc
- .isLeapYear(1998));
- assertTrue("Returned incorrect value for leap year", gc
- .isLeapYear(2000));
-
- }
-
- /**
- * @tests java.util.GregorianCalendar#roll(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "roll",
- args = {int.class, int.class}
- )
- public void test_rollII() {
- // Test for method void java.util.GregorianCalendar.roll(int, int)
- GregorianCalendar gc = new GregorianCalendar(1972, Calendar.OCTOBER, 8,
- 2, 5, 0);
- gc.roll(Calendar.DAY_OF_MONTH, -1);
- assertTrue("Failed to roll DAY_OF_MONTH down by 1", gc
- .equals(new GregorianCalendar(1972, Calendar.OCTOBER, 7, 2, 5,
- 0)));
- gc = new GregorianCalendar(1972, Calendar.OCTOBER, 8, 2, 5, 0);
- gc.roll(Calendar.DAY_OF_MONTH, 25);
- assertTrue("Failed to roll DAY_OF_MONTH up by 25", gc
- .equals(new GregorianCalendar(1972, Calendar.OCTOBER, 2, 2, 5,
- 0)));
- gc = new GregorianCalendar(1972, Calendar.OCTOBER, 8, 2, 5, 0);
- gc.roll(Calendar.DAY_OF_MONTH, -10);
- assertTrue("Failed to roll DAY_OF_MONTH down by 10", gc
- .equals(new GregorianCalendar(1972, Calendar.OCTOBER, 29, 2, 5,
- 0)));
- }
-
- /**
- * @tests java.util.GregorianCalendar#roll(int, boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "roll",
- args = {int.class, boolean.class}
- )
- public void test_rollIZ() {
- // Test for method void java.util.GregorianCalendar.roll(int, boolean)
- GregorianCalendar gc = new GregorianCalendar(1972, Calendar.OCTOBER,
- 13, 19, 9, 59);
- gc.roll(Calendar.DAY_OF_MONTH, false);
- assertTrue("Failed to roll day_of_month down", gc
- .equals(new GregorianCalendar(1972, Calendar.OCTOBER, 12, 19,
- 9, 59)));
- gc = new GregorianCalendar(1972, Calendar.OCTOBER, 13, 19, 9, 59);
- gc.roll(Calendar.DAY_OF_MONTH, true);
- assertTrue("Failed to roll day_of_month up", gc
- .equals(new GregorianCalendar(1972, Calendar.OCTOBER, 14, 19,
- 9, 59)));
- gc = new GregorianCalendar(1972, Calendar.OCTOBER, 31, 19, 9, 59);
- gc.roll(Calendar.DAY_OF_MONTH, true);
- assertTrue("Failed to roll day_of_month up", gc
- .equals(new GregorianCalendar(1972, Calendar.OCTOBER, 1, 19, 9,
- 59)));
-
- GregorianCalendar cal = new GregorianCalendar();
- int result;
- try {
- cal.roll(Calendar.ZONE_OFFSET, true);
- result = 0;
- } catch (IllegalArgumentException e) {
- result = 1;
- }
- assertEquals("ZONE_OFFSET roll", 1, result);
- try {
- cal.roll(Calendar.DST_OFFSET, true);
- result = 0;
- } catch (IllegalArgumentException e) {
- result = 1;
- }
- assertEquals("ZONE_OFFSET roll", 1, result);
-
- cal.set(2004, Calendar.DECEMBER, 31, 5, 0, 0);
- cal.roll(Calendar.WEEK_OF_YEAR, true);
- assertTrue("Wrong year: " + cal.getTime(),
- cal.get(Calendar.YEAR) == 2004);
- assertTrue("Wrong month: " + cal.getTime(),
- cal.get(Calendar.MONTH) == Calendar.JANUARY);
- assertTrue("Wrong date: " + cal.getTime(), cal.get(Calendar.DATE) == 9);
- }
-
- /**
- * @tests java.util.GregorianCalendar#setGregorianChange(java.util.Date)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setGregorianChange",
- args = {java.util.Date.class}
- )
- public void test_setGregorianChangeLjava_util_Date() {
- // Test for method void
- // java.util.GregorianCalendar.setGregorianChange(java.util.Date)
- GregorianCalendar gc1 = new GregorianCalendar(1582, Calendar.OCTOBER,
- 4, 0, 0);
- GregorianCalendar gc2 = new GregorianCalendar(1972, Calendar.OCTOBER,
- 13, 0, 0);
- gc1.setGregorianChange(gc2.getTime());
- assertTrue("Returned incorrect value", gc2.getTime().equals(
- gc1.getGregorianChange()));
- }
-
- /**
- * @tests java.util.GregorianCalendar#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
-
- // Regression for HARMONY-498
- GregorianCalendar gCalend = new GregorianCalendar();
-
- gCalend.set(Calendar.MILLISECOND, 0);
- int dayOfMonth = gCalend.get(Calendar.DAY_OF_MONTH);
-
- // create clone object and change date
- GregorianCalendar gCalendClone = (GregorianCalendar) gCalend.clone();
- gCalendClone.add(Calendar.DATE, 1);
-
- assertEquals("Before", dayOfMonth, gCalend.get(Calendar.DAY_OF_MONTH));
- gCalend.set(Calendar.MILLISECOND, 0);//changes nothing
- assertEquals("After", dayOfMonth, gCalend.get(Calendar.DAY_OF_MONTH));
- }
-
- /**
- * @tests java.util.GregorianCalendar#getMinimalDaysInFirstWeek()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMinimalDaysInFirstWeek",
- args = {}
- )
- @KnownFailure("Looks like there're some mistakes in timezones and/or locales data")
- public void test_getMinimalDaysInFirstWeek() {
- // Regression for Harmony-1037
- GregorianCalendar g = new GregorianCalendar(TimeZone
- .getTimeZone("Paris/France"), new Locale("en", "GB"));
- int minimalDaysInFirstWeek = g.getMinimalDaysInFirstWeek();
- assertEquals(4, minimalDaysInFirstWeek);
-
- g = new GregorianCalendar(TimeZone.getTimeZone("Paris/France"),
- new Locale("fr"));
- minimalDaysInFirstWeek = g.getMinimalDaysInFirstWeek();
- assertEquals(4, minimalDaysInFirstWeek);
-
- g = new GregorianCalendar(TimeZone.getTimeZone("Europe/London"),
- new Locale("fr", "CA"));
- minimalDaysInFirstWeek = g.getMinimalDaysInFirstWeek();
- assertEquals(1, minimalDaysInFirstWeek);
- }
-
- /**
- * @tests java.util.GregorianCalendar#computeTime()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Checks computeTime indirectly.",
- method = "computeTime",
- args = {}
- )
- public void test_computeTime() {
-
- // Regression for Harmony-493
- GregorianCalendar g = new GregorianCalendar(
- TimeZone.getTimeZone("Europe/London"),
- new Locale("en", "GB")
- );
- g.clear();
- g.set(2006, 02, 26, 01, 50, 00);
- assertEquals(1143337800000L, g.getTimeInMillis());
-
- GregorianCalendar g1 = new GregorianCalendar(
- TimeZone.getTimeZone("Europe/Moscow")
- );
- g1.clear();
- g1.set(2006, 02, 26, 02, 20, 00); // in the DST transition interval
- assertEquals(1143328800000L, g1.getTimeInMillis());
- assertEquals(3, g1.get(Calendar.HOUR_OF_DAY));
- g1.clear();
- g1.set(2006, 9, 29, 02, 50, 00); // transition from DST
- assertEquals(1162079400000L, g1.getTimeInMillis());
- assertEquals(2, g1.get(Calendar.HOUR_OF_DAY));
- // End of regression test
-
- g1.set(2006, -9, 29, 02, 50, 00); // transition from DST
- g1.setLenient(false);
-
- try {
- g1.getTimeInMillis();
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Checks computeFields indirectly.",
- method = "computeFields",
- args = {}
- )
- public void test_computeFields() {
- GregorianCalendar g = new GregorianCalendar(
- TimeZone.getTimeZone("Europe/London"),
- new Locale("en", "GB")
- );
- g.clear();
- g.setTimeInMillis(1222185600225L);
- assertEquals(1, g.get(Calendar.ERA));
- assertEquals(2008, g.get(Calendar.YEAR));
- assertEquals(Calendar.SEPTEMBER, g.get(Calendar.MONTH));
- assertEquals(23, g.get(Calendar.DAY_OF_MONTH));
- assertEquals(17, g.get(Calendar.HOUR_OF_DAY));
- assertEquals(0, g.get(Calendar.MINUTE));
- }
-
- /**
- * @tests java.util.GregorianCalendar#get(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ArrayIndexOutOfBoundsException.",
- method = "get",
- args = {int.class}
- )
- @SuppressWarnings("deprecation")
- public void test_getI() {
- // Regression test for HARMONY-2959
- Date date = new Date(Date.parse("Jan 15 00:00:01 GMT 2000"));
- GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
- gc.setGregorianChange(date);
- gc.setTimeInMillis(Date.parse("Dec 24 00:00:01 GMT 2000"));
- assertEquals(346, gc.get(Calendar.DAY_OF_YEAR));
-
- // Regression test for HARMONY-3003
- date = new Date(Date.parse("Feb 28 00:00:01 GMT 2000"));
- gc = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
- gc.setGregorianChange(date);
- gc.setTimeInMillis(Date.parse("Dec 1 00:00:01 GMT 2000"));
- assertEquals(1, gc.get(Calendar.DAY_OF_MONTH));
- assertEquals(11, gc.get(Calendar.MONTH));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- GregorianCalendar g = new GregorianCalendar(
- TimeZone.getTimeZone("Europe/London"),
- new Locale("en", "GB")
- );
- g.clear();
- g.setTimeInMillis(1222185600225L);
-
- GregorianCalendar g1 = new GregorianCalendar(
- TimeZone.getTimeZone("Europe/Moscow"));
- g1.clear();
- g1.set(2008, Calendar.SEPTEMBER, 23, 18, 0, 0);
- assertNotSame(g.hashCode(), g1.hashCode());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setFirstDayOfWeek",
- args = {int.class}
- )
- public void test_setFirstDayOfWeekI() {
- GregorianCalendar g = new GregorianCalendar(
- TimeZone.getTimeZone("Europe/London"),
- new Locale("en", "GB"));
-
- for (int i = 0; i < 10; i++) {
- g.setFirstDayOfWeek(i);
- assertEquals(i, g.getFirstDayOfWeek());
- }
- g.setLenient(false);
- g.setFirstDayOfWeek(10);
- g.setFirstDayOfWeek(-10);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setMinimalDaysInFirstWeek",
- args = {int.class}
- )
- public void test_setMinimalDaysInFirstWeekI() {
- GregorianCalendar g = new GregorianCalendar(
- TimeZone.getTimeZone("Europe/London"),
- new Locale("en", "GB"));
-
- for (int i = 0; i < 10; i++) {
- g.setMinimalDaysInFirstWeek(i);
- assertEquals(i, g.getMinimalDaysInFirstWeek());
- }
- g.setLenient(false);
- g.setMinimalDaysInFirstWeek(10);
- g.setMinimalDaysInFirstWeek(-10);
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- Locale.setDefault(Locale.US);
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/HashMapTest.java b/luni/src/test/java/tests/api/java/util/HashMapTest.java
deleted file mode 100644
index 6a0b8e2..0000000
--- a/luni/src/test/java/tests/api/java/util/HashMapTest.java
+++ /dev/null
@@ -1,640 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.AbstractMap;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
-import tests.support.Support_MapTest2;
-import tests.support.Support_UnmodifiableCollectionTest;
-
-@TestTargetClass(HashMap.class)
-public class HashMapTest extends junit.framework.TestCase {
- class MockMap extends AbstractMap {
- public Set entrySet() {
- return null;
- }
- public int size(){
- return 0;
- }
- }
-
- private static class MockMapNull extends AbstractMap {
- public Set entrySet() {
- return null;
- }
-
- public int size() {
- return 10;
- }
- }
-
- HashMap hm;
-
- final static int hmSize = 1000;
-
- static Object[] objArray;
-
- static Object[] objArray2;
- {
- objArray = new Object[hmSize];
- objArray2 = new Object[hmSize];
- for (int i = 0; i < objArray.length; i++) {
- objArray[i] = new Integer(i);
- objArray2[i] = objArray[i].toString();
- }
- }
-
- /**
- * @tests java.util.HashMap#HashMap()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "HashMap",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.HashMap()
- new Support_MapTest2(new HashMap()).runTest();
-
- HashMap hm2 = new HashMap();
- assertEquals("Created incorrect HashMap", 0, hm2.size());
- }
-
- /**
- * @tests java.util.HashMap#HashMap(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "HashMap",
- args = {int.class}
- )
- public void test_ConstructorI() {
- // Test for method java.util.HashMap(int)
- HashMap hm2 = new HashMap(5);
- assertEquals("Created incorrect HashMap", 0, hm2.size());
- try {
- new HashMap(-1);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- HashMap empty = new HashMap(0);
- assertNull("Empty hashmap access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
- }
-
- /**
- * @tests java.util.HashMap#HashMap(int, float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "HashMap",
- args = {int.class, float.class}
- )
- public void test_ConstructorIF() {
- // Test for method java.util.HashMap(int, float)
- HashMap hm2 = new HashMap(5, (float) 0.5);
- assertEquals("Created incorrect HashMap", 0, hm2.size());
- try {
- new HashMap(0, 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- HashMap empty = new HashMap(0, 0.75f);
- assertNull("Empty hashtable access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
- }
-
- /**
- * @tests java.util.HashMap#HashMap(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "HashMap",
- args = {java.util.Map.class}
- )
- public void test_ConstructorLjava_util_Map() {
- // Test for method java.util.HashMap(java.util.Map)
- Map myMap = new TreeMap();
- for (int counter = 0; counter < hmSize; counter++)
- myMap.put(objArray2[counter], objArray[counter]);
- HashMap hm2 = new HashMap(myMap);
- for (int counter = 0; counter < hmSize; counter++)
- assertTrue("Failed to construct correct HashMap", hm
- .get(objArray2[counter]) == hm2.get(objArray2[counter]));
-
- try {
- Map mockMap = new MockMap();
- hm = new HashMap(mockMap);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- //empty
- }
- }
-
- /**
- * @tests java.util.HashMap#clear()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- // Test for method void java.util.HashMap.clear()
- hm.clear();
- assertEquals("Clear failed to reset size", 0, hm.size());
- for (int i = 0; i < hmSize; i++)
- assertNull("Failed to clear all elements",
- hm.get(objArray2[i]));
-
- }
-
- /**
- * @tests java.util.HashMap#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- // Test for method java.lang.Object java.util.HashMap.clone()
- HashMap hm2 = (HashMap) hm.clone();
- assertTrue("Clone answered equivalent HashMap", hm2 != hm);
- for (int counter = 0; counter < hmSize; counter++)
- assertTrue("Clone answered unequal HashMap", hm
- .get(objArray2[counter]) == hm2.get(objArray2[counter]));
-
- HashMap map = new HashMap();
- map.put("key", "value");
- // get the keySet() and values() on the original Map
- Set keys = map.keySet();
- Collection values = map.values();
- assertEquals("values() does not work",
- "value", values.iterator().next());
- assertEquals("keySet() does not work",
- "key", keys.iterator().next());
- AbstractMap map2 = (AbstractMap) map.clone();
- map2.put("key", "value2");
- Collection values2 = map2.values();
- assertTrue("values() is identical", values2 != values);
- // values() and keySet() on the cloned() map should be different
- assertEquals("values() was not cloned",
- "value2", values2.iterator().next());
- map2.clear();
- map2.put("key2", "value3");
- Set key2 = map2.keySet();
- assertTrue("keySet() is identical", key2 != keys);
- assertEquals("keySet() was not cloned",
- "key2", key2.iterator().next());
-
- // regresion test for HARMONY-4603
- HashMap hashmap = new HashMap();
- MockClonable mock = new MockClonable(1);
- hashmap.put(1, mock);
- assertEquals(1, ((MockClonable) hashmap.get(1)).i);
- HashMap hm3 = (HashMap)hashmap.clone();
- assertEquals(1, ((MockClonable) hm3.get(1)).i);
- mock.i = 0;
- assertEquals(0, ((MockClonable) hashmap.get(1)).i);
- assertEquals(0, ((MockClonable) hm3.get(1)).i);
- }
-
- /**
- * @tests java.util.HashMap#containsKey(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "containsKey",
- args = {java.lang.Object.class}
- )
- public void test_containsKeyLjava_lang_Object() {
- // Test for method boolean
- // java.util.HashMap.containsKey(java.lang.Object)
- assertTrue("Returned false for valid key", hm.containsKey(new Integer(
- 876).toString()));
- assertTrue("Returned true for invalid key", !hm.containsKey("KKDKDKD"));
-
- HashMap m = new HashMap();
- m.put(null, "test");
- assertTrue("Failed with null key", m.containsKey(null));
- assertTrue("Failed with missing key matching null hash", !m
- .containsKey(new Integer(0)));
- }
-
- /**
- * @tests java.util.HashMap#containsValue(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "containsValue",
- args = {java.lang.Object.class}
- )
- public void test_containsValueLjava_lang_Object() {
- // Test for method boolean
- // java.util.HashMap.containsValue(java.lang.Object)
- assertTrue("Returned false for valid value", hm
- .containsValue(new Integer(875)));
- assertTrue("Returned true for invalid valie", !hm
- .containsValue(new Integer(-9)));
- }
-
- /**
- * @tests java.util.HashMap#entrySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "entrySet",
- args = {}
- )
- public void test_entrySet() {
- // Test for method java.util.Set java.util.HashMap.entrySet()
- Set s = hm.entrySet();
- Iterator i = s.iterator();
- assertTrue("Returned set of incorrect size", hm.size() == s.size());
- while (i.hasNext()) {
- Map.Entry m = (Map.Entry) i.next();
- assertTrue("Returned incorrect entry set", hm.containsKey(m
- .getKey())
- && hm.containsValue(m.getValue()));
- }
- }
-
- /**
- * @tests java.util.HashMap#get(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {java.lang.Object.class}
- )
- public void test_getLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.HashMap.get(java.lang.Object)
- assertNull("Get returned non-null for non existent key",
- hm.get("T"));
- hm.put("T", "HELLO");
- assertEquals("Get returned incorrect value for existing key", "HELLO", hm.get("T")
- );
-
- HashMap m = new HashMap();
- m.put(null, "test");
- assertEquals("Failed with null key", "test", m.get(null));
- assertNull("Failed with missing key matching null hash", m
- .get(new Integer(0)));
-
- // Regression for HARMONY-206
- ReusableKey k = new ReusableKey();
- HashMap map = new HashMap();
- k.setKey(1);
- map.put(k, "value1");
-
- k.setKey(18);
- assertNull(map.get(k));
-
- k.setKey(17);
- assertNull(map.get(k));
- }
-
- /**
- * @tests java.util.HashMap#isEmpty()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isEmpty",
- args = {}
- )
- public void test_isEmpty() {
- // Test for method boolean java.util.HashMap.isEmpty()
- assertTrue("Returned false for new map", new HashMap().isEmpty());
- assertTrue("Returned true for non-empty", !hm.isEmpty());
- }
-
- /**
- * @tests java.util.HashMap#keySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "keySet",
- args = {}
- )
- public void test_keySet() {
- // Test for method java.util.Set java.util.HashMap.keySet()
- Set s = hm.keySet();
- assertTrue("Returned set of incorrect size()", s.size() == hm.size());
- for (int i = 0; i < objArray.length; i++)
- assertTrue("Returned set does not contain all keys", s
- .contains(objArray[i].toString()));
-
- HashMap m = new HashMap();
- m.put(null, "test");
- assertTrue("Failed with null key", m.keySet().contains(null));
- assertNull("Failed with null key", m.keySet().iterator().next());
-
- Map map = new HashMap(101);
- map.put(new Integer(1), "1");
- map.put(new Integer(102), "102");
- map.put(new Integer(203), "203");
- Iterator it = map.keySet().iterator();
- Integer remove1 = (Integer) it.next();
- it.hasNext();
- it.remove();
- Integer remove2 = (Integer) it.next();
- it.remove();
- ArrayList list = new ArrayList(Arrays.asList(new Integer[] {
- new Integer(1), new Integer(102), new Integer(203) }));
- list.remove(remove1);
- list.remove(remove2);
- assertTrue("Wrong result", it.next().equals(list.get(0)));
- assertEquals("Wrong size", 1, map.size());
- assertTrue("Wrong contents", map.keySet().iterator().next().equals(
- list.get(0)));
-
- Map map2 = new HashMap(101);
- map2.put(new Integer(1), "1");
- map2.put(new Integer(4), "4");
- Iterator it2 = map2.keySet().iterator();
- Integer remove3 = (Integer) it2.next();
- Integer next;
- if (remove3.intValue() == 1)
- next = new Integer(4);
- else
- next = new Integer(1);
- it2.hasNext();
- it2.remove();
- assertTrue("Wrong result 2", it2.next().equals(next));
- assertEquals("Wrong size 2", 1, map2.size());
- assertTrue("Wrong contents 2", map2.keySet().iterator().next().equals(
- next));
- }
-
- /**
- * @tests java.util.HashMap#put(java.lang.Object, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "put",
- args = {java.lang.Object.class, java.lang.Object.class}
- )
- public void test_putLjava_lang_ObjectLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.HashMap.put(java.lang.Object, java.lang.Object)
- hm.put("KEY", "VALUE");
- assertEquals("Failed to install key/value pair",
- "VALUE", hm.get("KEY"));
-
- HashMap m = new HashMap();
- m.put(new Short((short) 0), "short");
- m.put(null, "test");
- m.put(new Integer(0), "int");
- assertEquals("Failed adding to bucket containing null", "short", m.get(
- new Short((short) 0)));
- assertEquals("Failed adding to bucket containing null2", "int", m.get(
- new Integer(0)));
- }
-
- /**
- * @tests java.util.HashMap#putAll(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify NullPointerException.",
- method = "putAll",
- args = {java.util.Map.class}
- )
- public void test_putAllLjava_util_Map() {
- // Test for method void java.util.HashMap.putAll(java.util.Map)
- HashMap hm2 = new HashMap();
- hm2.putAll(hm);
- for (int i = 0; i < 1000; i++)
- assertTrue("Failed to clear all elements", hm2.get(
- new Integer(i).toString()).equals((new Integer(i))));
-
- Map mockMap = new MockMap();
- hm2 = new HashMap();
- hm2.putAll(mockMap);
- assertEquals("Size should be 0", 0, hm2.size());
- }
-
- /**
- * @tests java.util.HashMap#putAll(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "putAll",
- args = {java.util.Map.class}
- )
- public void test_putAllLjava_util_Map_Null() {
- HashMap hashMap = new HashMap();
- try {
- hashMap.putAll(new MockMapNull());
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected.
- }
-
- try {
- hashMap = new HashMap(new MockMapNull());
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected.
- }
- }
-
- /**
- * @tests java.util.HashMap#remove(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_removeLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.HashMap.remove(java.lang.Object)
- int size = hm.size();
- Integer y = new Integer(9);
- Integer x = ((Integer) hm.remove(y.toString()));
- assertTrue("Remove returned incorrect value", x.equals(new Integer(9)));
- assertNull("Failed to remove given key", hm.get(new Integer(9)));
- assertTrue("Failed to decrement size", hm.size() == (size - 1));
- assertNull("Remove of non-existent key returned non-null", hm
- .remove("LCLCLC"));
-
- HashMap m = new HashMap();
- m.put(null, "test");
- assertNull("Failed with same hash as null",
- m.remove(new Integer(0)));
- assertEquals("Failed with null key", "test", m.remove(null));
- }
-
- /**
- * @tests java.util.HashMap#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- public void test_size() {
- // Test for method int java.util.HashMap.size()
- assertTrue("Returned incorrect size",
- hm.size() == (objArray.length + 2));
- }
-
- /**
- * @tests java.util.HashMap#values()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
- public void test_values() {
- // Test for method java.util.Collection java.util.HashMap.values()
- Collection c = hm.values();
- assertTrue("Returned collection of incorrect size()", c.size() == hm
- .size());
- for (int i = 0; i < objArray.length; i++)
- assertTrue("Returned collection does not contain all keys", c
- .contains(objArray[i]));
-
- HashMap myHashMap = new HashMap();
- for (int i = 0; i < 100; i++)
- myHashMap.put(objArray2[i], objArray[i]);
- Collection values = myHashMap.values();
- new Support_UnmodifiableCollectionTest(
- "Test Returned Collection From HashMap.values()", values)
- .runTest();
- values.remove(new Integer(0));
- assertTrue(
- "Removing from the values collection should remove from the original map",
- !myHashMap.containsValue(new Integer(0)));
-
- }
-
- static class ReusableKey {
- private int key = 0;
-
- public void setKey(int key) {
- this.key = key;
- }
-
- public int hashCode() {
- return key;
- }
-
- public boolean equals(Object o) {
- if (o == this) {
- return true;
- }
- if (!(o instanceof ReusableKey)) {
- return false;
- }
- return key == ((ReusableKey) o).key;
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_Map_Entry_hashCode() {
- //Related to HARMONY-403
- HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(10);
- Integer key = new Integer(1);
- Integer val = new Integer(2);
- map.put(key, val);
- int expected = key.hashCode() ^ val.hashCode();
- assertEquals(expected, map.hashCode());
- key = new Integer(4);
- val = new Integer(8);
- map.put(key, val);
- expected += key.hashCode() ^ val.hashCode();
- assertEquals(expected, map.hashCode());
- }
-
- class MockClonable implements Cloneable{
- public int i;
-
- public MockClonable(int i) {
- this.i = i;
- }
-
- @Override
- protected Object clone() throws CloneNotSupportedException {
- return new MockClonable(i);
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- hm = new HashMap();
- for (int i = 0; i < objArray.length; i++)
- hm.put(objArray2[i], objArray[i]);
- hm.put("test", null);
- hm.put(null, "test");
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/HashSetTest.java b/luni/src/test/java/tests/api/java/util/HashSetTest.java
deleted file mode 100644
index 7eda101..0000000
--- a/luni/src/test/java/tests/api/java/util/HashSetTest.java
+++ /dev/null
@@ -1,341 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-import java.io.ObjectOutputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.Serializable;
-import java.lang.reflect.Method;
-import java.lang.reflect.InvocationTargetException;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-@TestTargetClass(HashSet.class)
-public class HashSetTest extends junit.framework.TestCase {
-
- HashSet hs;
-
- static Object[] objArray;
- {
- objArray = new Object[1000];
- for (int i = 0; i < objArray.length; i++)
- objArray[i] = new Integer(i);
- }
-
- /**
- * @tests java.util.HashSet#HashSet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "HashSet",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.HashSet()
- HashSet hs2 = new HashSet();
- assertEquals("Created incorrect HashSet", 0, hs2.size());
- }
-
- /**
- * @tests java.util.HashSet#HashSet(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "HashSet",
- args = {int.class}
- )
- public void test_ConstructorI() {
- // Test for method java.util.HashSet(int)
- HashSet hs2 = new HashSet(5);
- assertEquals("Created incorrect HashSet", 0, hs2.size());
- try {
- new HashSet(-1);
- } catch (IllegalArgumentException e) {
- return;
- }
- fail(
- "Failed to throw IllegalArgumentException for capacity < 0");
- }
-
- /**
- * @tests java.util.HashSet#HashSet(int, float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "HashSet",
- args = {int.class, float.class}
- )
- public void test_ConstructorIF() {
- // Test for method java.util.HashSet(int, float)
- HashSet hs2 = new HashSet(5, (float) 0.5);
- assertEquals("Created incorrect HashSet", 0, hs2.size());
- try {
- new HashSet(0, 0);
- } catch (IllegalArgumentException e) {
- return;
- }
- fail(
- "Failed to throw IllegalArgumentException for initial load factor <= 0");
- }
-
- /**
- * @tests java.util.HashSet#HashSet(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "HashSet",
- args = {java.util.Collection.class}
- )
- public void test_ConstructorLjava_util_Collection() {
- // Test for method java.util.HashSet(java.util.Collection)
- HashSet hs2 = new HashSet(Arrays.asList(objArray));
- for (int counter = 0; counter < objArray.length; counter++)
- assertTrue("HashSet does not contain correct elements", hs
- .contains(objArray[counter]));
- assertTrue("HashSet created from collection incorrect size",
- hs2.size() == objArray.length);
-
- try {
- new HashSet(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.HashSet#add(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "add",
- args = {java.lang.Object.class}
- )
- public void test_addLjava_lang_Object() {
- // Test for method boolean java.util.HashSet.add(java.lang.Object)
- int size = hs.size();
- hs.add(new Integer(8));
- assertTrue("Added element already contained by set", hs.size() == size);
- hs.add(new Integer(-9));
- assertTrue("Failed to increment set size after add",
- hs.size() == size + 1);
- assertTrue("Failed to add element to set", hs.contains(new Integer(-9)));
- }
-
- /**
- * @tests java.util.HashSet#clear()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- // Test for method void java.util.HashSet.clear()
- Set orgSet = (Set) hs.clone();
- hs.clear();
- Iterator i = orgSet.iterator();
- assertEquals("Returned non-zero size after clear", 0, hs.size());
- while (i.hasNext())
- assertTrue("Failed to clear set", !hs.contains(i.next()));
- }
-
- /**
- * @tests java.util.HashSet#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- // Test for method java.lang.Object java.util.HashSet.clone()
- HashSet hs2 = (HashSet) hs.clone();
- assertTrue("clone returned an equivalent HashSet", hs != hs2);
- assertTrue("clone did not return an equal HashSet", hs.equals(hs2));
- }
-
- /**
- * @tests java.util.HashSet#contains(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "contains",
- args = {java.lang.Object.class}
- )
- public void test_containsLjava_lang_Object() {
- // Test for method boolean java.util.HashSet.contains(java.lang.Object)
- assertTrue("Returned false for valid object", hs.contains(objArray[90]));
- assertTrue("Returned true for invalid Object", !hs
- .contains(new Object()));
-
- HashSet s = new HashSet();
- s.add(null);
- assertTrue("Cannot handle null", s.contains(null));
- }
-
- /**
- * @tests java.util.HashSet#isEmpty()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isEmpty",
- args = {}
- )
- public void test_isEmpty() {
- // Test for method boolean java.util.HashSet.isEmpty()
- assertTrue("Empty set returned false", new HashSet().isEmpty());
- assertTrue("Non-empty set returned true", !hs.isEmpty());
- }
-
- /**
- * @tests java.util.HashSet#iterator()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "iterator",
- args = {}
- )
- public void test_iterator() {
- // Test for method java.util.Iterator java.util.HashSet.iterator()
- Iterator i = hs.iterator();
- int x = 0;
- while (i.hasNext()) {
- assertTrue("Failed to iterate over all elements", hs.contains(i
- .next()));
- ++x;
- }
- assertTrue("Returned iteration of incorrect size", hs.size() == x);
-
- HashSet s = new HashSet();
- s.add(null);
- assertNull("Cannot handle null", s.iterator().next());
- }
-
- /**
- * @tests java.util.HashSet#remove(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_removeLjava_lang_Object() {
- // Test for method boolean java.util.HashSet.remove(java.lang.Object)
- int size = hs.size();
- hs.remove(new Integer(98));
- assertTrue("Failed to remove element", !hs.contains(new Integer(98)));
- assertTrue("Failed to decrement set size", hs.size() == size - 1);
-
- HashSet s = new HashSet();
- s.add(null);
- assertTrue("Cannot handle null", s.remove(null));
- assertFalse(hs.remove(new Integer(-98)));
- }
-
- /**
- * @tests java.util.HashSet#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- public void test_size() {
- // Test for method int java.util.HashSet.size()
- assertTrue("Returned incorrect size", hs.size() == (objArray.length + 1));
- hs.clear();
- assertEquals("Cleared set returned non-zero size", 0, hs.size());
- }
-
- /**
- * @tests java.util.HashSet#SerializationTest
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- )
- })
- public void test_Serialization() throws Exception{
- HashSet<String> hs = new HashSet<String>();
- hs.add("hello");
- hs.add("world");
- SerializationTest.verifySelf(hs, comparator);
- SerializationTest.verifyGolden(this, hs, comparator);
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- hs = new HashSet();
- for (int i = 0; i < objArray.length; i++)
- hs.add(objArray[i]);
- hs.add(null);
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-
- private static final SerializationTest.SerializableAssert comparator = new
- SerializationTest.SerializableAssert() {
- public void assertDeserialized(Serializable initial, Serializable deserialized) {
- HashSet<String> initialHs = (HashSet<String>) initial;
- HashSet<String> deseriaHs = (HashSet<String>) deserialized;
- assertEquals("should be equal", initialHs.size(), deseriaHs.size());
- assertEquals("should be equal", initialHs, deseriaHs);
- }
-
- };
-}
diff --git a/luni/src/test/java/tests/api/java/util/HashtableTest.java b/luni/src/test/java/tests/api/java/util/HashtableTest.java
deleted file mode 100644
index 00b6227..0000000
--- a/luni/src/test/java/tests/api/java/util/HashtableTest.java
+++ /dev/null
@@ -1,992 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.ConcurrentModificationException;
-import java.util.Enumeration;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.Set;
-import java.util.TreeMap;
-import java.util.Vector;
-
-import tests.api.java.util.HashMapTest.ReusableKey;
-import tests.support.Support_MapTest2;
-import tests.support.Support_UnmodifiableCollectionTest;
-
-@TestTargetClass(Hashtable.class)
-public class HashtableTest extends junit.framework.TestCase {
-
- private Hashtable ht10;
-
- private Hashtable ht100;
-
- private Hashtable htfull;
-
- private Vector keyVector;
-
- private Vector elmVector;
-
- private String h10sVal;
-
- /**
- * @tests java.util.Hashtable#Hashtable()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Hashtable",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.Hashtable()
- new Support_MapTest2(new Hashtable()).runTest();
-
- Hashtable h = new Hashtable();
-
- assertEquals("Created incorrect hashtable", 0, h.size());
- }
-
- /**
- * @tests java.util.Hashtable#Hashtable(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Hashtable",
- args = {int.class}
- )
- public void test_ConstructorI() {
- // Test for method java.util.Hashtable(int)
- Hashtable h = new Hashtable(9);
-
- assertEquals("Created incorrect hashtable", 0, h.size());
-
- Hashtable empty = new Hashtable(0);
- assertNull("Empty hashtable access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
-
- try {
- new Hashtable(-1);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Hashtable#Hashtable(int, float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Hashtable",
- args = {int.class, float.class}
- )
- public void test_ConstructorIF() {
- // Test for method java.util.Hashtable(int, float)
- Hashtable h = new java.util.Hashtable(10, 0.5f);
- assertEquals("Created incorrect hashtable", 0, h.size());
-
- Hashtable empty = new Hashtable(0, 0.75f);
- assertNull("Empty hashtable access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
-
- try {
- new Hashtable(-1, 0.75f);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new Hashtable(0, -0.75f);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Hashtable#Hashtable(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Hashtable",
- args = {java.util.Map.class}
- )
- public void test_ConstructorLjava_util_Map() {
- // Test for method java.util.Hashtable(java.util.Map)
- Map map = new TreeMap();
- Object firstVal = "Gabba";
- Object secondVal = new Integer(5);
- map.put("Gah", firstVal);
- map.put("Ooga", secondVal);
- Hashtable ht = new Hashtable(map);
- assertTrue("a) Incorrect Hashtable constructed",
- ht.get("Gah") == firstVal);
- assertTrue("b) Incorrect Hashtable constructed",
- ht.get("Ooga") == secondVal);
-
- try {
- new Hashtable(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Hashtable#clear()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- // Test for method void java.util.Hashtable.clear()
- Hashtable h = hashtableClone(htfull);
- h.clear();
- assertEquals("Hashtable was not cleared", 0, h.size());
- Enumeration el = h.elements();
- Enumeration keys = h.keys();
- assertTrue("Hashtable improperly cleared", !el.hasMoreElements()
- && !(keys.hasMoreElements()));
- }
-
- /**
- * @tests java.util.Hashtable#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- // Test for method java.lang.Object java.util.Hashtable.clone()
-
- Hashtable h = (Hashtable) htfull.clone();
- assertTrue("Clone different size than original", h.size() == htfull
- .size());
-
- Enumeration org = htfull.keys();
- Enumeration cpy = h.keys();
-
- String okey, ckey;
- while (org.hasMoreElements()) {
- assertTrue("Key comparison failed", (okey = (String) org
- .nextElement()).equals(ckey = (String) cpy.nextElement()));
- assertTrue("Value comparison failed", ((String) htfull.get(okey))
- .equals((String) h.get(ckey)));
- }
- assertTrue("Copy has more keys than original", !cpy.hasMoreElements());
- }
-
- /**
- * @tests java.util.Hashtable#contains(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "contains",
- args = {java.lang.Object.class}
- )
- public void test_containsLjava_lang_Object() {
- // Test for method boolean
- // java.util.Hashtable.contains(java.lang.Object)
- assertTrue("Element not found", ht10.contains("Val 7"));
- assertTrue("Invalid element found", !ht10.contains("ZZZZZZZZZZZZZZZZ"));
-
- try {
- ht10.contains(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Hashtable#containsKey(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "containsKey",
- args = {java.lang.Object.class}
- )
- public void test_containsKeyLjava_lang_Object() {
- // Test for method boolean
- // java.util.Hashtable.containsKey(java.lang.Object)
-
- assertTrue("Failed to find key", htfull.containsKey("FKey 4"));
- assertTrue("Failed to find key", !htfull.containsKey("FKey 99"));
-
- try {
- htfull.containsKey(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Hashtable#containsValue(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "containsValue",
- args = {java.lang.Object.class}
- )
- public void test_containsValueLjava_lang_Object() {
- // Test for method boolean
- // java.util.Hashtable.containsValue(java.lang.Object)
- Enumeration e = elmVector.elements();
- while (e.hasMoreElements())
- assertTrue("Returned false for valid value", ht10.containsValue(e
- .nextElement()));
- assertTrue("Returned true for invalid value", !ht10
- .containsValue(new Object()));
-
- try {
- ht10.containsValue(null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Hashtable#elements()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "elements",
- args = {}
- )
- public void test_elements() {
- // Test for method java.util.Enumeration java.util.Hashtable.elements()
- Enumeration elms = ht10.elements();
- int i = 0;
- while (elms.hasMoreElements()) {
- String s = (String) elms.nextElement();
- assertTrue("Missing key from enumeration", elmVector.contains(s));
- ++i;
- }
-
- assertEquals("All keys not retrieved", 10, ht10.size());
- }
-
- /**
- * @tests java.util.Hashtable#elements()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "elements",
- args = {}
- )
- public void test_elements_subtest0() {
- // this is the reference implementation behavior
- final Hashtable ht = new Hashtable(7);
- ht.put("1", "a");
- // these three elements hash to the same bucket in a 7 element Hashtable
- ht.put("2", "b");
- ht.put("9", "c");
- ht.put("12", "d");
- // Hashtable looks like:
- // 0: "1"
- // 1: "12" -> "9" -> "2"
- Enumeration en = ht.elements();
- // cache the first entry
- en.hasMoreElements();
- ht.remove("12");
- ht.remove("9");
- boolean exception = false;
- try {
- // cached "12"
- Object result = en.nextElement();
- assertNull("unexpected: " + result, result);
- // next is removed "9"
- result = en.nextElement();
- assertNull("unexpected: " + result, result);
- result = en.nextElement();
- assertTrue("unexpected: " + result, "b".equals(result));
- } catch (NoSuchElementException e) {
- exception = true;
- }
- assertTrue("unexpected NoSuchElementException", !exception);
- }
-
- /**
- * @tests java.util.Hashtable#entrySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "entrySet",
- args = {}
- )
- public void test_entrySet() {
- // Test for method java.util.Set java.util.Hashtable.entrySet()
- Set s = ht10.entrySet();
- Set s2 = new HashSet();
- Iterator i = s.iterator();
- while (i.hasNext())
- s2.add(((Map.Entry) i.next()).getValue());
- Enumeration e = elmVector.elements();
- while (e.hasMoreElements())
- assertTrue("Returned incorrect entry set", s2.contains(e
- .nextElement()));
-
- assertEquals("Not synchronized",
- "java.util.Collections$SynchronizedSet", s.getClass().getName());
-
- boolean exception = false;
- try {
- ((Map.Entry) ht10.entrySet().iterator().next()).setValue(null);
- } catch (NullPointerException e1) {
- exception = true;
- }
- assertTrue(
- "Should not be able to assign null to a Hashtable entrySet() Map.Entry",
- exception);
- }
-
- /**
- * @tests java.util.Hashtable#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean java.util.Hashtable.equals(java.lang.Object)
- Hashtable h = hashtableClone(ht10);
- assertTrue("Returned false for equal tables", ht10.equals(h));
- assertTrue("Returned true for unequal tables", !ht10.equals(htfull));
- }
-
- /**
- * @tests java.util.Hashtable#get(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {java.lang.Object.class}
- )
- public void test_getLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.Hashtable.get(java.lang.Object)
- Hashtable h = hashtableClone(htfull);
- assertEquals("Could not retrieve element", "FVal 2", ((String) h.get("FKey 2"))
- );
-
-
- // Regression for HARMONY-262
- ReusableKey k = new ReusableKey();
- Hashtable h2 = new Hashtable();
- k.setKey(1);
- h2.put(k, "value1");
-
- k.setKey(13);
- assertNull(h2.get(k));
-
- k.setKey(12);
- assertNull(h2.get(k));
-
- try {
- h2.get(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Hashtable#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- // Test for method int java.util.Hashtable.hashCode()
- Set entrySet = ht10.entrySet();
- Iterator iterator = entrySet.iterator();
- int expectedHash;
- for (expectedHash = 0; iterator.hasNext(); expectedHash += iterator
- .next().hashCode())
- ;
- assertTrue("Incorrect hashCode returned. Wanted: " + expectedHash
- + " got: " + ht10.hashCode(), expectedHash == ht10.hashCode());
- }
-
- /**
- * @tests java.util.Hashtable#isEmpty()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isEmpty",
- args = {}
- )
- public void test_isEmpty() {
- // Test for method boolean java.util.Hashtable.isEmpty()
-
- assertTrue("isEmpty returned incorrect value", !ht10.isEmpty());
- assertTrue("isEmpty returned incorrect value",
- new java.util.Hashtable().isEmpty());
-
- final Hashtable ht = new Hashtable();
- ht.put("0", "");
- Thread t1 = new Thread() {
- public void run() {
- while (!ht.isEmpty())
- ;
- ht.put("final", "");
- }
- };
- t1.start();
- for (int i = 1; i < 10000; i++) {
- synchronized (ht) {
- ht.remove(String.valueOf(i - 1));
- ht.put(String.valueOf(i), "");
- }
- int size;
- if ((size = ht.size()) != 1) {
- String result = "Size is not 1: " + size + " " + ht;
- // terminate the thread
- ht.clear();
- fail(result);
- }
- }
- // terminate the thread
- ht.clear();
- }
-
- /**
- * @tests java.util.Hashtable#keys()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "keys",
- args = {}
- )
- public void test_keys() {
- // Test for method java.util.Enumeration java.util.Hashtable.keys()
-
- Enumeration keys = ht10.keys();
- int i = 0;
- while (keys.hasMoreElements()) {
- String s = (String) keys.nextElement();
- assertTrue("Missing key from enumeration", keyVector.contains(s));
- ++i;
- }
-
- assertEquals("All keys not retrieved", 10, ht10.size());
- }
-
- /**
- * @tests java.util.Hashtable#keys()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "keys",
- args = {}
- )
- public void test_keys_subtest0() {
- // this is the reference implementation behavior
- final Hashtable ht = new Hashtable(3);
- ht.put("initial", "");
- Enumeration en = ht.keys();
- en.hasMoreElements();
- ht.remove("initial");
- boolean exception = false;
- try {
- Object result = en.nextElement();
- assertTrue("unexpected: " + result, "initial".equals(result));
- } catch (NoSuchElementException e) {
- exception = true;
- }
- assertTrue("unexpected NoSuchElementException", !exception);
- }
-
- /**
- * @tests java.util.Hashtable#keySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "keySet",
- args = {}
- )
- public void test_keySet() {
- // Test for method java.util.Set java.util.Hashtable.keySet()
- Set s = ht10.keySet();
- Enumeration e = keyVector.elements();
- while (e.hasMoreElements())
- assertTrue("Returned incorrect key set", s
- .contains(e.nextElement()));
-
- assertEquals("Not synchronized",
- "java.util.Collections$SynchronizedSet", s.getClass().getName());
-
- Map map = new Hashtable(101);
- map.put(new Integer(1), "1");
- map.put(new Integer(102), "102");
- map.put(new Integer(203), "203");
- Iterator it = map.keySet().iterator();
- Integer remove1 = (Integer) it.next();
- it.remove();
- Integer remove2 = (Integer) it.next();
- it.remove();
- ArrayList list = new ArrayList(Arrays.asList(new Integer[] {
- new Integer(1), new Integer(102), new Integer(203) }));
- list.remove(remove1);
- list.remove(remove2);
- assertTrue("Wrong result", it.next().equals(list.get(0)));
- assertEquals("Wrong size", 1, map.size());
- assertTrue("Wrong contents", map.keySet().iterator().next().equals(
- list.get(0)));
-
- Map map2 = new Hashtable(101);
- map2.put(new Integer(1), "1");
- map2.put(new Integer(4), "4");
- Iterator it2 = map2.keySet().iterator();
- Integer remove3 = (Integer) it2.next();
- Integer next;
- if (remove3.intValue() == 1)
- next = new Integer(4);
- else
- next = new Integer(1);
- it2.hasNext();
- it2.remove();
- assertTrue("Wrong result 2", it2.next().equals(next));
- assertEquals("Wrong size 2", 1, map2.size());
- assertTrue("Wrong contents 2", map2.keySet().iterator().next().equals(
- next));
- }
-
- /**
- * @tests java.util.Hashtable#keySet()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "keySet",
- args = {}
- )
- public void test_keySet_subtest0() {
- Set s1 = ht10.keySet();
- assertTrue("should contain key", s1.remove("Key 0"));
- assertTrue("should not contain key", !s1.remove("Key 0"));
-
- final int iterations = 10000;
- final Hashtable ht = new Hashtable();
- Thread t1 = new Thread() {
- public void run() {
- for (int i = 0; i < iterations; i++) {
- ht.put(String.valueOf(i), "");
- ht.remove(String.valueOf(i));
- }
- }
- };
- t1.start();
- Set set = ht.keySet();
- for (int i = 0; i < iterations; i++) {
- Iterator it = set.iterator();
- try {
- it.next();
- it.remove();
- int size;
- // ensure removing with the iterator doesn't corrupt the
- // Hashtable
- if ((size = ht.size()) < 0) {
- fail("invalid size: " + size);
- }
- } catch (NoSuchElementException e) {
- } catch (ConcurrentModificationException e) {
- }
- }
- }
-
- /**
- * @tests java.util.Hashtable#keySet()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "keySet",
- args = {}
- )
- public void test_keySet_subtest1() {
- // this is the reference implementation behavior
- final Hashtable ht = new Hashtable(7);
- ht.put("1", "a");
- // these three elements hash to the same bucket in a 7 element Hashtable
- ht.put("2", "b");
- ht.put("9", "c");
- ht.put("12", "d");
- // Hashtable looks like:
- // 0: "1"
- // 1: "12" -> "9" -> "2"
- Enumeration en = ht.elements();
- // cache the first entry
- en.hasMoreElements();
- Iterator it = ht.keySet().iterator();
- // this is mostly a copy of the test in test_elements_subtest0()
- // test removing with the iterator does not null the values
- while (it.hasNext()) {
- String key = (String) it.next();
- if ("12".equals(key) || "9".equals(key)) {
- it.remove();
- }
- }
- it.remove();
- boolean exception = false;
- try {
- // cached "12"
- Object result = en.nextElement();
- assertTrue("unexpected: " + result, "d".equals(result));
- // next is removed "9"
- result = en.nextElement();
- assertTrue("unexpected: " + result, "c".equals(result));
- result = en.nextElement();
- assertTrue("unexpected: " + result, "b".equals(result));
- } catch (NoSuchElementException e) {
- exception = true;
- }
- assertTrue("unexpected NoSuchElementException", !exception);
- }
-
- /**
- * @tests java.util.Hashtable#put(java.lang.Object, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "put",
- args = {java.lang.Object.class, java.lang.Object.class}
- )
- public void test_putLjava_lang_ObjectLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.Hashtable.put(java.lang.Object, java.lang.Object)
- Hashtable h = hashtableClone(ht100);
- Integer key = new Integer(100);
- h.put("Value 100", key);
- assertTrue("Key/Value not inserted", h.size() == 1 && (h.contains(key)));
-
- // Put into "full" table
- h = hashtableClone(htfull);
- h.put("Value 100", key);
- assertTrue("Key/Value not inserted into full table", h.size() == 8
- && (h.contains(key)));
-
- try {
- h.put(null, key);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- try {
- h.put("Value 100", null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Hashtable#putAll(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "putAll",
- args = {java.util.Map.class}
- )
- public void test_putAllLjava_util_Map() {
- // Test for method void java.util.Hashtable.putAll(java.util.Map)
- Hashtable h = new Hashtable();
- h.putAll(ht10);
- Enumeration e = keyVector.elements();
- while (e.hasMoreElements()) {
- Object x = e.nextElement();
- assertTrue("Failed to put all elements", h.get(x).equals(
- ht10.get(x)));
- }
-
- try {
- h.putAll(null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Hashtable#remove(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_removeLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.Hashtable.remove(java.lang.Object)
- Hashtable h = hashtableClone(htfull);
- Object k = h.remove("FKey 0");
- assertTrue("Remove failed", !h.containsKey("FKey 0") || k == null);
- assertNull(h.remove("FKey 0"));
-
- try {
- h.remove(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Hashtable#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- public void test_size() {
- // Test for method int java.util.Hashtable.size()
- assertTrue("Returned invalid size", ht10.size() == 10
- && (ht100.size() == 0));
-
- final Hashtable ht = new Hashtable();
- ht.put("0", "");
- Thread t1 = new Thread() {
- public void run() {
- while (ht.size() > 0)
- ;
- ht.put("final", "");
- }
- };
- t1.start();
- for (int i = 1; i < 10000; i++) {
- synchronized (ht) {
- ht.remove(String.valueOf(i - 1));
- ht.put(String.valueOf(i), "");
- }
- int size;
- if ((size = ht.size()) != 1) {
- String result = "Size is not 1: " + size + " " + ht;
- // terminate the thread
- ht.clear();
- fail(result);
- }
- }
- // terminate the thread
- ht.clear();
- }
-
- /**
- * @tests java.util.Hashtable#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.util.Hashtable.toString()
- Hashtable h = new Hashtable();
- assertEquals("Incorrect toString for Empty table",
- "{}", h.toString());
-
- h.put("one", "1");
- h.put("two", h);
- h.put(h, "3");
- h.put(h, h);
- String result = h.toString();
- assertTrue("should contain self ref", result.indexOf("(this") > -1);
- }
-
- /**
- * @tests java.util.Hashtable#values()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
- public void test_values() {
- // Test for method java.util.Collection java.util.Hashtable.values()
- Collection c = ht10.values();
- Enumeration e = elmVector.elements();
- while (e.hasMoreElements())
- assertTrue("Returned incorrect values", c.contains(e.nextElement()));
-
- assertEquals("Not synchronized",
- "java.util.Collections$SynchronizedCollection", c.getClass().getName());
-
- Hashtable myHashtable = new Hashtable();
- for (int i = 0; i < 100; i++)
- myHashtable.put(new Integer(i), new Integer(i));
- Collection values = myHashtable.values();
- new Support_UnmodifiableCollectionTest(
- "Test Returned Collection From Hashtable.values()", values)
- .runTest();
- values.remove(new Integer(0));
- assertTrue(
- "Removing from the values collection should remove from the original map",
- !myHashtable.containsValue(new Integer(0)));
- }
-
- /**
- * Regression Test for JIRA 2181
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "entrySet",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "remove",
- args = {java.lang.Object.class}
- )
- })
- public void test_entrySet_remove()
- {
- Hashtable<String,String> hashtable = new Hashtable<String,String>();
- hashtable.put("my.nonexistent.prop", "AAA");
- hashtable.put( "parse.error", "BBB" );
- Iterator<Map.Entry<String,String>> iterator =
- hashtable.entrySet().iterator();
- while(iterator.hasNext())
- {
- Map.Entry entry = iterator.next();
- final Object value = entry.getValue();
- if(value.equals("AAA"))
- {
- iterator.remove();
- }
- }
- assertFalse(hashtable.containsKey("my.nonexistent.prop"));
- }
-
- class Mock_Hashtable extends Hashtable {
- boolean flag = false;
-
- public Mock_Hashtable(int i) {
- super(i);
- }
-
- @Override
- protected void rehash() {
- flag = true;
- super.rehash();
- }
-
- public boolean isRehashed() {
- return flag;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "rehash",
- args = {}
- )
- public void test_rehash() {
- Mock_Hashtable mht = new Mock_Hashtable(5);
-
- assertFalse(mht.isRehashed());
- for(int i = 0; i < 10; i++) {
- mht.put(i, "New value");
- }
- assertTrue(mht.isRehashed());
- }
-
- protected Hashtable hashtableClone(Hashtable s) {
- return (Hashtable) s.clone();
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
-
- ht10 = new Hashtable(10);
- ht100 = new Hashtable(100);
- htfull = new Hashtable(10);
- keyVector = new Vector(10);
- elmVector = new Vector(10);
-
- for (int i = 0; i < 10; i++) {
- ht10.put("Key " + i, "Val " + i);
- keyVector.addElement("Key " + i);
- elmVector.addElement("Val " + i);
- }
-
- for (int i = 0; i < 7; i++)
- htfull.put("FKey " + i, "FVal " + i);
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/IdentityHashMapTest.java b/luni/src/test/java/tests/api/java/util/IdentityHashMapTest.java
deleted file mode 100644
index 02a4fe5..0000000
--- a/luni/src/test/java/tests/api/java/util/IdentityHashMapTest.java
+++ /dev/null
@@ -1,613 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.Serializable;
-import java.util.AbstractMap;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.IdentityHashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
-import tests.support.Support_MapTest2;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-@TestTargetClass(IdentityHashMap.class)
-public class IdentityHashMapTest extends junit.framework.TestCase {
- private static final String ID = "hello";
-
- class MockMap extends AbstractMap {
- public Set entrySet() {
- return null;
- }
- public int size(){
- return 0;
- }
- }
- /*
- * TODO: change all the statements testing the keys and values with equals()
- * method to check for reference equality instead
- */
-
- IdentityHashMap hm;
-
- final static int hmSize = 1000;
-
- static Object[] objArray;
-
- static Object[] objArray2;
- {
- objArray = new Object[hmSize];
- objArray2 = new Object[hmSize];
- for (int i = 0; i < objArray.length; i++) {
- objArray[i] = new Integer(i);
- objArray2[i] = objArray[i].toString();
- }
- }
-
- /**
- * @tests java.util.IdentityHashMap#IdentityHashMap()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IdentityHashMap",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.IdentityHashMap()
- new Support_MapTest2(new IdentityHashMap()).runTest();
-
- IdentityHashMap hm2 = new IdentityHashMap();
- assertEquals("Created incorrect IdentityHashMap", 0, hm2.size());
- }
-
- /**
- * @tests java.util.IdentityHashMap#IdentityHashMap(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IdentityHashMap",
- args = {int.class}
- )
- public void test_ConstructorI() {
- // Test for method java.util.IdentityHashMap(int)
- IdentityHashMap hm2 = new IdentityHashMap(5);
- assertEquals("Created incorrect IdentityHashMap", 0, hm2.size());
- try {
- new IdentityHashMap(-1);
- fail("Failed to throw IllegalArgumentException for initial capacity < 0");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- IdentityHashMap empty = new IdentityHashMap(0);
- assertNull("Empty IdentityHashMap access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
- }
-
- /**
- * @tests java.util.IdentityHashMap#IdentityHashMap(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IdentityHashMap",
- args = {java.util.Map.class}
- )
- public void test_ConstructorLjava_util_Map() {
- // Test for method java.util.IdentityHashMap(java.util.Map)
- Map myMap = new TreeMap();
- for (int counter = 0; counter < hmSize; counter++)
- myMap.put(objArray2[counter], objArray[counter]);
- IdentityHashMap hm2 = new IdentityHashMap(myMap);
- for (int counter = 0; counter < hmSize; counter++)
- assertTrue("Failed to construct correct IdentityHashMap", hm
- .get(objArray2[counter]) == hm2.get(objArray2[counter]));
-
- Map mockMap = new MockMap();
- hm2 = new IdentityHashMap(mockMap);
- assertEquals("Size should be 0", 0, hm2.size());
-
- try {
- new IdentityHashMap(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.IdentityHashMap#clear()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- // Test for method void java.util.IdentityHashMap.clear()
- hm.clear();
- assertEquals("Clear failed to reset size", 0, hm.size());
- for (int i = 0; i < hmSize; i++)
- assertNull("Failed to clear all elements",
- hm.get(objArray2[i]));
-
- }
-
- /**
- * @tests java.util.IdentityHashMap#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- // Test for method java.lang.Object java.util.IdentityHashMap.clone()
- IdentityHashMap hm2 = (IdentityHashMap) hm.clone();
- assertTrue("Clone answered equivalent IdentityHashMap", hm2 != hm);
- for (int counter = 0; counter < hmSize; counter++)
- assertTrue("Clone answered unequal IdentityHashMap", hm
- .get(objArray2[counter]) == hm2.get(objArray2[counter]));
-
- IdentityHashMap map = new IdentityHashMap();
- map.put("key", "value");
- // get the keySet() and values() on the original Map
- Set keys = map.keySet();
- Collection values = map.values();
- assertEquals("values() does not work",
- "value", values.iterator().next());
- assertEquals("keySet() does not work",
- "key", keys.iterator().next());
- AbstractMap map2 = (AbstractMap) map.clone();
- map2.put("key", "value2");
- Collection values2 = map2.values();
- assertTrue("values() is identical", values2 != values);
- // values() and keySet() on the cloned() map should be different
- assertEquals("values() was not cloned",
- "value2", values2.iterator().next());
- map2.clear();
- map2.put("key2", "value3");
- Set key2 = map2.keySet();
- assertTrue("keySet() is identical", key2 != keys);
- assertEquals("keySet() was not cloned",
- "key2", key2.iterator().next());
- }
-
- /**
- * @tests java.util.IdentityHashMap#containsKey(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "containsKey",
- args = {java.lang.Object.class}
- )
- public void test_containsKeyLjava_lang_Object() {
- // Test for method boolean
- // java.util.IdentityHashMap.containsKey(java.lang.Object)
- assertTrue("Returned false for valid key", hm
- .containsKey(objArray2[23]));
- assertTrue("Returned true for copy of valid key", !hm
- .containsKey(new Integer(23).toString()));
- assertTrue("Returned true for invalid key", !hm.containsKey("KKDKDKD"));
-
- IdentityHashMap m = new IdentityHashMap();
- m.put(null, "test");
- assertTrue("Failed with null key", m.containsKey(null));
- assertTrue("Failed with missing key matching null hash", !m
- .containsKey(new Integer(0)));
- }
-
- /**
- * @tests java.util.IdentityHashMap#containsValue(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "containsValue",
- args = {java.lang.Object.class}
- )
- public void test_containsValueLjava_lang_Object() {
- // Test for method boolean
- // java.util.IdentityHashMap.containsValue(java.lang.Object)
- assertTrue("Returned false for valid value", hm
- .containsValue(objArray[19]));
- assertTrue("Returned true for invalid valie", !hm
- .containsValue(new Integer(-9)));
- }
-
- /**
- * @tests java.util.IdentityHashMap#entrySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "entrySet",
- args = {}
- )
- public void test_entrySet() {
- // Test for method java.util.Set java.util.IdentityHashMap.entrySet()
- Set s = hm.entrySet();
- Iterator i = s.iterator();
- assertTrue("Returned set of incorrect size", hm.size() == s.size());
- while (i.hasNext()) {
- Map.Entry m = (Map.Entry) i.next();
- assertTrue("Returned incorrect entry set", hm.containsKey(m
- .getKey())
- && hm.containsValue(m.getValue()));
- }
- }
-
- /**
- * @tests java.util.IdentityHashMap#get(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {java.lang.Object.class}
- )
- public void test_getLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.IdentityHashMap.get(java.lang.Object)
- assertNull("Get returned non-null for non existent key",
- hm.get("T"));
- hm.put("T", "HELLO");
- assertEquals("Get returned incorecct value for existing key", "HELLO", hm.get("T")
- );
-
- IdentityHashMap m = new IdentityHashMap();
- m.put(null, "test");
- assertEquals("Failed with null key", "test", m.get(null));
- assertNull("Failed with missing key matching null hash", m
- .get(new Integer(0)));
- }
-
- /**
- * @tests java.util.IdentityHashMap#isEmpty()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isEmpty",
- args = {}
- )
- public void test_isEmpty() {
- // Test for method boolean java.util.IdentityHashMap.isEmpty()
- assertTrue("Returned false for new map", new IdentityHashMap()
- .isEmpty());
- assertTrue("Returned true for non-empty", !hm.isEmpty());
- }
-
- /**
- * @tests java.util.IdentityHashMap#keySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "keySet",
- args = {}
- )
- public void test_keySet() {
- // Test for method java.util.Set java.util.IdentityHashMap.keySet()
- Set s = hm.keySet();
- assertTrue("Returned set of incorrect size()", s.size() == hm.size());
- for (int i = 0; i < objArray.length; i++) {
- assertTrue("Returned set does not contain all keys", s
- .contains(objArray2[i]));
- }
-
- IdentityHashMap m = new IdentityHashMap();
- m.put(null, "test");
- assertTrue("Failed with null key", m.keySet().contains(null));
- assertNull("Failed with null key", m.keySet().iterator().next());
-
- Map map = new IdentityHashMap(101);
- map.put(new Integer(1), "1");
- map.put(new Integer(102), "102");
- map.put(new Integer(203), "203");
- Iterator it = map.keySet().iterator();
- Integer remove1 = (Integer) it.next();
- it.hasNext();
- it.remove();
- Integer remove2 = (Integer) it.next();
- it.remove();
- ArrayList list = new ArrayList(Arrays.asList(new Integer[] {
- new Integer(1), new Integer(102), new Integer(203) }));
- list.remove(remove1);
- list.remove(remove2);
- assertTrue("Wrong result", it.next().equals(list.get(0)));
- assertEquals("Wrong size", 1, map.size());
- assertTrue("Wrong contents", map.keySet().iterator().next().equals(
- list.get(0)));
-
- Map map2 = new IdentityHashMap(101);
- map2.put(new Integer(1), "1");
- map2.put(new Integer(4), "4");
- Iterator it2 = map2.keySet().iterator();
- Integer remove3 = (Integer) it2.next();
- Integer next;
- if (remove3.intValue() == 1)
- next = new Integer(4);
- else
- next = new Integer(1);
- it2.hasNext();
- it2.remove();
- assertTrue("Wrong result 2", it2.next().equals(next));
- assertEquals("Wrong size 2", 1, map2.size());
- assertTrue("Wrong contents 2", map2.keySet().iterator().next().equals(
- next));
- }
-
- /**
- * @tests java.util.IdentityHashMap#put(java.lang.Object, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "put",
- args = {java.lang.Object.class, java.lang.Object.class}
- )
- public void test_putLjava_lang_ObjectLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.IdentityHashMap.put(java.lang.Object, java.lang.Object)
- hm.put("KEY", "VALUE");
- assertEquals("Failed to install key/value pair",
- "VALUE", hm.get("KEY"));
-
- IdentityHashMap m = new IdentityHashMap();
- Short s0 = new Short((short) 0);
- m.put(s0, "short");
- m.put(null, "test");
- Integer i0 = new Integer(0);
- m.put(i0, "int");
- assertEquals("Failed adding to bucket containing null",
- "short", m.get(s0));
- assertEquals("Failed adding to bucket containing null2", "int", m.get(i0)
- );
- }
-
- /**
- * @tests java.util.IdentityHashMap#putAll(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "putAll",
- args = {java.util.Map.class}
- )
- public void test_putAllLjava_util_Map() {
- // Test for method void java.util.IdentityHashMap.putAll(java.util.Map)
- IdentityHashMap hm2 = new IdentityHashMap();
- hm2.putAll(hm);
- for (int i = 0; i < 1000; i++)
- assertTrue("Failed to clear all elements", hm2.get(objArray2[i])
- .equals((new Integer(i))));
-
- hm2 = new IdentityHashMap();
- Map mockMap = new MockMap();
- hm2.putAll(mockMap);
- assertEquals("Size should be 0", 0, hm2.size());
-
- try {
- hm2.putAll(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.IdentityHashMap#remove(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_removeLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.IdentityHashMap.remove(java.lang.Object)
- int size = hm.size();
- Integer x = ((Integer) hm.remove(objArray2[9]));
- assertTrue("Remove returned incorrect value", x.equals(new Integer(9)));
- assertNull("Failed to remove given key", hm.get(objArray2[9]));
- assertTrue("Failed to decrement size", hm.size() == (size - 1));
- assertNull("Remove of non-existent key returned non-null", hm
- .remove("LCLCLC"));
-
- IdentityHashMap m = new IdentityHashMap();
- m.put(null, "test");
- assertNull("Failed with same hash as null",
- m.remove(objArray[0]));
- assertEquals("Failed with null key", "test", m.remove(null));
- }
-
- /**
- * @tests java.util.IdentityHashMap#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- public void test_size() {
- // Test for method int java.util.IdentityHashMap.size()
- assertEquals("Returned incorrect size, ", (objArray.length + 2), hm
- .size());
- }
-
- /**
- * @tests java.util.IdentityHashMap#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- IdentityHashMap mapOne = new IdentityHashMap();
- IdentityHashMap mapTwo = new IdentityHashMap();
- IdentityHashMap mapThree = new IdentityHashMap();
- IdentityHashMap mapFour = new IdentityHashMap();
-
- String one = "one";
- String alsoOne = new String(one); // use the new operator to ensure a
- // new reference is constructed
- String two = "two";
- String alsoTwo = new String(two); // use the new operator to ensure a
- // new reference is constructed
-
- mapOne.put(one, two);
- mapFour.put(one, two);
-
- // these two are not equal to the above two
- mapTwo.put(alsoOne, two);
- mapThree.put(one, alsoTwo);
-
- assertEquals("failure of equality of IdentityHashMaps", mapOne, mapFour);
- assertTrue("failure of non-equality of IdentityHashMaps one and two",
- !mapOne.equals(mapTwo));
- assertTrue("failure of non-equality of IdentityHashMaps one and three",
- !mapOne.equals(mapThree));
- assertTrue("failure of non-equality of IdentityHashMaps two and three",
- !mapTwo.equals(mapThree));
-
- HashMap hashMapTwo = new HashMap();
- HashMap hashMapThree = new HashMap();
- hashMapTwo.put(alsoOne, two);
- hashMapThree.put(one, alsoTwo);
-
- assertTrue(
- "failure of non-equality of IdentityHashMaps one and Hashmap two",
- !mapOne.equals(hashMapTwo));
- assertTrue(
- "failure of non-equality of IdentityHashMaps one and Hashmap three",
- !mapOne.equals(hashMapThree));
- }
-
- /**
- * @tests java.util.IdentityHashMap#values()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
- public void test_values() {
- // Test for method java.util.Collection
- // java.util.IdentityHashMap.values()
- Collection c = hm.values();
- assertTrue("Returned collection of incorrect size()", c.size() == hm
- .size());
- for (int i = 0; i < objArray.length; i++)
- assertTrue("Returned collection does not contain all keys", c
- .contains(objArray[i]));
-
- IdentityHashMap myIdentityHashMap = new IdentityHashMap();
- for (int i = 0; i < 100; i++)
- myIdentityHashMap.put(objArray2[i], objArray[i]);
- Collection values = myIdentityHashMap.values();
- values.remove(objArray[0]);
- assertTrue(
- "Removing from the values collection should remove from the original map",
- !myIdentityHashMap.containsValue(objArray2[0]));
-
- }
-
- /**
- * @tests java.util.IdentityHashMap#Serialization()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- )
- })
- public void test_Serialization() throws Exception {
- IdentityHashMap<String, String> map = new IdentityHashMap<String, String>();
- map.put(ID, "world");
- // BEGIN android-added
- // Regression test for null key in serialized IdentityHashMap (1178549)
- // Together with this change the IdentityHashMap.golden.ser resource
- // was replaced by a version that contains a map with a null key.
- map.put(null, "null");
- // END android-added
- SerializationTest.verifySelf(map, comparator);
- SerializationTest.verifyGolden(this, map, comparator);
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- hm = new IdentityHashMap();
- for (int i = 0; i < objArray.length; i++)
- hm.put(objArray2[i], objArray[i]);
- hm.put("test", null);
- hm.put(null, "test");
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-
- private static final SerializationTest.SerializableAssert comparator = new
- SerializationTest.SerializableAssert() {
-
- public void assertDeserialized(Serializable initial, Serializable deserialized) {
- IdentityHashMap<String, String> initialMap = (IdentityHashMap<String, String>) initial;
- IdentityHashMap<String, String> deseriaMap = (IdentityHashMap<String, String>) deserialized;
- assertEquals("should be equal", initialMap.size(), deseriaMap.size());
- }
-
- };
-}
diff --git a/luni/src/test/java/tests/api/java/util/InvalidPropertiesFormatExceptionTest.java b/luni/src/test/java/tests/api/java/util/InvalidPropertiesFormatExceptionTest.java
deleted file mode 100644
index d598233..0000000
--- a/luni/src/test/java/tests/api/java/util/InvalidPropertiesFormatExceptionTest.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/* 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.NotSerializableException;
-import java.util.InvalidPropertiesFormatException;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-@TestTargetClass(InvalidPropertiesFormatException.class)
-public class InvalidPropertiesFormatExceptionTest extends
- junit.framework.TestCase {
-
- /**
- * @tests java.util.InvalidPropertiesFormatException#SerializationTest()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- )
- public void test_Serialization() throws Exception {
- InvalidPropertiesFormatException ipfe = new InvalidPropertiesFormatException(
- "Hey, this is InvalidPropertiesFormatException");
- try {
- SerializationTest.verifySelf(ipfe);
- } catch (NotSerializableException e) {
- // expected
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/LinkedHashMapTest.java b/luni/src/test/java/tests/api/java/util/LinkedHashMapTest.java
deleted file mode 100644
index 7169aca..0000000
--- a/luni/src/test/java/tests/api/java/util/LinkedHashMapTest.java
+++ /dev/null
@@ -1,839 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.AbstractMap;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
-import tests.support.Support_MapTest2;
-import tests.support.Support_UnmodifiableCollectionTest;
-
-/**
- * @tests java.util.LinkedHashMap
- */
-@TestTargetClass(LinkedHashMap.class)
-public class LinkedHashMapTest extends junit.framework.TestCase {
-
- LinkedHashMap hm;
-
- final static int hmSize = 1000;
-
- static Object[] objArray;
-
- static Object[] objArray2;
- {
- objArray = new Object[hmSize];
- objArray2 = new Object[hmSize];
- for (int i = 0; i < objArray.length; i++) {
- objArray[i] = new Integer(i);
- objArray2[i] = objArray[i].toString();
- }
- }
-
- static final class CacheMap extends LinkedHashMap {
- protected boolean removeEldestEntry(Map.Entry e) {
- return size() > 5;
- }
- }
-
- private static class MockMapNull extends AbstractMap {
- @Override
- public Set entrySet() {
- return null;
- }
-
- @Override
- public int size() {
- return 10;
- }
- }
-
- /**
- * @tests java.util.LinkedHashMap#LinkedHashMap()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "LinkedHashMap",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.LinkedHashMap()
- new Support_MapTest2(new LinkedHashMap()).runTest();
-
- LinkedHashMap hm2 = new LinkedHashMap();
- assertEquals("Created incorrect LinkedHashMap", 0, hm2.size());
- }
-
- /**
- * @tests java.util.LinkedHashMap#LinkedHashMap(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Need to improve code.",
- method = "LinkedHashMap",
- args = {int.class}
- )
- public void test_ConstructorI() {
- // Test for method java.util.LinkedHashMap(int)
- LinkedHashMap hm2 = new LinkedHashMap(5);
- assertEquals("Created incorrect LinkedHashMap", 0, hm2.size());
- try {
- new LinkedHashMap(-1);
- fail("Failed to throw IllegalArgumentException for initial " +
- "capacity < 0");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- LinkedHashMap empty = new LinkedHashMap(0);
- assertNull("Empty LinkedHashMap access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
- }
-
- /**
- * @tests java.util.LinkedHashMap#LinkedHashMap(int, float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Need to improve code.",
- method = "LinkedHashMap",
- args = {int.class, float.class}
- )
- public void test_ConstructorIF() {
- // Test for method java.util.LinkedHashMap(int, float)
- LinkedHashMap hm2 = new LinkedHashMap(5, (float) 0.5);
- assertEquals("Created incorrect LinkedHashMap", 0, hm2.size());
- try {
- new LinkedHashMap(0, 0);
- fail("Failed to throw IllegalArgumentException for initial " +
- "load factor <= 0");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- LinkedHashMap empty = new LinkedHashMap(0, 0.75f);
- assertNull("Empty hashtable access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
- }
-
- /**
- * @tests java.util.LinkedHashMap#LinkedHashMap(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify IllegalArgumentException.",
- method = "LinkedHashMap",
- args = {java.util.Map.class}
- )
- public void test_ConstructorLjava_util_Map() {
- // Test for method java.util.LinkedHashMap(java.util.Map)
- Map myMap = new TreeMap();
- for (int counter = 0; counter < hmSize; counter++)
- myMap.put(objArray2[counter], objArray[counter]);
- LinkedHashMap hm2 = new LinkedHashMap(myMap);
- for (int counter = 0; counter < hmSize; counter++)
- assertTrue("Failed to construct correct LinkedHashMap", hm
- .get(objArray2[counter]) == hm2.get(objArray2[counter]));
- }
-
- /**
- * @tests java.util.LinkedHashMap#get(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ClassCastException, NullPointerException.",
- method = "get",
- args = {java.lang.Object.class}
- )
- public void test_getLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.LinkedHashMap.get(java.lang.Object)
- assertNull("Get returned non-null for non existent key",
- hm.get("T"));
- hm.put("T", "HELLO");
- assertEquals("Get returned incorecct value for existing key", "HELLO", hm.get("T")
- );
-
- LinkedHashMap m = new LinkedHashMap();
- m.put(null, "test");
- assertEquals("Failed with null key", "test", m.get(null));
- assertNull("Failed with missing key matching null hash", m
- .get(new Integer(0)));
- }
-
- /**
- * @tests java.util.LinkedHashMap#put(java.lang.Object, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify that put returns null if there was no mapping for key, or associated null with the specified key.",
- method = "put",
- args = {java.lang.Object.class, java.lang.Object.class}
- )
- public void test_putLjava_lang_ObjectLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.LinkedHashMap.put(java.lang.Object, java.lang.Object)
- hm.put("KEY", "VALUE");
- assertEquals("Failed to install key/value pair",
- "VALUE", hm.get("KEY"));
-
- LinkedHashMap m = new LinkedHashMap();
- m.put(new Short((short) 0), "short");
- m.put(null, "test");
- m.put(new Integer(0), "int");
- assertEquals("Failed adding to bucket containing null", "short", m.get(
- new Short((short) 0)));
- assertEquals("Failed adding to bucket containing null2", "int", m.get(
- new Integer(0)));
- }
-
- /**
- * @tests java.util.LinkedHashMap#putAll(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "putAll",
- args = {java.util.Map.class}
- )
- public void test_putAllLjava_util_Map() {
- // Test for method void java.util.LinkedHashMap.putAll(java.util.Map)
- LinkedHashMap hm2 = new LinkedHashMap();
- hm2.putAll(hm);
- for (int i = 0; i < 1000; i++)
- assertTrue("Failed to clear all elements", hm2.get(
- new Integer(i).toString()).equals((new Integer(i))));
- }
-
- /**
- * @tests java.util.LinkedHashMap#putAll(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "putAll",
- args = {java.util.Map.class}
- )
- public void test_putAll_Ljava_util_Map_Null() {
- LinkedHashMap linkedHashMap = new LinkedHashMap();
- try {
- linkedHashMap.putAll(new MockMapNull());
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected.
- }
-
- try {
- linkedHashMap = new LinkedHashMap(new MockMapNull());
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected.
- }
- }
-
- /**
- * @tests java.util.LinkedHashMap#entrySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "entrySet",
- args = {}
- )
- public void test_entrySet() {
- // Test for method java.util.Set java.util.LinkedHashMap.entrySet()
- Set s = hm.entrySet();
- Iterator i = s.iterator();
- assertTrue("Returned set of incorrect size", hm.size() == s.size());
- while (i.hasNext()) {
- Map.Entry m = (Map.Entry) i.next();
- assertTrue("Returned incorrect entry set", hm.containsKey(m
- .getKey())
- && hm.containsValue(m.getValue()));
- }
- }
-
- /**
- * @tests java.util.LinkedHashMap#keySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "keySet",
- args = {}
- )
- public void test_keySet() {
- // Test for method java.util.Set java.util.LinkedHashMap.keySet()
- Set s = hm.keySet();
- assertTrue("Returned set of incorrect size()", s.size() == hm.size());
- for (int i = 0; i < objArray.length; i++)
- assertTrue("Returned set does not contain all keys", s
- .contains(objArray[i].toString()));
-
- LinkedHashMap m = new LinkedHashMap();
- m.put(null, "test");
- assertTrue("Failed with null key", m.keySet().contains(null));
- assertNull("Failed with null key", m.keySet().iterator().next());
-
- Map map = new LinkedHashMap(101);
- map.put(new Integer(1), "1");
- map.put(new Integer(102), "102");
- map.put(new Integer(203), "203");
- Iterator it = map.keySet().iterator();
- Integer remove1 = (Integer) it.next();
- it.hasNext();
- it.remove();
- Integer remove2 = (Integer) it.next();
- it.remove();
- ArrayList list = new ArrayList(Arrays.asList(new Integer[] {
- new Integer(1), new Integer(102), new Integer(203) }));
- list.remove(remove1);
- list.remove(remove2);
- assertTrue("Wrong result", it.next().equals(list.get(0)));
- assertEquals("Wrong size", 1, map.size());
- assertTrue("Wrong contents", map.keySet().iterator().next().equals(
- list.get(0)));
-
- Map map2 = new LinkedHashMap(101);
- map2.put(new Integer(1), "1");
- map2.put(new Integer(4), "4");
- Iterator it2 = map2.keySet().iterator();
- Integer remove3 = (Integer) it2.next();
- Integer next;
- if (remove3.intValue() == 1)
- next = new Integer(4);
- else
- next = new Integer(1);
- it2.hasNext();
- it2.remove();
- assertTrue("Wrong result 2", it2.next().equals(next));
- assertEquals("Wrong size 2", 1, map2.size());
- assertTrue("Wrong contents 2", map2.keySet().iterator().next().equals(
- next));
- }
-
- /**
- * @tests java.util.LinkedHashMap#values()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
- public void test_values() {
- // Test for method java.util.Collection java.util.LinkedHashMap.values()
- Collection c = hm.values();
- assertTrue("Returned collection of incorrect size()", c.size() == hm
- .size());
- for (int i = 0; i < objArray.length; i++)
- assertTrue("Returned collection does not contain all keys", c
- .contains(objArray[i]));
-
- LinkedHashMap myLinkedHashMap = new LinkedHashMap();
- for (int i = 0; i < 100; i++)
- myLinkedHashMap.put(objArray2[i], objArray[i]);
- Collection values = myLinkedHashMap.values();
- new Support_UnmodifiableCollectionTest(
- "Test Returned Collection From LinkedHashMap.values()", values)
- .runTest();
- values.remove(new Integer(0));
- assertTrue(
- "Removing from the values collection should remove from the original map",
- !myLinkedHashMap.containsValue(new Integer(0)));
-
- }
-
- /**
- * @tests java.util.LinkedHashMap#remove(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_removeLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.LinkedHashMap.remove(java.lang.Object)
- int size = hm.size();
- Integer y = new Integer(9);
- Integer x = ((Integer) hm.remove(y.toString()));
- assertTrue("Remove returned incorrect value", x.equals(new Integer(9)));
- assertNull("Failed to remove given key", hm.get(new Integer(9)));
- assertTrue("Failed to decrement size", hm.size() == (size - 1));
- assertNull("Remove of non-existent key returned non-null", hm
- .remove("LCLCLC"));
-
- LinkedHashMap m = new LinkedHashMap();
- m.put(null, "test");
- assertNull("Failed with same hash as null",
- m.remove(new Integer(0)));
- assertEquals("Failed with null key", "test", m.remove(null));
- }
-
- /**
- * @tests java.util.LinkedHashMap#clear()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- // Test for method void java.util.LinkedHashMap.clear()
- hm.clear();
- assertEquals("Clear failed to reset size", 0, hm.size());
- for (int i = 0; i < hmSize; i++)
- assertNull("Failed to clear all elements",
- hm.get(objArray2[i]));
-
- }
-
- /**
- * @tests java.util.LinkedHashMap#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- // Test for method java.lang.Object java.util.LinkedHashMap.clone()
- LinkedHashMap hm2 = (LinkedHashMap) hm.clone();
- assertTrue("Clone answered equivalent LinkedHashMap", hm2 != hm);
- for (int counter = 0; counter < hmSize; counter++)
- assertTrue("Clone answered unequal LinkedHashMap", hm
- .get(objArray2[counter]) == hm2.get(objArray2[counter]));
-
- LinkedHashMap map = new LinkedHashMap();
- map.put("key", "value");
- // get the keySet() and values() on the original Map
- Set keys = map.keySet();
- Collection values = map.values();
- assertEquals("values() does not work",
- "value", values.iterator().next());
- assertEquals("keySet() does not work",
- "key", keys.iterator().next());
- AbstractMap map2 = (AbstractMap) map.clone();
- map2.put("key", "value2");
- Collection values2 = map2.values();
- assertTrue("values() is identical", values2 != values);
-
- // values() and keySet() on the cloned() map should be different
- assertEquals("values() was not cloned",
- "value2", values2.iterator().next());
- map2.clear();
- map2.put("key2", "value3");
- Set key2 = map2.keySet();
- assertTrue("keySet() is identical", key2 != keys);
- assertEquals("keySet() was not cloned",
- "key2", key2.iterator().next());
- }
-
- /**
- * @tests java.util.LinkedHashMap#clone()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone_ordered() {
- // Test for method java.lang.Object java.util.LinkedHashMap.clone()
- LinkedHashMap<String, String> hm1 = new LinkedHashMap<String, String>(10, 0.75f, true);
- hm1.put("a", "a");
- hm1.put("b", "b");
- hm1.put("c", "c");
- LinkedHashMap<String, String> hm2 = (LinkedHashMap<String, String>) hm1.clone();
- hm1.get("a");
-
- Map.Entry<String, String>[] set = new Map.Entry[3];
- Iterator<Map.Entry<String,String>> iterator = hm1.entrySet().iterator();
-
- assertEquals("b", iterator.next().getKey());
- assertEquals("c", iterator.next().getKey());
- assertEquals("a", iterator.next().getKey());
-
- iterator = hm2.entrySet().iterator();
- assertEquals("a", iterator.next().getKey());
- assertEquals("b", iterator.next().getKey());
- assertEquals("c", iterator.next().getKey());
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test.",
- method = "clone",
- args = {}
- )
- // regresion test for HARMONY-4603
- public void test_clone_Mock() {
- LinkedHashMap hashMap = new MockMap();
- String value = "value a";
- hashMap.put("key", value);
- MockMap cloneMap = (MockMap) hashMap.clone();
- assertEquals(value, cloneMap.get("key"));
- assertEquals(hashMap, cloneMap);
- assertEquals(1, cloneMap.num);
-
- hashMap.put("key", "value b");
- assertFalse(hashMap.equals(cloneMap));
- }
-
- class MockMap extends LinkedHashMap {
- int num;
-
- public Object put(Object k, Object v) {
- num++;
- return super.put(k, v);
- }
-
- protected boolean removeEldestEntry(Map.Entry e) {
- return num > 1;
- }
- }
-
- /**
- * @tests java.util.LinkedHashMap#containsKey(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ClassCastException, NullPointerException.",
- method = "containsKey",
- args = {java.lang.Object.class}
- )
- public void test_containsKeyLjava_lang_Object() {
- // Test for method boolean
- // java.util.LinkedHashMap.containsKey(java.lang.Object)
- assertTrue("Returned false for valid key", hm.containsKey(new Integer(
- 876).toString()));
- assertTrue("Returned true for invalid key", !hm.containsKey("KKDKDKD"));
-
- LinkedHashMap m = new LinkedHashMap();
- m.put(null, "test");
- assertTrue("Failed with null key", m.containsKey(null));
- assertTrue("Failed with missing key matching null hash", !m
- .containsKey(new Integer(0)));
- }
-
- /**
- * @tests java.util.LinkedHashMap#containsValue(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ClassCastException, NullPointerException.",
- method = "containsValue",
- args = {java.lang.Object.class}
- )
- public void test_containsValueLjava_lang_Object() {
- // Test for method boolean
- // java.util.LinkedHashMap.containsValue(java.lang.Object)
- assertTrue("Returned false for valid value", hm
- .containsValue(new Integer(875)));
- assertTrue("Returned true for invalid valie", !hm
- .containsValue(new Integer(-9)));
- }
-
- /**
- * @tests java.util.LinkedHashMap#isEmpty()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isEmpty",
- args = {}
- )
- public void test_isEmpty() {
- // Test for method boolean java.util.LinkedHashMap.isEmpty()
- assertTrue("Returned false for new map", new LinkedHashMap().isEmpty());
- assertTrue("Returned true for non-empty", !hm.isEmpty());
- }
-
- /**
- * @tests java.util.LinkedHashMap#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- public void test_size() {
- // Test for method int java.util.LinkedHashMap.size()
- assertTrue("Returned incorrect size",
- hm.size() == (objArray.length + 2));
- }
-
- /**
- * @tests java.util.LinkedHashMap#entrySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "entrySet",
- args = {}
- )
- public void test_ordered_entrySet() {
- int i;
- int sz = 100;
- LinkedHashMap lhm = new LinkedHashMap();
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lhm.put(ii, ii.toString());
- }
-
- Set s1 = lhm.entrySet();
- Iterator it1 = s1.iterator();
- assertTrue("Returned set of incorrect size 1", lhm.size() == s1.size());
- for (i = 0; it1.hasNext(); i++) {
- Map.Entry m = (Map.Entry) it1.next();
- Integer jj = (Integer) m.getKey();
- assertTrue("Returned incorrect entry set 1", jj.intValue() == i);
- }
-
- LinkedHashMap lruhm = new LinkedHashMap(200, .75f, true);
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lruhm.put(ii, ii.toString());
- }
-
- Set s3 = lruhm.entrySet();
- Iterator it3 = s3.iterator();
- assertTrue("Returned set of incorrect size 2", lruhm.size() == s3
- .size());
- for (i = 0; i < sz && it3.hasNext(); i++) {
- Map.Entry m = (Map.Entry) it3.next();
- Integer jj = (Integer) m.getKey();
- assertTrue("Returned incorrect entry set 2", jj.intValue() == i);
- }
-
- /* fetch the even numbered entries to affect traversal order */
- int p = 0;
- for (i = 0; i < sz; i += 2) {
- String ii = (String) lruhm.get(new Integer(i));
- p = p + Integer.parseInt(ii);
- }
- assertEquals("invalid sum of even numbers", 2450, p);
-
- Set s2 = lruhm.entrySet();
- Iterator it2 = s2.iterator();
- assertTrue("Returned set of incorrect size 3", lruhm.size() == s2
- .size());
- for (i = 1; i < sz && it2.hasNext(); i += 2) {
- Map.Entry m = (Map.Entry) it2.next();
- Integer jj = (Integer) m.getKey();
- assertTrue("Returned incorrect entry set 3", jj.intValue() == i);
- }
- for (i = 0; i < sz && it2.hasNext(); i += 2) {
- Map.Entry m = (Map.Entry) it2.next();
- Integer jj = (Integer) m.getKey();
- assertTrue("Returned incorrect entry set 4", jj.intValue() == i);
- }
- assertTrue("Entries left to iterate on", !it2.hasNext());
- }
-
- /**
- * @tests java.util.LinkedHashMap#keySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "keySet",
- args = {}
- )
- public void test_ordered_keySet() {
- int i;
- int sz = 100;
- LinkedHashMap lhm = new LinkedHashMap();
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lhm.put(ii, ii.toString());
- }
-
- Set s1 = lhm.keySet();
- Iterator it1 = s1.iterator();
- assertTrue("Returned set of incorrect size", lhm.size() == s1.size());
- for (i = 0; it1.hasNext(); i++) {
- Integer jj = (Integer) it1.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i);
- }
-
- LinkedHashMap lruhm = new LinkedHashMap(200, .75f, true);
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lruhm.put(ii, ii.toString());
- }
-
- Set s3 = lruhm.keySet();
- Iterator it3 = s3.iterator();
- assertTrue("Returned set of incorrect size", lruhm.size() == s3.size());
- for (i = 0; i < sz && it3.hasNext(); i++) {
- Integer jj = (Integer) it3.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i);
- }
-
- /* fetch the even numbered entries to affect traversal order */
- int p = 0;
- for (i = 0; i < sz; i += 2) {
- String ii = (String) lruhm.get(new Integer(i));
- p = p + Integer.parseInt(ii);
- }
- assertEquals("invalid sum of even numbers", 2450, p);
-
- Set s2 = lruhm.keySet();
- Iterator it2 = s2.iterator();
- assertTrue("Returned set of incorrect size", lruhm.size() == s2.size());
- for (i = 1; i < sz && it2.hasNext(); i += 2) {
- Integer jj = (Integer) it2.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i);
- }
- for (i = 0; i < sz && it2.hasNext(); i += 2) {
- Integer jj = (Integer) it2.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i);
- }
- assertTrue("Entries left to iterate on", !it2.hasNext());
- }
-
- /**
- * @tests java.util.LinkedHashMap#values()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
- public void test_ordered_values() {
- int i;
- int sz = 100;
- LinkedHashMap lhm = new LinkedHashMap();
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lhm.put(ii, new Integer(i * 2));
- }
-
- Collection s1 = lhm.values();
- Iterator it1 = s1.iterator();
- assertTrue("Returned set of incorrect size 1", lhm.size() == s1.size());
- for (i = 0; it1.hasNext(); i++) {
- Integer jj = (Integer) it1.next();
- assertTrue("Returned incorrect entry set 1", jj.intValue() == i * 2);
- }
-
- LinkedHashMap lruhm = new LinkedHashMap(200, .75f, true);
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lruhm.put(ii, new Integer(i * 2));
- }
-
- Collection s3 = lruhm.values();
- Iterator it3 = s3.iterator();
- assertTrue("Returned set of incorrect size", lruhm.size() == s3.size());
- for (i = 0; i < sz && it3.hasNext(); i++) {
- Integer jj = (Integer) it3.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i * 2);
- }
-
- // fetch the even numbered entries to affect traversal order
- int p = 0;
- for (i = 0; i < sz; i += 2) {
- Integer ii = (Integer) lruhm.get(new Integer(i));
- p = p + ii.intValue();
- }
- assertTrue("invalid sum of even numbers", p == 2450 * 2);
-
- Collection s2 = lruhm.values();
- Iterator it2 = s2.iterator();
- assertTrue("Returned set of incorrect size", lruhm.size() == s2.size());
- for (i = 1; i < sz && it2.hasNext(); i += 2) {
- Integer jj = (Integer) it2.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i * 2);
- }
- for (i = 0; i < sz && it2.hasNext(); i += 2) {
- Integer jj = (Integer) it2.next();
- assertTrue("Returned incorrect entry set", jj.intValue() == i * 2);
- }
- assertTrue("Entries left to iterate on", !it2.hasNext());
- }
-
- /**
- * @tests java.util.LinkedHashMap#removeEldestEntry(java.util.Map$Entry)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "removeEldestEntry",
- args = {java.util.Map.Entry.class}
- )
- public void test_remove_eldest() {
- int i;
- int sz = 10;
- CacheMap lhm = new CacheMap();
- for (i = 0; i < sz; i++) {
- Integer ii = new Integer(i);
- lhm.put(ii, new Integer(i * 2));
- }
-
- Collection s1 = lhm.values();
- Iterator it1 = s1.iterator();
- assertTrue("Returned set of incorrect size 1", lhm.size() == s1.size());
- for (i = 5; it1.hasNext(); i++) {
- Integer jj = (Integer) it1.next();
- assertTrue("Returned incorrect entry set 1", jj.intValue() == i * 2);
- }
- assertTrue("Entries left in map", !it1.hasNext());
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- hm = new LinkedHashMap();
- for (int i = 0; i < objArray.length; i++)
- hm.put(objArray2[i], objArray[i]);
- hm.put("test", null);
- hm.put(null, "test");
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/LinkedHashSetTest.java b/luni/src/test/java/tests/api/java/util/LinkedHashSetTest.java
deleted file mode 100644
index 1b8eeaa..0000000
--- a/luni/src/test/java/tests/api/java/util/LinkedHashSetTest.java
+++ /dev/null
@@ -1,446 +0,0 @@
-/* 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.Set;
-import java.util.Vector;
-
-/**
- * @tests java.util.LinkedHashSet
- */
-
-@TestTargetClass(java.util.LinkedHashSet.class)
-public class LinkedHashSetTest extends junit.framework.TestCase {
-
- LinkedHashSet hs;
-
- static Object[] objArray;
- {
- objArray = new Object[1000];
- for (int i = 0; i < objArray.length; i++)
- objArray[i] = new Integer(i);
- }
-
- /**
- * @tests java.util.LinkedHashSet#LinkedHashSet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "LinkedHashSet",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.LinkedHashSet()
- LinkedHashSet hs2 = new LinkedHashSet();
- assertEquals("Created incorrect LinkedHashSet", 0, hs2.size());
- }
-
- /**
- * @tests java.util.LinkedHashSet#LinkedHashSet(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "LinkedHashSet",
- args = {int.class}
- )
- public void test_ConstructorI() {
- // Test for method java.util.LinkedHashSet(int)
- LinkedHashSet hs2 = new LinkedHashSet(5);
- assertEquals("Created incorrect LinkedHashSet", 0, hs2.size());
- try {
- new LinkedHashSet(-1);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.LinkedHashSet#LinkedHashSet(int, float)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "LinkedHashSet",
- args = {int.class, float.class}
- )
- public void test_ConstructorIF() {
- // Test for method java.util.LinkedHashSet(int, float)
- LinkedHashSet hs2 = new LinkedHashSet(5, (float) 0.5);
- assertEquals("Created incorrect LinkedHashSet", 0, hs2.size());
-
- try {
- new LinkedHashSet(-1, 0.5f);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new LinkedHashSet(1, -0.5f);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new LinkedHashSet(1, 0f);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.LinkedHashSet#LinkedHashSet(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "LinkedHashSet",
- args = {java.util.Collection.class}
- )
- public void test_ConstructorLjava_util_Collection() {
- // Test for method java.util.LinkedHashSet(java.util.Collection)
- LinkedHashSet hs2 = new LinkedHashSet(Arrays.asList(objArray));
- for (int counter = 0; counter < objArray.length; counter++)
- assertTrue("LinkedHashSet does not contain correct elements", hs
- .contains(objArray[counter]));
- assertTrue("LinkedHashSet created from collection incorrect size", hs2
- .size() == objArray.length);
-
- try {
- new LinkedHashSet(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.LinkedHashSet#add(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "add",
- args = {java.lang.Object.class}
- )
- public void test_addLjava_lang_Object() {
- // Test for method boolean java.util.LinkedHashSet.add(java.lang.Object)
- int size = hs.size();
- hs.add(new Integer(8));
- assertTrue("Added element already contained by set", hs.size() == size);
- hs.add(new Integer(-9));
- assertTrue("Failed to increment set size after add",
- hs.size() == size + 1);
- assertTrue("Failed to add element to set", hs.contains(new Integer(-9)));
- }
-
- /**
- * @tests java.util.LinkedHashSet#clear()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- // Test for method void java.util.LinkedHashSet.clear()
- Set orgSet = (Set) hs.clone();
- hs.clear();
- Iterator i = orgSet.iterator();
- assertEquals("Returned non-zero size after clear", 0, hs.size());
- while (i.hasNext())
- assertTrue("Failed to clear set", !hs.contains(i.next()));
- }
-
- /**
- * @tests java.util.LinkedHashSet#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- // Test for method java.lang.Object java.util.LinkedHashSet.clone()
- LinkedHashSet hs2 = (LinkedHashSet) hs.clone();
- assertTrue("clone returned an equivalent LinkedHashSet", hs != hs2);
- assertTrue("clone did not return an equal LinkedHashSet", hs
- .equals(hs2));
- }
-
- /**
- * @tests java.util.LinkedHashSet#contains(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies null as a parameter.",
- method = "contains",
- args = {java.lang.Object.class}
- )
- public void test_containsLjava_lang_Object() {
- // Test for method boolean
- // java.util.LinkedHashSet.contains(java.lang.Object)
- assertTrue("Returned false for valid object", hs.contains(objArray[90]));
- assertTrue("Returned true for invalid Object", !hs
- .contains(new Object()));
-
- LinkedHashSet s = new LinkedHashSet();
- s.add(null);
- assertTrue("Cannot handle null", s.contains(null));
- }
-
- /**
- * @tests java.util.LinkedHashSet#isEmpty()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isEmpty",
- args = {}
- )
- public void test_isEmpty() {
- // Test for method boolean java.util.LinkedHashSet.isEmpty()
- assertTrue("Empty set returned false", new LinkedHashSet().isEmpty());
- assertTrue("Non-empty set returned true", !hs.isEmpty());
- }
-
- /**
- * @tests java.util.LinkedHashSet#iterator()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "iterator",
- args = {}
- )
- public void test_iterator() {
- // Test for method java.util.Iterator java.util.LinkedHashSet.iterator()
- Iterator i = hs.iterator();
- int x = 0;
- int j;
- for (j = 0; i.hasNext(); j++) {
- Object oo = i.next();
- if (oo != null) {
- Integer ii = (Integer) oo;
- assertTrue("Incorrect element found", ii.intValue() == j);
- } else {
- assertTrue("Cannot find null", hs.contains(oo));
- }
- ++x;
- }
- assertTrue("Returned iteration of incorrect size", hs.size() == x);
-
- LinkedHashSet s = new LinkedHashSet();
- s.add(null);
- assertNull("Cannot handle null", s.iterator().next());
- }
-
- /**
- * @tests java.util.LinkedHashSet#remove(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ClassCastException, NullPointerException, UnsupportedOperationException.",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_removeLjava_lang_Object() {
- // Test for method boolean
- // java.util.LinkedHashSet.remove(java.lang.Object)
- int size = hs.size();
- hs.remove(new Integer(98));
- assertTrue("Failed to remove element", !hs.contains(new Integer(98)));
- assertTrue("Failed to decrement set size", hs.size() == size - 1);
-
- LinkedHashSet s = new LinkedHashSet();
- s.add(null);
- assertTrue("Cannot handle null", s.remove(null));
- }
-
- /**
- * @tests java.util.LinkedHashSet#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- public void test_size() {
- // Test for method int java.util.LinkedHashSet.size()
- assertTrue("Returned incorrect size", hs.size() == (objArray.length + 1));
- hs.clear();
- assertEquals("Cleared set returned non-zero size", 0, hs.size());
- }
-
- class Mock_LinkedHashSet extends LinkedHashSet {
- @Override
- public boolean retainAll(Collection c) {
- throw new UnsupportedOperationException();
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "retainAll",
- args = {java.util.Collection.class}
- )
- public void test_retainAllLjava_util_Collection() {
- LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>();
- Vector v = new Vector<Float>();
- v.add(new Float(3.14));
- lhs.add(new Integer(1));
- assertEquals(1, lhs.size());
- lhs.retainAll(v);
- assertEquals(0, lhs.size());
- v = new Vector<Integer>();
- v.add(new Integer(1));
- v.add(new Integer(2));
- v.add(new Integer(3));
- v.add(new Integer(4));
- v.add(new Integer(5));
- v.add(new Integer(6));
- lhs.add(new Integer(1));
- lhs.add(new Integer(6));
- lhs.add(new Integer(7));
- lhs.add(new Integer(8));
- lhs.add(new Integer(9));
- lhs.add(new Integer(10));
- lhs.add(new Integer(11));
- lhs.add(new Integer(12));
- lhs.add(new Integer(13));
- assertEquals(9, lhs.size());
- lhs.retainAll(v);
- assertEquals(2, lhs.size());
-
- try {
- lhs.retainAll(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- lhs = new Mock_LinkedHashSet();
-
- try {
- lhs.retainAll(v);
- fail("UnsupportedOperationException expected");
- } catch (UnsupportedOperationException e) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toArray",
- args = {}
- )
- public void test_toArray() {
- LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>();
- lhs.add(new Integer(1));
- lhs.add(new Integer(6));
- lhs.add(new Integer(7));
- lhs.add(new Integer(8));
- lhs.add(new Integer(9));
- lhs.add(new Integer(10));
- lhs.add(new Integer(11));
- lhs.add(new Integer(12));
- lhs.add(new Integer(13));
-
- Object[] o = lhs.toArray();
- for (int i = 0; i < o.length; i++) {
- assertTrue(lhs.contains(o[i]));
- }
- assertEquals(lhs.size(), o.length);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toArray",
- args = {java.lang.Object[].class}
- )
- public void test_toArray$Ljava_lang_Object() {
- LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>();
- lhs.add(new Integer(1));
- lhs.add(new Integer(6));
- lhs.add(new Integer(7));
- lhs.add(new Integer(8));
- lhs.add(new Integer(9));
- lhs.add(new Integer(10));
- lhs.add(new Integer(11));
- lhs.add(new Integer(12));
- lhs.add(new Integer(13));
-
- Object[] o1 = new Object[lhs.size()];
- Object[] o2 = new Double[lhs.size()];
- lhs.toArray(o1);
- for (int i = 0; i < o1.length; i++) {
- assertTrue(lhs.contains(o1[i]));
- }
-
- try {
- lhs.toArray(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- try {
- lhs.toArray(o2);
- fail("ArrayStoreException expected");
- } catch (ArrayStoreException e) {
- //expected
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- hs = new LinkedHashSet();
- for (int i = 0; i < objArray.length; i++)
- hs.add(objArray[i]);
- hs.add(null);
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/LinkedListTest.java b/luni/src/test/java/tests/api/java/util/LinkedListTest.java
deleted file mode 100644
index 46b766a..0000000
--- a/luni/src/test/java/tests/api/java/util/LinkedListTest.java
+++ /dev/null
@@ -1,841 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.NoSuchElementException;
-
-
-import tests.support.Support_ListTest;
-
-@TestTargetClass(LinkedList.class)
-public class LinkedListTest extends junit.framework.TestCase {
-
- LinkedList ll;
-
- static Object[] objArray;
- {
- objArray = new Object[100];
- for (int i = 0; i < objArray.length; i++)
- objArray[i] = new Integer(i);
- }
-
- /**
- * @tests java.util.LinkedList#LinkedList()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "LinkedList",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.LinkedList()
- new Support_ListTest("", ll).runTest();
-
- LinkedList subList = new LinkedList();
- for (int i = -50; i < 150; i++)
- subList.add(new Integer(i));
- new Support_ListTest("", subList.subList(50, 150)).runTest();
- }
-
- /**
- * @tests java.util.LinkedList#LinkedList(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "LinkedList",
- args = {java.util.Collection.class}
- )
- public void test_ConstructorLjava_util_Collection() {
- // Test for method java.util.LinkedList(java.util.Collection)
- assertTrue("Incorrect LinkedList constructed", new LinkedList(ll)
- .equals(ll));
-
- try {
- new LinkedList(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.LinkedList#add(int, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "add",
- args = {int.class, java.lang.Object.class}
- )
- public void test_addILjava_lang_Object() {
- // Test for method void java.util.LinkedList.add(int, java.lang.Object)
- Object o;
- ll.add(50, o = "Test");
- assertTrue("Failed to add Object>: " + ll.get(50).toString(), ll
- .get(50) == o);
- assertTrue("Failed to fix up list after insert",
- ll.get(51) == objArray[50] && (ll.get(52) == objArray[51]));
- ll.add(50, null);
- assertNull("Did not add null correctly", ll.get(50));
- }
-
- /**
- * @tests java.util.LinkedList#add(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "add",
- args = {java.lang.Object.class}
- )
- public void test_addLjava_lang_Object() {
- // Test for method boolean java.util.LinkedList.add(java.lang.Object)
- Object o;
- ll.add(o = new Object());
- assertTrue("Failed to add Object", ll.getLast() == o);
- ll.add(null);
- assertNull("Did not add null correctly", ll.get(ll.size() - 1));
- }
-
- /**
- * @tests java.util.LinkedList#addAll(int, java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addAll",
- args = {int.class, java.util.Collection.class}
- )
- public void test_addAllILjava_util_Collection() {
- // Test for method boolean java.util.LinkedList.addAll(int,
- // java.util.Collection)
- ll.addAll(50, (Collection) ll.clone());
- assertEquals("Returned incorrect size after adding to existing list", 200, ll
- .size());
- for (int i = 0; i < 50; i++)
- assertTrue("Manipulated elements < index", ll.get(i) == objArray[i]);
- for (int i = 0; i >= 50 && (i < 150); i++)
- assertTrue("Failed to ad elements properly",
- ll.get(i) == objArray[i - 50]);
- for (int i = 0; i >= 150 && (i < 200); i++)
- assertTrue("Failed to ad elements properly",
- ll.get(i) == objArray[i - 100]);
- List myList = new LinkedList();
- myList.add(null);
- myList.add("Blah");
- myList.add(null);
- myList.add("Booga");
- myList.add(null);
- ll.addAll(50, myList);
- assertNull("a) List w/nulls not added correctly", ll.get(50));
- assertEquals("b) List w/nulls not added correctly",
- "Blah", ll.get(51));
- assertNull("c) List w/nulls not added correctly", ll.get(52));
- assertEquals("d) List w/nulls not added correctly",
- "Booga", ll.get(53));
- assertNull("e) List w/nulls not added correctly", ll.get(54));
-
- try {
- ll.addAll(-1, (Collection) null);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- ll.addAll(ll.size() + 1, (Collection) null);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- ll.addAll(0, null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.LinkedList#addAll(int, java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IndexOutOfBoundsException.",
- method = "addAll",
- args = {int.class, java.util.Collection.class}
- )
- public void test_addAllILjava_util_Collection_2() {
- // Regression for HARMONY-467
- LinkedList obj = new LinkedList();
- try {
- obj.addAll(-1, (Collection) null);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * @tests java.util.LinkedList#addAll(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addAll",
- args = {java.util.Collection.class}
- )
- public void test_addAllLjava_util_Collection() {
- // Test for method boolean
- // java.util.LinkedList.addAll(java.util.Collection)
- List l = new ArrayList();
- l.addAll((Collection) ll.clone());
- for (int i = 0; i < ll.size(); i++)
- assertTrue("Failed to add elements properly", l.get(i).equals(
- ll.get(i)));
- ll.addAll((Collection) ll.clone());
- assertEquals("Returned incorrect siZe after adding to existing list", 200, ll
- .size());
- for (int i = 0; i < 100; i++) {
- assertTrue("Added to list in incorrect order", ll.get(i).equals(
- l.get(i)));
- assertTrue("Failed to add to existing list", ll.get(i + 100)
- .equals(l.get(i)));
- }
- List myList = new LinkedList();
- myList.add(null);
- myList.add("Blah");
- myList.add(null);
- myList.add("Booga");
- myList.add(null);
- ll.addAll(myList);
- assertNull("a) List w/nulls not added correctly", ll.get(200));
- assertEquals("b) List w/nulls not added correctly",
- "Blah", ll.get(201));
- assertNull("c) List w/nulls not added correctly", ll.get(202));
- assertEquals("d) List w/nulls not added correctly",
- "Booga", ll.get(203));
- assertNull("e) List w/nulls not added correctly", ll.get(204));
-
- try {
- ll.addAll(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.LinkedList#addFirst(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addFirst",
- args = {java.lang.Object.class}
- )
- public void test_addFirstLjava_lang_Object() {
- // Test for method void java.util.LinkedList.addFirst(java.lang.Object)
- Object o;
- ll.addFirst(o = new Object());
- assertTrue("Failed to add Object", ll.getFirst() == o);
- ll.addFirst(null);
- assertNull("Failed to add null", ll.getFirst());
- }
-
- /**
- * @tests java.util.LinkedList#addLast(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addLast",
- args = {java.lang.Object.class}
- )
- public void test_addLastLjava_lang_Object() {
- // Test for method void java.util.LinkedList.addLast(java.lang.Object)
- Object o;
- ll.addLast(o = new Object());
- assertTrue("Failed to add Object", ll.getLast() == o);
- ll.addLast(null);
- assertNull("Failed to add null", ll.getLast());
- }
-
- /**
- * @tests java.util.LinkedList#clear()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- // Test for method void java.util.LinkedList.clear()
- ll.clear();
- for (int i = 0; i < ll.size(); i++)
- assertNull("Failed to clear list", ll.get(i));
- }
-
- /**
- * @tests java.util.LinkedList#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- // Test for method java.lang.Object java.util.LinkedList.clone()
- Object x = ll.clone();
- assertTrue("Cloned list was inequal to cloned", x.equals(ll));
- for (int i = 0; i < ll.size(); i++)
- assertTrue("Cloned list contains incorrect elements", ll.get(i)
- .equals(((LinkedList) x).get(i)));
- ll.addFirst(null);
- x = ll.clone();
- assertTrue("List with a null did not clone properly", ll.equals(x));
- }
-
- /**
- * @tests java.util.LinkedList#contains(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "contains",
- args = {java.lang.Object.class}
- )
- public void test_containsLjava_lang_Object() {
- // Test for method boolean
- // java.util.LinkedList.contains(java.lang.Object)
- assertTrue("Returned false for valid element", ll
- .contains(objArray[99]));
- assertTrue("Returned false for equal element", ll.contains(new Integer(
- 8)));
- assertTrue("Returned true for invalid element", !ll
- .contains(new Object()));
- assertTrue("Should not contain null", !ll.contains(null));
- ll.add(25, null);
- assertTrue("Should contain null", ll.contains(null));
- }
-
- /**
- * @tests java.util.LinkedList#get(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {int.class}
- )
- public void test_getI() {
- // Test for method java.lang.Object java.util.LinkedList.get(int)
- assertTrue("Returned incorrect element", ll.get(22) == objArray[22]);
- try {
- ll.get(8765);
- fail("Failed to throw expected exception for index > size");
- } catch (IndexOutOfBoundsException e) {
- }
- }
-
- /**
- * @tests java.util.LinkedList#getFirst()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFirst",
- args = {}
- )
- public void test_getFirst() {
- // Test for method java.lang.Object java.util.LinkedList.getFirst()
- assertTrue("Returned incorrect first element", ll.getFirst().equals(
- objArray[0]));
-
- ll.clear();
- try {
- ll.getFirst();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.LinkedList#getLast()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLast",
- args = {}
- )
- public void test_getLast() {
- // Test for method java.lang.Object java.util.LinkedList.getLast()
- assertTrue("Returned incorrect first element", ll.getLast().equals(
- objArray[objArray.length - 1]));
-
- ll.clear();
- try {
- ll.getLast();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.LinkedList#indexOf(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "indexOf",
- args = {java.lang.Object.class}
- )
- public void test_indexOfLjava_lang_Object() {
- // Test for method int java.util.LinkedList.indexOf(java.lang.Object)
- assertEquals("Returned incorrect index", 87, ll.indexOf(objArray[87]));
- assertEquals("Returned index for invalid Object", -1, ll
- .indexOf(new Object()));
- ll.add(20, null);
- ll.add(24, null);
- assertTrue("Index of null should be 20, but got: " + ll.indexOf(null),
- ll.indexOf(null) == 20);
- }
-
- /**
- * @tests java.util.LinkedList#lastIndexOf(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lastIndexOf",
- args = {java.lang.Object.class}
- )
- public void test_lastIndexOfLjava_lang_Object() {
- // Test for method int
- // java.util.LinkedList.lastIndexOf(java.lang.Object)
- ll.add(new Integer(99));
- assertEquals("Returned incorrect index",
- 100, ll.lastIndexOf(objArray[99]));
- assertEquals("Returned index for invalid Object", -1, ll
- .lastIndexOf(new Object()));
- ll.add(20, null);
- ll.add(24, null);
- assertTrue("Last index of null should be 20, but got: "
- + ll.lastIndexOf(null), ll.lastIndexOf(null) == 24);
- }
-
- /**
- * @tests java.util.LinkedList#listIterator(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "listIterator",
- args = {int.class}
- )
- public void test_listIteratorI() {
- // Test for method java.util.ListIterator
- // java.util.LinkedList.listIterator(int)
- ListIterator i1 = ll.listIterator();
- ListIterator i2 = ll.listIterator(0);
- Object elm;
- int n = 0;
- while (i2.hasNext()) {
- if (n == 0 || n == objArray.length - 1) {
- if (n == 0)
- assertTrue("First element claimed to have a previous", !i2
- .hasPrevious());
- if (n == objArray.length)
- assertTrue("Last element claimed to have next", !i2
- .hasNext());
- }
- elm = i2.next();
- assertTrue("Iterator returned elements in wrong order",
- elm == objArray[n]);
- if (n > 0 && n < objArray.length - 1) {
- assertTrue("Next index returned incorrect value",
- i2.nextIndex() == n + 1);
- assertTrue("previousIndex returned incorrect value : "
- + i2.previousIndex() + ", n val: " + n, i2
- .previousIndex() == n);
- }
- elm = i1.next();
- assertTrue("Iterator returned elements in wrong order",
- elm == objArray[n]);
- ++n;
- }
-
- i2 = ll.listIterator(ll.size()/2);
- assertTrue((Integer)i2.next() == ll.size()/2);
- List myList = new LinkedList();
- myList.add(null);
- myList.add("Blah");
- myList.add(null);
- myList.add("Booga");
- myList.add(null);
- ListIterator li = myList.listIterator();
- assertTrue("li.hasPrevious() should be false", !li.hasPrevious());
- assertNull("li.next() should be null", li.next());
- assertTrue("li.hasPrevious() should be true", li.hasPrevious());
- assertNull("li.prev() should be null", li.previous());
- assertNull("li.next() should be null", li.next());
- assertEquals("li.next() should be Blah", "Blah", li.next());
- assertNull("li.next() should be null", li.next());
- assertEquals("li.next() should be Booga", "Booga", li.next());
- assertTrue("li.hasNext() should be true", li.hasNext());
- assertNull("li.next() should be null", li.next());
- assertTrue("li.hasNext() should be false", !li.hasNext());
-
- try {
- ll.listIterator(-1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- ll.listIterator(ll.size() + 1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.LinkedList#remove(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {int.class}
- )
- public void test_removeI() {
- // Test for method java.lang.Object java.util.LinkedList.remove(int)
- ll.remove(10);
- assertEquals("Failed to remove element", -1, ll.indexOf(objArray[10]));
- try {
- ll.remove(999);
- fail("Failed to throw expected exception when index out of range");
- } catch (IndexOutOfBoundsException e) {
- // Correct
- }
-
- ll.add(20, null);
- ll.remove(20);
- assertNotNull("Should have removed null", ll.get(20));
- }
-
- /**
- * @tests java.util.LinkedList#remove(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_removeLjava_lang_Object() {
- // Test for method boolean java.util.LinkedList.remove(java.lang.Object)
- assertTrue("Failed to remove valid Object", ll.remove(objArray[87]));
- assertTrue("Removed invalid object", !ll.remove(new Object()));
- assertEquals("Found Object after removal", -1, ll.indexOf(objArray[87]));
- ll.add(null);
- ll.remove(null);
- assertTrue("Should not contain null afrer removal", !ll.contains(null));
- }
-
- /**
- * @tests java.util.LinkedList#removeFirst()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "removeFirst",
- args = {}
- )
- public void test_removeFirst() {
- // Test for method java.lang.Object java.util.LinkedList.removeFirst()
- ll.removeFirst();
- assertTrue("Failed to remove first element",
- ll.getFirst() != objArray[0]);
-
- ll.clear();
- try {
- ll.removeFirst();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.LinkedList#removeLast()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "removeLast",
- args = {}
- )
- public void test_removeLast() {
- // Test for method java.lang.Object java.util.LinkedList.removeLast()
- ll.removeLast();
- assertTrue("Failed to remove last element",
- ll.getLast() != objArray[objArray.length - 1]);
-
- ll.clear();
- try {
- ll.removeLast();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.LinkedList#set(int, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "set",
- args = {int.class, java.lang.Object.class}
- )
- public void test_setILjava_lang_Object() {
- // Test for method java.lang.Object java.util.LinkedList.set(int,
- // java.lang.Object)
- Object obj;
- ll.set(65, obj = new Object());
- assertTrue("Failed to set object", ll.get(65) == obj);
-
- try {
- ll.set(-1, obj = new Object());
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- ll.set(ll.size() + 1, obj = new Object());
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.LinkedList#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- public void test_size() {
- // Test for method int java.util.LinkedList.size()
- assertTrue("Returned incorrect size", ll.size() == objArray.length);
- ll.removeFirst();
- assertTrue("Returned incorrect size", ll.size() == objArray.length - 1);
- }
-
- /**
- * @tests java.util.LinkedList#toArray()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toArray",
- args = {}
- )
- public void test_toArray() {
- // Test for method java.lang.Object [] java.util.LinkedList.toArray()
- ll.add(null);
- Object[] obj = ll.toArray();
- assertEquals("Returned array of incorrect size", objArray.length + 1, obj.length);
-
- for (int i = 0; i < obj.length - 1; i++)
- assertTrue("Returned incorrect array: " + i, obj[i] == objArray[i]);
- assertNull("Returned incorrect array--end isn't null",
- obj[obj.length - 1]);
- }
-
- /**
- * @tests java.util.LinkedList#toArray(java.lang.Object[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toArray",
- args = {java.lang.Object[].class}
- )
- public void test_toArray$Ljava_lang_Object() {
- // Test for method java.lang.Object []
- // java.util.LinkedList.toArray(java.lang.Object [])
- Integer[] argArray = new Integer[100];
- Object[] retArray;
- retArray = ll.toArray(argArray);
- assertTrue("Returned different array than passed", retArray == argArray);
- List retList = new LinkedList(Arrays.asList(retArray));
- Iterator li = ll.iterator();
- Iterator ri = retList.iterator();
- while (li.hasNext())
- assertTrue("Lists are not equal", li.next() == ri.next());
- argArray = new Integer[1000];
- retArray = ll.toArray(argArray);
- assertNull("Failed to set first extra element to null", argArray[ll
- .size()]);
- for (int i = 0; i < ll.size(); i++)
- assertTrue("Returned incorrect array: " + i,
- retArray[i] == objArray[i]);
- ll.add(50, null);
- argArray = new Integer[101];
- retArray = ll.toArray(argArray);
- assertTrue("Returned different array than passed", retArray == argArray);
- retArray = ll.toArray(argArray);
- assertTrue("Returned different array than passed", retArray == argArray);
- retList = new LinkedList(Arrays.asList(retArray));
- li = ll.iterator();
- ri = retList.iterator();
- while (li.hasNext())
- assertTrue("Lists are not equal", li.next() == ri.next());
-
- try {
- ll.toArray(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- LinkedList<String> lls = new LinkedList<String>();
- lls.add("First");
- lls.add("Second");
-
- try {
- lls.toArray(argArray);
- fail("ArrayStoreException expected");
- } catch (ArrayStoreException e) {
- //expected
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "offer",
- args = {java.lang.Object.class}
- )
- public void test_offer() {
- int origSize = ll.size();
- assertTrue("offer() should return true'", ll.offer(objArray[0]));
- assertEquals("offer() should add an element as the last one", origSize, ll.lastIndexOf(objArray[0]));
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "poll",
- args = {}
- )
- public void test_poll() {
- for (int i = 0; i < objArray.length; i++) {
- assertEquals("should remove the head", objArray[i], ll.poll());
- }
- assertEquals("should be empty", 0, ll.size());
- assertNull("should return 'null' if list is empty", ll.poll());
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {}
- )
- public void test_remove() {
- for (int i = 0; i < objArray.length; i++) {
- assertEquals("should remove the head", objArray[i], ll.remove());
- }
- assertEquals("should be empty", 0, ll.size());
- try {
- ll.remove();
- fail("NoSuchElementException is expected when removing from the empty list");
- } catch (NoSuchElementException e) {
- //-- expected
- }
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "element",
- args = {}
- )
- public void test_element() {
- assertEquals("should return the head", objArray[0], ll.element());
- assertEquals("element() should remove nothing", objArray.length, ll.size());
- try {
- new LinkedList().remove();
- fail("NoSuchElementException is expected when the list is empty");
- } catch (NoSuchElementException e) {
- //-- expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "peek",
- args = {}
- )
- public void test_peek() {
- assertEquals("should remove the head", objArray[0], ll.peek());
- assertEquals("should remove the head", objArray[0], ll.peek());
-
- ll.clear();
-
- assertNull("should return 'null' if list is empty", ll.peek());
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() throws Exception {
- super.setUp();
- ll = new LinkedList();
- for (int i = 0; i < objArray.length; i++) {
- ll.add(objArray[i]);
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/ListResourceBundleTest.java b/luni/src/test/java/tests/api/java/util/ListResourceBundleTest.java
deleted file mode 100644
index 57ae793..0000000
--- a/luni/src/test/java/tests/api/java/util/ListResourceBundleTest.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.Enumeration;
-import java.util.ListResourceBundle;
-import java.util.Locale;
-import java.util.ResourceBundle;
-import java.util.Vector;
-
-@TestTargetClass(java.util.ListResourceBundle.class)
-public class ListResourceBundleTest extends junit.framework.TestCase {
-
- /**
- * @tests java.util.ListResourceBundle#getKeys()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getKeys",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ListResourceBundle",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getContents",
- args = {}
- )
- })
- public void test_getKeys() {
- ResourceBundle bundle;
- String name = "tests.support.Support_TestResource";
- Locale.setDefault(new Locale("en", "US"));
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
- Enumeration keys = bundle.getKeys();
- Vector result = new Vector();
- while (keys.hasMoreElements()) {
- result.addElement(keys.nextElement());
- }
- assertTrue("Missing key parent1", result.contains("parent1"));
- assertTrue("Missing key parent2", result.contains("parent2"));
- assertTrue("Missing key parent3", result.contains("parent3"));
- assertTrue("Missing key parent4", result.contains("parent4"));
- assertTrue("Missing key child1", result.contains("child1"));
- assertTrue("Missing key child2", result.contains("child2"));
- assertTrue("Missing key child3", result.contains("child3"));
- }
-
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "handleGetObject",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ListResourceBundle",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getContents",
- args = {}
- )
- })
- public void test_handleGetObjectLjava_lang_String() {
- ListResourceBundle bundle;
- String name = "tests.support.Support_TestResource";
- Locale.setDefault(new Locale("en", "US"));
- bundle = (ListResourceBundle)ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
- Enumeration keys = bundle.getKeys();
- String keyValue = null;
- Vector result = new Vector();
- while (keys.hasMoreElements()) {
- result.addElement(bundle.handleGetObject((String)keys.nextElement()));
- }
- assertEquals(9, result.size());
- assertTrue(result.contains(null));
- assertTrue(result.contains("frFRVARValue4"));
- assertTrue(result.contains("frFRVARChildValue1"));
- assertTrue(result.contains("frFRVARChildValue2"));
- assertTrue(result.contains("frFRVARChildValue3"));
- assertTrue(result.remove(null));
- assertTrue(result.remove(null));
- assertTrue(result.remove(null));
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/LocaleTest.java b/luni/src/test/java/tests/api/java/util/LocaleTest.java
deleted file mode 100644
index 82f1145..0000000
--- a/luni/src/test/java/tests/api/java/util/LocaleTest.java
+++ /dev/null
@@ -1,646 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.AndroidOnly;
-
-import java.security.Permission;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Locale;
-import java.util.MissingResourceException;
-import java.util.Set;
-
-@TestTargetClass(Locale.class)
-public class LocaleTest extends junit.framework.TestCase {
-
- Locale testLocale;
-
- Locale l;
-
- Locale defaultLocale;
-
- /**
- * @tests java.util.Locale#Locale(java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Locale",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.util.Locale(java.lang.String)
- Locale x = new Locale("xx");
- assertTrue("Failed to create Locale", x.getVariant().equals(""));
-
- try {
- new Locale(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Locale#Locale(java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Locale",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_String() {
- // Test for method java.util.Locale(java.lang.String, java.lang.String)
- Locale x = new Locale("xx", "CV");
- assertTrue("Failed to create Locale", x.getCountry().equals("CV")
- && x.getVariant().equals(""));
-
- try {
- new Locale("xx", null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- try {
- new Locale(null, "CV");
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Locale#Locale(java.lang.String, java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Locale",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String() {
- // Test for method java.util.Locale(java.lang.String, java.lang.String,
- // java.lang.String)
- Locale x = new Locale("xx", "CV", "ZZ");
- assertTrue("Failed to create Locale", x.getLanguage().equals("xx")
- && (x.getCountry().equals("CV") && x.getVariant().equals("ZZ")));
- try {
- new Locale(null, "CV", "ZZ");
- fail("expected NullPointerException with 1st parameter == null");
- } catch(NullPointerException e) {
- }
-
- try {
- new Locale("xx", null, "ZZ");
- fail("expected NullPointerException with 2nd parameter == null");
- } catch(NullPointerException e) {
- }
-
- try {
- new Locale("xx", "CV", null);
- fail("expected NullPointerException with 3rd parameter == null");
- } catch(NullPointerException e) {
- }
- }
-
- /**
- * @tests java.util.Locale#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- // Test for method java.lang.Object java.util.Locale.clone()
- assertTrue("Clone failed", l.clone().equals(l));
- }
-
- /**
- * @tests java.util.Locale#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean java.util.Locale.equals(java.lang.Object)
- Locale l2 = new Locale("en", "CA", "WIN32");
- assertTrue("Same object returned false", testLocale.equals(testLocale));
- assertTrue("Same values returned false", testLocale.equals(l2));
- assertTrue("Different locales returned true", !testLocale.equals(l));
-
- }
-
- /**
- * @tests java.util.Locale#getAvailableLocales()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAvailableLocales",
- args = {}
- )
- public void test_getAvailableLocales() {
-// BEGIN android-changed
- // Test for method java.util.Locale []
- // java.util.Locale.getAvailableLocales()
- // Assumes there will generally be about 10+ available locales...
- // even in minimal configurations for android
- try {
- Locale[] locales = Locale.getAvailableLocales();
- assertTrue("Wrong number of locales: " + locales.length, locales.length > 10);
- // regression test for HARMONY-1514
- // HashSet can filter duplicate locales
- Set<Locale> localesSet = new HashSet<Locale>(Arrays.asList(locales));
- assertEquals(localesSet.size(), locales.length);
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
-// END android-changed
- }
-
- /**
- * @tests java.util.Locale#getCountry()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCountry",
- args = {}
- )
- public void test_getCountry() {
- // Test for method java.lang.String java.util.Locale.getCountry()
- assertTrue("Returned incorrect country: " + testLocale.getCountry(),
- testLocale.getCountry().equals("CA"));
- }
-
- /**
- * @tests java.util.Locale#getDefault()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDefault",
- args = {}
- )
- public void test_getDefault() {
- // Test for method java.util.Locale java.util.Locale.getDefault()
- assertTrue("returns copy", Locale.getDefault() == Locale.getDefault());
- Locale org = Locale.getDefault();
- Locale.setDefault(l);
- Locale x = Locale.getDefault();
- Locale.setDefault(org);
- assertEquals("Failed to get locale", "fr_CA_WIN32", x.toString());
- }
-
- /**
- * @tests java.util.Locale#getDisplayCountry()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDisplayCountry",
- args = {}
- )
- @AndroidOnly("ICU has different display name for countries")
- public void test_getDisplayCountry() {
- // Test for method java.lang.String java.util.Locale.getDisplayCountry()
- assertTrue("Returned incorrect country: "
- + testLocale.getDisplayCountry(), testLocale
- .getDisplayCountry().equals("Canada"));
-
- // Regression for Harmony-1146
- Locale l_countryCD = new Locale("", "CD"); //$NON-NLS-1$ //$NON-NLS-2$
-// BEGIN android-changed
-// ICU has different display name for countries
-// assertEquals("The Democratic Republic Of Congo", //$NON-NLS-1$
-// l_countryCD.getDisplayCountry());
- assertEquals("Congo - Kinshasa", //$NON-NLS-1$
- l_countryCD.getDisplayCountry());
-// END android-changed
- }
-
- /**
- * @tests java.util.Locale#getDisplayCountry(java.util.Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDisplayCountry",
- args = {java.util.Locale.class}
- )
- public void test_getDisplayCountryLjava_util_Locale() {
- // Test for method java.lang.String
- // java.util.Locale.getDisplayCountry(java.util.Locale)
- assertEquals("Returned incorrect country", "Italie", Locale.ITALY
- .getDisplayCountry(l));
- }
-
- /**
- * @tests java.util.Locale#getDisplayLanguage()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDisplayLanguage",
- args = {}
- )
- public void test_getDisplayLanguage() {
- // Test for method java.lang.String
- // java.util.Locale.getDisplayLanguage()
- assertTrue("Returned incorrect language: "
- + testLocale.getDisplayLanguage(), testLocale
- .getDisplayLanguage().equals("English"));
-
- // Regression for Harmony-1146
- Locale l_languageAE = new Locale("ae", ""); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals("Avestan", l_languageAE.getDisplayLanguage()); //$NON-NLS-1$
- }
-
- /**
- * @tests java.util.Locale#getDisplayLanguage(java.util.Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDisplayLanguage",
- args = {java.util.Locale.class}
- )
- public void test_getDisplayLanguageLjava_util_Locale() {
- // Test for method java.lang.String
- // java.util.Locale.getDisplayLanguage(java.util.Locale)
- assertTrue("Returned incorrect language: "
- + testLocale.getDisplayLanguage(l), testLocale
- .getDisplayLanguage(l).equals("anglais"));
- }
-
- /**
- * @tests java.util.Locale#getDisplayName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDisplayName",
- args = {}
- )
- public void test_getDisplayName() {
- // Test for method java.lang.String java.util.Locale.getDisplayName()
- assertTrue("Returned incorrect name: " + testLocale.getDisplayName(),
- testLocale.getDisplayName().equals("English (Canada,WIN32)"));
- }
-
- /**
- * @tests java.util.Locale#getDisplayName(java.util.Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDisplayName",
- args = {java.util.Locale.class}
- )
- public void test_getDisplayNameLjava_util_Locale() {
- // Test for method java.lang.String
- // java.util.Locale.getDisplayName(java.util.Locale)
- assertTrue("Returned incorrect name: " + testLocale.getDisplayName(l),
- testLocale.getDisplayName(l).equals("anglais (Canada,WIN32)"));
- }
-
- /**
- * @tests java.util.Locale#getDisplayVariant()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDisplayVariant",
- args = {}
- )
- public void test_getDisplayVariant() {
- // Test for method java.lang.String java.util.Locale.getDisplayVariant()
- assertTrue("Returned incorrect variant: "
- + testLocale.getDisplayVariant(), testLocale
- .getDisplayVariant().equals("WIN32"));
- }
-
- /**
- * @tests java.util.Locale#getDisplayVariant(java.util.Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDisplayVariant",
- args = {java.util.Locale.class}
- )
- public void test_getDisplayVariantLjava_util_Locale() {
- // Test for method java.lang.String
- // java.util.Locale.getDisplayVariant(java.util.Locale)
- assertTrue("Returned incorrect variant: "
- + testLocale.getDisplayVariant(l), testLocale
- .getDisplayVariant(l).equals("WIN32"));
- }
-
- /**
- * @tests java.util.Locale#getISO3Country()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getISO3Country",
- args = {}
- )
- public void test_getISO3Country() {
- // Test for method java.lang.String java.util.Locale.getISO3Country()
- assertTrue("Returned incorrect ISO3 country: "
- + testLocale.getISO3Country(), testLocale.getISO3Country()
- .equals("CAN"));
-
- Locale l = new Locale("", "CD");
- assertEquals("COD", l.getISO3Country());
-
- Locale x = new Locale("xx", "C");
- try {
- x.getISO3Country();
- } catch (MissingResourceException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Locale#getISO3Language()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getISO3Language",
- args = {}
- )
- public void test_getISO3Language() {
- // Test for method java.lang.String java.util.Locale.getISO3Language()
- assertTrue("Returned incorrect ISO3 language: "
- + testLocale.getISO3Language(), testLocale.getISO3Language()
- .equals("eng"));
-
- Locale l = new Locale("ae");
- assertEquals("ave", l.getISO3Language());
-
- // Regression for Harmony-1146
- Locale l_CountryCS = new Locale("", "CS"); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals("SCG", l_CountryCS.getISO3Country()); //$NON-NLS-1$
-
- // Regression for Harmony-1129
- l = new Locale("ak", ""); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals("aka", l.getISO3Language()); //$NON-NLS-1$
-
- Locale x = new Locale("xx", "C");
- try {
- x.getISO3Language();
- } catch (MissingResourceException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Locale#getISOCountries()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getISOCountries",
- args = {}
- )
- public void test_getISOCountries() {
- // Test for method java.lang.String []
- // java.util.Locale.getISOCountries()
- // Assumes all countries are 2 digits, and that there will always be
- // 230 countries on the list...
- String[] isoCountries = Locale.getISOCountries();
- int length = isoCountries.length;
- int familiarCount = 0;
- for (int i = 0; i < length; i++) {
- if (isoCountries[i].length() != 2) {
- fail("Wrong format for ISOCountries.");
- }
- if (isoCountries[i].equals("CA") || isoCountries[i].equals("BB")
- || isoCountries[i].equals("US")
- || isoCountries[i].equals("KR"))
- familiarCount++;
- }
- assertTrue("ISOCountries missing.", familiarCount == 4 && length > 230);
- }
-
- /**
- * @tests java.util.Locale#getISOLanguages()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getISOLanguages",
- args = {}
- )
- public void test_getISOLanguages() {
- // Test for method java.lang.String []
- // java.util.Locale.getISOLanguages()
- // Assumes always at least 131 ISOlanguages...
- String[] isoLang = Locale.getISOLanguages();
- int length = isoLang.length;
- assertTrue("Random element in wrong format.", (isoLang[length / 2]
- .length() == 2)
- && isoLang[length / 2].toLowerCase()
- .equals(isoLang[length / 2]));
- assertTrue("Wrong number of ISOLanguages.", length > 130);
- }
-
- /**
- * @tests java.util.Locale#getLanguage()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLanguage",
- args = {}
- )
- public void test_getLanguage() {
- // Test for method java.lang.String java.util.Locale.getLanguage()
- assertTrue("Returned incorrect language: " + testLocale.getLanguage(),
- testLocale.getLanguage().equals("en"));
- }
-
- /**
- * @tests java.util.Locale#getVariant()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getVariant",
- args = {}
- )
- public void test_getVariant() {
- // Test for method java.lang.String java.util.Locale.getVariant()
- assertTrue("Returned incorrect variant: " + testLocale.getVariant(),
- testLocale.getVariant().equals("WIN32"));
- }
-
- SecurityManager sm = new SecurityManager() {
- final String forbidenPermissionName = "user.language";
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals(forbidenPermissionName)) {
- throw new SecurityException();
- }
- }
- };
- /**
- * @tests java.util.Locale#setDefault(java.util.Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setDefault",
- args = {java.util.Locale.class}
- )
- public void test_setDefaultLjava_util_Locale() {
- // Test for method void java.util.Locale.setDefault(java.util.Locale)
-
- Locale org = Locale.getDefault();
- Locale.setDefault(l);
- Locale x = Locale.getDefault();
- Locale.setDefault(org);
- assertEquals("Failed to set locale", "fr_CA_WIN32", x.toString());
-
- Locale.setDefault(new Locale("tr", ""));
- String res1 = "\u0069".toUpperCase();
- String res2 = "\u0049".toLowerCase();
- Locale.setDefault(org);
- assertEquals("Wrong toUppercase conversion", "\u0130", res1);
- assertEquals("Wrong toLowercase conversion", "\u0131", res2);
-
- try {
- Locale.setDefault(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- Locale.setDefault(Locale.CANADA);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.util.Locale#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.util.Locale.toString()
- assertEquals("Returned incorrect string representation", "en_CA_WIN32", testLocale
- .toString());
-
- Locale l = new Locale("en", "");
- assertEquals("Wrong representation 1", "en", l.toString());
- l = new Locale("", "CA");
- assertEquals("Wrong representation 2", "_CA", l.toString());
- l = new Locale("", "CA", "var");
- assertEquals("Wrong representation 2.5", "_CA_var", l.toString());
- l = new Locale("en", "", "WIN");
- assertEquals("Wrong representation 4", "en__WIN", l.toString());
- l = new Locale("en", "CA");
- assertEquals("Wrong representation 6", "en_CA", l.toString());
- l = new Locale("en", "CA", "VAR");
- assertEquals("Wrong representation 7", "en_CA_VAR", l.toString());
-
- l = new Locale("", "", "var");
- assertEquals("Wrong representation 8", "", l.toString());
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- Locale l1 = new Locale("en", "US");
- Locale l2 = new Locale("fr", "CA");
-
- assertTrue(l1.hashCode() != l2.hashCode());
- }
-
-// BEGIN android-removed
-// These locales are not part of the android reference impl
-// // Regression Test for HARMONY-2953
-// public void test_getISO() {
-// Locale locale = new Locale("an");
-// assertEquals("arg", locale.getISO3Language());
-//
-// locale = new Locale("PS");
-// assertEquals("pus", locale.getISO3Language());
-//
-// List<String> languages = Arrays.asList(Locale.getISOLanguages());
-// assertTrue(languages.contains("ak"));
-//
-// List<String> countries = Arrays.asList(Locale.getISOCountries());
-// assertTrue(countries.contains("CS"));
-// }
-// END android-removed
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- defaultLocale = Locale.getDefault();
- Locale.setDefault(Locale.US);
- testLocale = new Locale("en", "CA", "WIN32");
- l = new Locale("fr", "CA", "WIN32");
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- Locale.setDefault(defaultLocale);
- }
-}
-
-
diff --git a/luni/src/test/java/tests/api/java/util/MissingResourceExceptionTest.java b/luni/src/test/java/tests/api/java/util/MissingResourceExceptionTest.java
deleted file mode 100644
index 468e122..0000000
--- a/luni/src/test/java/tests/api/java/util/MissingResourceExceptionTest.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.Locale;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-@TestTargetClass(MissingResourceException.class)
-public class MissingResourceExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.util.MissingResourceException#MissingResourceException(java.lang.String,
- * java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "MissingResourceException",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String() {
- // Test for method java.util.MissingResourceException(java.lang.String,
- // java.lang.String, java.lang.String)
- assertNotNull(new MissingResourceException("Detail string", "Class name string", "Key string"));
- assertNotNull(new MissingResourceException(null, "Class name string", "Key string"));
- assertNotNull(new MissingResourceException("Detail string", null, "Key string"));
- assertNotNull(new MissingResourceException("Detail string", "Class name string", null));
- try {
- ResourceBundle.getBundle("Non-ExistentBundle");
- } catch (MissingResourceException e) {
- return;
- }
- fail("Failed to generate expected exception");
- }
-
- /**
- * @tests java.util.MissingResourceException#getClassName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getClassName",
- args = {}
- )
- public void test_getClassName() {
- // Test for method java.lang.String
- // java.util.MissingResourceException.getClassName()
- try {
- ResourceBundle.getBundle("Non-ExistentBundle");
- } catch (MissingResourceException e) {
- assertEquals("Returned incorrect class name", "Non-ExistentBundle"
- + '_' + Locale.getDefault(), e.getClassName());
- }
- }
-
- /**
- * @tests java.util.MissingResourceException#getKey()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getKey",
- args = {}
- )
- public void test_getKey() {
- // Test for method java.lang.String
- // java.util.MissingResourceException.getKey()
- try {
- ResourceBundle.getBundle("Non-ExistentBundle");
- } catch (MissingResourceException e) {
- assertTrue("Returned incorrect class name", e.getKey().equals(""));
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/NoSuchElementExceptionTest.java b/luni/src/test/java/tests/api/java/util/NoSuchElementExceptionTest.java
deleted file mode 100644
index 8f795e8..0000000
--- a/luni/src/test/java/tests/api/java/util/NoSuchElementExceptionTest.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.NoSuchElementException;
-import java.util.Vector;
-
-@TestTargetClass(NoSuchElementException.class)
-public class NoSuchElementExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.util.NoSuchElementException#NoSuchElementException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NoSuchElementException",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.NoSuchElementException()
-
- assertNotNull(new NoSuchElementException());
-
- try {
- Vector v = new Vector();
- v.elements().nextElement();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.NoSuchElementException#NoSuchElementException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NoSuchElementException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.util.NoSuchElementException(java.lang.String)
-
- assertNotNull(new NoSuchElementException("String"));
- assertNotNull(new NoSuchElementException(null));
-
- try {
- Vector v = new Vector();
- v.firstElement();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/ObservableTest.java b/luni/src/test/java/tests/api/java/util/ObservableTest.java
deleted file mode 100644
index 8164eff..0000000
--- a/luni/src/test/java/tests/api/java/util/ObservableTest.java
+++ /dev/null
@@ -1,322 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.Observable;
-import java.util.Observer;
-import java.util.Vector;
-
-@TestTargetClass(Observable.class)
-public class ObservableTest extends junit.framework.TestCase {
-
- static class TestObserver implements Observer {
- public Vector objv = new Vector();
-
- int updateCount = 0;
-
- public void update(Observable observed, Object arg) {
- ++updateCount;
- objv.add(arg);
- }
-
- public int updateCount() {
- return updateCount;
- }
-
- }
-
- static class DeleteTestObserver implements Observer {
- int updateCount = 0;
-
- boolean deleteAll = false;
-
- public DeleteTestObserver(boolean all) {
- deleteAll = all;
- }
-
- public void update(Observable observed, Object arg) {
- ++updateCount;
- if (deleteAll)
- observed.deleteObservers();
- else
- observed.deleteObserver(this);
- }
-
- public int updateCount() {
- return updateCount;
- }
-
- }
-
- static class TestObservable extends Observable {
- public void doChange() {
- setChanged();
- }
-
- public void clearChange() {
- clearChanged();
- }
- }
-
- Observer observer;
-
- TestObservable observable;
-
- /**
- * @tests java.util.Observable#Observable()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Observable",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.Observable()
- try {
- Observable ov = new Observable();
- assertTrue("Wrong initial values.", !ov.hasChanged());
- assertEquals("Wrong initial values.", 0, ov.countObservers());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.util.Observable#addObserver(java.util.Observer)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addObserver",
- args = {java.util.Observer.class}
- )
- public void test_addObserverLjava_util_Observer() {
- // Test for method void
- // java.util.Observable.addObserver(java.util.Observer)
- TestObserver test = new TestObserver();
- observable.addObserver(test);
- assertEquals("Failed to add observer", 1, observable.countObservers());
- observable.addObserver(test);
- assertEquals("Duplicate observer", 1, observable.countObservers());
-
- Observable o = new Observable();
- try {
- o.addObserver(null);
- fail("Expected adding a null observer to throw a NPE.");
- } catch (NullPointerException ex) {
- // expected;
- } catch (Throwable ex) {
- fail("Did not expect adding a new observer to throw a "
- + ex.getClass().getName());
- }
- }
-
- /**
- * @tests java.util.Observable#countObservers()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "countObservers",
- args = {}
- )
- public void test_countObservers() {
- // Test for method int java.util.Observable.countObservers()
- assertEquals("New observable had > 0 observers", 0, observable
- .countObservers());
- observable.addObserver(new TestObserver());
- assertEquals("Observable with observer returned other than 1", 1, observable
- .countObservers());
- }
-
- /**
- * @tests java.util.Observable#deleteObserver(java.util.Observer)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "deleteObserver",
- args = {java.util.Observer.class}
- )
- public void test_deleteObserverLjava_util_Observer() {
- // Test for method void
- // java.util.Observable.deleteObserver(java.util.Observer)
- observable.addObserver(observer = new TestObserver());
- observable.deleteObserver(observer);
- assertEquals("Failed to delete observer",
- 0, observable.countObservers());
- observable.deleteObserver(observer);
- observable.deleteObserver(null);
- }
-
- /**
- * @tests java.util.Observable#deleteObservers()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "deleteObservers",
- args = {}
- )
- public void test_deleteObservers() {
- // Test for method void java.util.Observable.deleteObservers()
- observable.addObserver(new TestObserver());
- observable.addObserver(new TestObserver());
- observable.addObserver(new TestObserver());
- observable.addObserver(new TestObserver());
- observable.addObserver(new TestObserver());
- observable.addObserver(new TestObserver());
- observable.addObserver(new TestObserver());
- observable.addObserver(new TestObserver());
- observable.deleteObservers();
- assertEquals("Failed to delete observers",
- 0, observable.countObservers());
- }
-
- /**
- * @tests java.util.Observable#hasChanged()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasChanged",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setChanged",
- args = {}
- )
- })
- public void test_hasChanged() {
- assertFalse(observable.hasChanged());
- observable.addObserver(observer = new TestObserver());
- observable.doChange();
- assertTrue(observable.hasChanged());
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setChanged",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clearChanged",
- args = {}
- )
- })
- public void test_clearChanged() {
- assertFalse(observable.hasChanged());
- observable.addObserver(observer = new TestObserver());
- observable.doChange();
- assertTrue(observable.hasChanged());
- observable.clearChange();
- assertFalse(observable.hasChanged());
- }
-
- /**
- * @tests java.util.Observable#notifyObservers()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "notifyObservers",
- args = {}
- )
- public void test_notifyObservers() {
- // Test for method void java.util.Observable.notifyObservers()
- observable.addObserver(observer = new TestObserver());
- observable.notifyObservers();
- assertEquals("Notified when unchnaged", 0, ((TestObserver) observer)
- .updateCount());
- ((TestObservable) observable).doChange();
- observable.notifyObservers();
- assertEquals("Failed to notify",
- 1, ((TestObserver) observer).updateCount());
-
- DeleteTestObserver observer1, observer2;
- observable.deleteObservers();
- observable.addObserver(observer1 = new DeleteTestObserver(false));
- observable.addObserver(observer2 = new DeleteTestObserver(false));
- observable.doChange();
- observable.notifyObservers();
- assertTrue("Failed to notify all", observer1.updateCount() == 1
- && observer2.updateCount() == 1);
- assertEquals("Failed to delete all", 0, observable.countObservers());
-
- observable.addObserver(observer1 = new DeleteTestObserver(false));
- observable.addObserver(observer2 = new DeleteTestObserver(false));
- observable.doChange();
- observable.notifyObservers();
- assertTrue("Failed to notify all 2", observer1.updateCount() == 1
- && observer2.updateCount() == 1);
- assertEquals("Failed to delete all 2", 0, observable.countObservers());
- }
-
- /**
- * @tests java.util.Observable#notifyObservers(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "notifyObservers",
- args = {java.lang.Object.class}
- )
- public void test_notifyObserversLjava_lang_Object() {
- // Test for method void
- // java.util.Observable.notifyObservers(java.lang.Object)
- Object obj;
- observable.addObserver(observer = new TestObserver());
- observable.notifyObservers();
- assertEquals("Notified when unchanged", 0, ((TestObserver) observer)
- .updateCount());
- ((TestObservable) observable).doChange();
- observable.notifyObservers(obj = new Object());
- assertEquals("Failed to notify",
- 1, ((TestObserver) observer).updateCount());
- assertTrue("Failed to pass Object arg", ((TestObserver) observer).objv
- .elementAt(0).equals(obj));
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- observable = new TestObservable();
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/PriorityQueueTest.java b/luni/src/test/java/tests/api/java/util/PriorityQueueTest.java
deleted file mode 100644
index 140eb4d..0000000
--- a/luni/src/test/java/tests/api/java/util/PriorityQueueTest.java
+++ /dev/null
@@ -1,1026 +0,0 @@
-/* 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Comparator;
-import java.util.Iterator;
-import java.util.List;
-import java.util.NoSuchElementException;
-import java.util.PriorityQueue;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-import tests.util.SerializationTester;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(PriorityQueue.class)
-public class PriorityQueueTest extends TestCase {
-
- private static final String SERIALIZATION_FILE_NAME = "/serialization/tests/api/java/util/PriorityQueue.golden.ser"; //$NON-NLS-1$
-
- /**
- * @tests java.util.PriorityQueue#iterator()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "iterator",
- args = {}
- )
- public void test_iterator() {
- PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
- Integer[] array = { 2, 45, 7, -12, 9 };
- for (int i = 0; i < array.length; i++) {
- integerQueue.offer(array[i]);
- }
- Iterator<Integer> iter = integerQueue.iterator();
- assertNotNull(iter);
- ArrayList<Integer> iterResult = new ArrayList<Integer>();
- while (iter.hasNext()) {
- iterResult.add(iter.next());
- }
- Object[] resultArray = iterResult.toArray();
- Arrays.sort(array);
- Arrays.sort(resultArray);
- assertTrue(Arrays.equals(array, resultArray));
- }
-
- /**
- * @tests java.util.PriorityQueue#iterator()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NoSuchElementException, IllegalStateException.",
- method = "iterator",
- args = {}
- )
- public void test_iterator_empty() {
- PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
- Iterator<Integer> iter = integerQueue.iterator();
- try {
- iter.next();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // expected
- }
-
- iter = integerQueue.iterator();
- try {
- iter.remove();
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.PriorityQueue#iterator()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NoSuchElementException.",
- method = "iterator",
- args = {}
- )
- public void test_iterator_outofbound() {
- PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
- integerQueue.offer(0);
- Iterator<Integer> iter = integerQueue.iterator();
- iter.next();
- try {
- iter.next();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // expected
- }
-
- iter = integerQueue.iterator();
- iter.next();
- iter.remove();
- try {
- iter.next();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.PriorityQueue#iterator()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "iterator",
- args = {}
- )
- public void test_iterator_remove() {
- PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
- Integer[] array = { 2, 45, 7, -12, 9 };
- for (int i = 0; i < array.length; i++) {
- integerQueue.offer(array[i]);
- }
- Iterator<Integer> iter = integerQueue.iterator();
- assertNotNull(iter);
- for (int i = 0; i < array.length; i++) {
- iter.next();
- if (2 == i) {
- iter.remove();
- }
- }
- assertEquals(array.length - 1, integerQueue.size());
-
- iter = integerQueue.iterator();
- Integer[] newArray = new Integer[array.length - 1];
- for (int i = 0; i < newArray.length; i++) {
- newArray[i] = iter.next();
- }
-
- Arrays.sort(newArray);
- for (int i = 0; i < integerQueue.size(); i++) {
- assertEquals(newArray[i], integerQueue.poll());
- }
-
- }
-
- /**
- * @tests java.util.PriorityQueue#iterator()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalStateException.",
- method = "iterator",
- args = {}
- )
- public void test_iterator_remove_illegalState() {
- PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
- Integer[] array = { 2, 45, 7, -12, 9 };
- for (int i = 0; i < array.length; i++) {
- integerQueue.offer(array[i]);
- }
- Iterator<Integer> iter = integerQueue.iterator();
- assertNotNull(iter);
- try {
- iter.remove();
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- iter.next();
- iter.remove();
- try {
- iter.remove();
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- }
-
- /**
- * @tests java.util.PriorityQueue.size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- public void test_size() {
- PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
- assertEquals(0, integerQueue.size());
- int[] array = { 2, 45, 7, -12, 9 };
- for (int i = 0; i < array.length; i++) {
- integerQueue.offer(array[i]);
- }
- assertEquals(array.length, integerQueue.size());
- }
-
- /**
- * @tests java.util.PriorityQueue#PriorityQueue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PriorityQueue",
- args = {}
- )
- public void test_Constructor() {
- PriorityQueue<Object> queue = new PriorityQueue<Object>();
- assertNotNull(queue);
- assertEquals(0, queue.size());
- assertNull(queue.comparator());
- }
-
- /**
- * @tests java.util.PriorityQueue#PriorityQueue(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PriorityQueue",
- args = {int.class}
- )
- public void test_ConstructorI() {
- PriorityQueue<Object> queue = new PriorityQueue<Object>(100);
- assertNotNull(queue);
- assertEquals(0, queue.size());
- assertNull(queue.comparator());
-
- try {
- new PriorityQueue(0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.PriorityQueue#PriorityQueue(int, Comparator<? super E>)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify IllegalArgumentException.",
- method = "PriorityQueue",
- args = {int.class, java.util.Comparator.class}
- )
- public void test_ConstructorILjava_util_Comparator() {
- PriorityQueue<Object> queue = new PriorityQueue<Object>(100,
- (Comparator<Object>) null);
- assertNotNull(queue);
- assertEquals(0, queue.size());
- assertNull(queue.comparator());
-
- MockComparator<Object> comparator = new MockComparator<Object>();
- queue = new PriorityQueue<Object>(100, comparator);
- assertNotNull(queue);
- assertEquals(0, queue.size());
- assertEquals(comparator, queue.comparator());
- }
-
- /**
- * @tests java.util.PriorityQueue#PriorityQueue(int, Comparator<? super E>)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies IllegalArgumentException.",
- method = "PriorityQueue",
- args = {int.class, java.util.Comparator.class}
- )
- public void test_ConstructorILjava_util_Comparator_illegalCapacity() {
- try {
- new PriorityQueue<Object>(0, new MockComparator<Object>());
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- try {
- new PriorityQueue<Object>(-1, new MockComparator<Object>());
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.PriorityQueue#PriorityQueue(int, Comparator<? super E>)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify IllegalArgumentException.",
- method = "PriorityQueue",
- args = {int.class, java.util.Comparator.class}
- )
- public void test_ConstructorILjava_util_Comparator_cast() {
- MockComparatorCast<Object> objectComparator = new MockComparatorCast<Object>();
- PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>(100,
- objectComparator);
- assertNotNull(integerQueue);
- assertEquals(0, integerQueue.size());
- assertEquals(objectComparator, integerQueue.comparator());
- Integer[] array = { 2, 45, 7, -12, 9 };
- List<Integer> list = Arrays.asList(array);
- integerQueue.addAll(list);
- assertEquals(list.size(), integerQueue.size());
- // just test here no cast exception raises.
- }
-
- /**
- * @tests java.util.PriorityQueue#PriorityQueue(Collection)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ClassCastException, NullPointerException.",
- method = "PriorityQueue",
- args = {java.util.Collection.class}
- )
- public void test_ConstructorLjava_util_Colleciton() {
- Integer[] array = { 2, 45, 7, -12, 9 };
- List<Integer> list = Arrays.asList(array);
- PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>(list);
- assertEquals(array.length, integerQueue.size());
- assertNull(integerQueue.comparator());
- Arrays.sort(array);
- for (int i = 0; i < array.length; i++) {
- assertEquals(array[i], integerQueue.poll());
- }
- }
-
- /**
- * @tests java.util.PriorityQueue#PriorityQueue(Collection)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "PriorityQueue",
- args = {java.util.Collection.class}
- )
- public void test_ConstructorLjava_util_Colleciton_null() {
- ArrayList<Object> list = new ArrayList<Object>();
- list.add(new Float(11));
- list.add(null);
- list.add(new Integer(10));
- try {
- new PriorityQueue<Object>(list);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.PriorityQueue#PriorityQueue(Collection)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ClassCastException.",
- method = "PriorityQueue",
- args = {java.util.Collection.class}
- )
- public void test_ConstructorLjava_util_Colleciton_non_comparable() {
- ArrayList<Object> list = new ArrayList<Object>();
- list.add(new Float(11));
- list.add(new Integer(10));
- try {
- new PriorityQueue<Object>(list);
- fail("should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.PriorityQueue#PriorityQueue(Collection)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ClassCastException, NullPointerException.",
- method = "PriorityQueue",
- args = {java.util.Collection.class}
- )
- public void test_ConstructorLjava_util_Colleciton_from_priorityqueue() {
- String[] array = { "AAAAA", "AA", "AAAA", "AAAAAAAA" };
- PriorityQueue<String> queue = new PriorityQueue<String>(4,
- new MockComparatorStringByLength());
- for (int i = 0; i < array.length; i++) {
- queue.offer(array[i]);
- }
- Collection<String> c = queue;
- PriorityQueue<String> constructedQueue = new PriorityQueue<String>(c);
- assertEquals(queue.comparator(), constructedQueue.comparator());
- while (queue.size() > 0) {
- assertEquals(queue.poll(), constructedQueue.poll());
- }
- assertEquals(0, constructedQueue.size());
- }
-
- /**
- * @tests java.util.PriorityQueue#PriorityQueue(Collection)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ClassCastException, NullPointerException.",
- method = "PriorityQueue",
- args = {java.util.Collection.class}
- )
- public void test_ConstructorLjava_util_Colleciton_from_sortedset() {
- int[] array = { 3, 5, 79, -17, 5 };
- TreeSet<Integer> treeSet = new TreeSet<Integer>(new MockComparator<Integer>());
- for (int i = 0; i < array.length; i++) {
- treeSet.add(array[i]);
- }
- Collection<? extends Integer> c = treeSet;
- PriorityQueue<Integer> queue = new PriorityQueue<Integer>(c);
- assertEquals(treeSet.comparator(), queue.comparator());
- Iterator<Integer> iter = treeSet.iterator();
- while (iter.hasNext()) {
- assertEquals(iter.next(), queue.poll());
- }
- assertEquals(0, queue.size());
- }
-
- /**
- * @tests java.util.PriorityQueue#PriorityQueue(PriorityQueue<? * extends
- * E>)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "ClassCastException can not be checked.",
- method = "PriorityQueue",
- args = {java.util.PriorityQueue.class}
- )
- public void test_ConstructorLjava_util_PriorityQueue() {
- PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
- int[] array = { 2, 45, 7, -12, 9 };
- for (int i = 0; i < array.length; i++) {
- integerQueue.offer(array[i]);
- }
- PriorityQueue objectQueue = new PriorityQueue(
- integerQueue);
- assertEquals(integerQueue.size(), objectQueue.size());
- assertEquals(integerQueue.comparator(), objectQueue.comparator());
- Arrays.sort(array);
- for (int i = 0; i < array.length; i++) {
- assertEquals(array[i], objectQueue.poll());
- }
-
- try {
- new PriorityQueue((PriorityQueue)null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.PriorityQueue#PriorityQueue(PriorityQueue<? * extends
- * E>)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "PriorityQueue",
- args = {java.util.PriorityQueue.class}
- )
- public void test_ConstructorLjava_util_PriorityQueue_null() {
- try {
- new PriorityQueue<Object>((PriorityQueue<Integer>) null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.PriorityQueue#PriorityQueue(SortedSet<? extends E>)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify ClassCastException, NullPointerException.",
- method = "PriorityQueue",
- args = {java.util.SortedSet.class}
- )
- public void test_ConstructorLjava_util_SortedSet() {
- int[] array = { 3, 5, 79, -17, 5 };
- TreeSet<Integer> treeSet = new TreeSet<Integer>();
- for (int i = 0; i < array.length; i++) {
- treeSet.add(array[i]);
- }
- PriorityQueue<Integer> queue = new PriorityQueue<Integer>(treeSet);
- Iterator<Integer> iter = treeSet.iterator();
- while (iter.hasNext()) {
- assertEquals(iter.next(), queue.poll());
- }
- }
-
- /**
- * @tests java.util.PriorityQueue#PriorityQueue(SortedSet<? extends E>)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "PriorityQueue",
- args = {java.util.SortedSet.class}
- )
- public void test_ConstructorLjava_util_SortedSet_null() {
- try {
- new PriorityQueue<Integer>((SortedSet<? extends Integer>) null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.PriorityQueue#offer(Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify exceptions.",
- method = "offer",
- args = {java.lang.Object.class}
- )
- public void test_offerLjava_lang_Object() {
- PriorityQueue<String> queue = new PriorityQueue<String>(10,
- new MockComparatorStringByLength());
- String[] array = { "AAAAA", "AA", "AAAA", "AAAAAAAA" };
- for (int i = 0; i < array.length; i++) {
- queue.offer(array[i]);
- }
- String[] sortedArray = { "AA", "AAAA", "AAAAA", "AAAAAAAA" };
- for (int i = 0; i < sortedArray.length; i++) {
- assertEquals(sortedArray[i], queue.poll());
- }
- assertEquals(0, queue.size());
- assertNull(queue.poll());
- }
-
- /**
- * @tests java.util.PriorityQueue#offer(Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "offer",
- args = {java.lang.Object.class}
- )
- public void test_offerLjava_lang_Object_null() {
- PriorityQueue<Object> queue = new PriorityQueue<Object>();
- try {
- queue.offer(null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.PriorityQueue#offer(Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ClassCastException.",
- method = "offer",
- args = {java.lang.Object.class}
- )
- public void test_offer_Ljava_lang_Object_non_Comparable() {
- PriorityQueue<Object> queue = new PriorityQueue<Object>();
- queue.offer(new Integer(10));
- try {
- queue.offer(new Float(1.3));
- fail("should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
-
- queue = new PriorityQueue<Object>();
- queue.offer(new Integer(10));
- try {
- queue.offer(new Object());
- fail("should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.PriorityQueue#poll()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "poll",
- args = {}
- )
- public void test_poll() {
- PriorityQueue<String> stringQueue = new PriorityQueue<String>();
- String[] array = { "MYTESTSTRING", "AAAAA", "BCDEF", "ksTRD", "AAAAA" };
- for (int i = 0; i < array.length; i++) {
- stringQueue.offer(array[i]);
- }
- Arrays.sort(array);
- for (int i = 0; i < array.length; i++) {
- assertEquals(array[i], stringQueue.poll());
- }
- assertEquals(0, stringQueue.size());
- assertNull(stringQueue.poll());
- }
-
- /**
- * @tests java.util.PriorityQueue#poll()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies poll method for empty queue.",
- method = "poll",
- args = {}
- )
- public void test_poll_empty() {
- PriorityQueue<Object> queue = new PriorityQueue<Object>();
- assertEquals(0, queue.size());
- assertNull(queue.poll());
- }
-
- /**
- * @tests java.util.PriorityQueue#peek()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "peek",
- args = {}
- )
- public void test_peek() {
- PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
- int[] array = { 2, 45, 7, -12, 9 };
- for (int i = 0; i < array.length; i++) {
- integerQueue.add(array[i]);
- }
- Arrays.sort(array);
- assertEquals(new Integer(array[0]), integerQueue.peek());
- assertEquals(new Integer(array[0]), integerQueue.peek());
- }
-
- /**
- * @tests java.util.PriorityQueue#peek()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies peek method for empty queue.",
- method = "peek",
- args = {}
- )
- public void test_peek_empty() {
- PriorityQueue<Object> queue = new PriorityQueue<Object>();
- assertEquals(0, queue.size());
- assertNull(queue.peek());
- assertNull(queue.peek());
- }
-
- /**
- * @tests java.util.PriorityQueue#Clear()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
- int[] array = { 2, 45, 7, -12, 9 };
- for (int i = 0; i < array.length; i++) {
- integerQueue.offer(array[i]);
- }
- integerQueue.clear();
- assertTrue(integerQueue.isEmpty());
- }
-
- /**
- * @tests java.util.PriorityQueue#add(Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify NullPointerException, ClassCastException.",
- method = "add",
- args = {java.lang.Object.class}
- )
- public void test_add_Ljava_lang_Object() {
- PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>();
- Integer[] array = { 2, 45, 7, -12, 9 };
- for (int i = 0; i < array.length; i++) {
- integerQueue.add(array[i]);
- }
- Arrays.sort(array);
- assertEquals(array.length, integerQueue.size());
- for (int i = 0; i < array.length; i++) {
- assertEquals(array[i], integerQueue.poll());
- }
- assertEquals(0, integerQueue.size());
- }
-
- /**
- * @tests java.util.PriorityQueue#add(Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException.",
- method = "add",
- args = {java.lang.Object.class}
- )
- public void test_add_Ljava_lang_Object_null() {
- PriorityQueue<Object> queue = new PriorityQueue<Object>();
- try {
- queue.add(null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.PriorityQueue#add(Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ClassCastException.",
- method = "add",
- args = {java.lang.Object.class}
- )
- public void test_add_Ljava_lang_Object_non_Comparable() {
- PriorityQueue<Object> queue = new PriorityQueue<Object>();
- queue.add(new Integer(10));
- try {
- queue.add(new Float(1.3));
- fail("should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
-
- queue = new PriorityQueue<Object>();
- queue.add(new Integer(10));
- try {
- queue.add(new Object());
- fail("should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.PriorityQueue#remove(Object)
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_remove_Ljava_lang_Object() {
- Integer[] array = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 16, 39 };
- List<Integer> list = Arrays.asList(array);
- PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>(list);
- assertTrue(integerQueue.remove(16));
- Integer[] newArray = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 39 };
- Arrays.sort(newArray);
- for (int i = 0; i < newArray.length; i++) {
- assertEquals(newArray[i], integerQueue.poll());
- }
- assertEquals(0, integerQueue.size());
- }
-
- /**
- * @tests java.util.PriorityQueue#remove(Object)
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_remove_Ljava_lang_Object_using_comparator() {
- PriorityQueue<String> queue = new PriorityQueue<String>(10,
- new MockComparatorStringByLength());
- String[] array = { "AAAAA", "AA", "AAAA", "AAAAAAAA" };
- for (int i = 0; i < array.length; i++) {
- queue.offer(array[i]);
- }
- assertFalse(queue.contains("BB"));
- assertTrue(queue.remove("BB"));
- }
-
- /**
- * @tests java.util.PriorityQueue#remove(Object)
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ClassCastException.",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_remove_Ljava_lang_Object_not_exists() {
- Integer[] array = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 16, 39 };
- List<Integer> list = Arrays.asList(array);
- PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>(list);
- assertFalse(integerQueue.remove(111));
- assertFalse(integerQueue.remove(null));
- try {
- integerQueue.remove("");
- fail("should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.PriorityQueue#remove(Object)
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies null as a parameter.",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_remove_Ljava_lang_Object_null() {
- Integer[] array = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 16, 39 };
- List<Integer> list = Arrays.asList(array);
- PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>(list);
- assertFalse(integerQueue.remove(null));
- }
-
- /**
- * @tests java.util.PriorityQueue#remove(Object)
- *
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies ClassCastException.",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_remove_Ljava_lang_Object_not_Compatible() {
- Integer[] array = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 16, 39 };
- List<Integer> list = Arrays.asList(array);
- PriorityQueue<Integer> integerQueue = new PriorityQueue<Integer>(list);
- try {
- integerQueue.remove(new Float(1.3F));
- fail("should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
-
- // although argument element type is not compatible with those in queue,
- // but comparator supports it.
- MockComparator<Object> comparator = new MockComparator<Object>();
- PriorityQueue<Integer> integerQueue1 = new PriorityQueue<Integer>(100,
- comparator);
- integerQueue1.offer(1);
- assertFalse(integerQueue1.remove(new Float(1.3F)));
-
- PriorityQueue<Object> queue = new PriorityQueue<Object>();
- Object o = new Object();
- queue.offer(o);
- try {
- queue.remove(o);
- fail("should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.PriorityQueue#comparator()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "comparator",
- args = {}
- )
- public void test_comparator() {
- PriorityQueue<Object> queue = new PriorityQueue<Object>();
- assertNull(queue.comparator());
-
- MockComparator<Object> comparator = new MockComparator<Object>();
- queue = new PriorityQueue<Object>(100, comparator);
- assertEquals(comparator, queue.comparator());
- }
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization.",
- method = "!SerializationSelf",
- args = {}
- )
- public void test_Serialization() throws Exception {
- Integer[] array = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 16, 39 };
- List<Integer> list = Arrays.asList(array);
- PriorityQueue<Integer> srcIntegerQueue = new PriorityQueue<Integer>(
- list);
- PriorityQueue<Integer> destIntegerQueue = (PriorityQueue<Integer>) SerializationTester
- .getDeserilizedObject(srcIntegerQueue);
- Arrays.sort(array);
- for (int i = 0; i < array.length; i++) {
- assertEquals(array[i], destIntegerQueue.poll());
- }
- assertEquals(0, destIntegerQueue.size());
- }
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization.",
- method = "!SerializationSelf",
- args = {}
- )
- public void test_Serialization_casting() throws Exception {
- Integer[] array = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 16, 39 };
- List<Integer> list = Arrays.asList(array);
- PriorityQueue<Integer> srcIntegerQueue = new PriorityQueue<Integer>(
- list);
- PriorityQueue<String> destStringQueue = (PriorityQueue<String>) SerializationTester
- .getDeserilizedObject(srcIntegerQueue);
- // will not incur class cast exception.
- Object o = destStringQueue.peek();
- Arrays.sort(array);
- Integer I = (Integer) o;
- assertEquals(array[0], I);
- }
-
- /**
- * @tests serialization/deserialization compatibility with RI.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationGolden",
- args = {}
- )
- public void test_SerializationCompatibility_cast() throws Exception {
- Integer[] array = { 2, 45, 7, -12, 9, 23, 17, 1118, 10, 16, 39 };
- List<Integer> list = Arrays.asList(array);
- PriorityQueue<Integer> srcIntegerQueue = new PriorityQueue<Integer>(
- list);
- PriorityQueue<String> destStringQueue = (PriorityQueue<String>) SerializationTester
- .readObject(srcIntegerQueue, SERIALIZATION_FILE_NAME);
-
- // will not incur class cast exception.
- Object o = destStringQueue.peek();
- Arrays.sort(array);
- Integer I = (Integer) o;
- assertEquals(array[0], I);
- }
-
- private static class MockComparator<E> implements Comparator<E> {
-
- public int compare(E object1, E object2) {
- int hashcode1 = object1.hashCode();
- int hashcode2 = object2.hashCode();
- if (hashcode1 > hashcode2) {
- return 1;
- } else if (hashcode1 == hashcode2) {
- return 0;
- } else {
- return -1;
- }
- }
- }
-
- private static class MockComparatorStringByLength implements
- Comparator<String> {
-
- public int compare(String object1, String object2) {
- int length1 = object1.length();
- int length2 = object2.length();
- if (length1 > length2) {
- return 1;
- } else if (length1 == length2) {
- return 0;
- } else {
- return -1;
- }
- }
-
- }
-
- private static class MockComparatorCast<E> implements Comparator<E> {
-
- public int compare(E object1, E object2) {
- return 0;
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/PropertiesTest.java b/luni/src/test/java/tests/api/java/util/PropertiesTest.java
deleted file mode 100644
index 61d7c35..0000000
--- a/luni/src/test/java/tests/api/java/util/PropertiesTest.java
+++ /dev/null
@@ -1,629 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PrintStream;
-import java.io.PrintWriter;
-import java.util.Enumeration;
-import java.util.InvalidPropertiesFormatException;
-import java.util.Properties;
-
-import tests.support.resource.Support_Resources;
-
-@TestTargetClass(Properties.class)
-public class PropertiesTest extends junit.framework.TestCase {
-
- Properties tProps;
-
- byte[] propsFile;
-
- /**
- * @tests java.util.Properties#Properties()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Properties",
- args = {}
- )
- public void test_Constructor() {
- Properties p = new Properties();
- // do something to avoid getting a variable unused warning
- p.clear();
- }
-
- /**
- * @tests java.util.Properties#Properties(java.util.Properties)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Properties",
- args = {java.util.Properties.class}
- )
- public void test_ConstructorLjava_util_Properties() {
- if (System.getProperty("java.vendor") != null) {
- Properties p = new Properties(System.getProperties());
- assertNotNull("failed to construct correct properties", p
- .getProperty("java.vendor"));
- }
- }
-
- /**
- * @tests java.util.Properties#getProperty(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies positive case.",
- method = "getProperty",
- args = {java.lang.String.class}
- )
- public void test_getPropertyLjava_lang_String() {
- assertEquals("Did not retrieve property", "this is a test property",
- tProps.getProperty("test.prop"));
- }
-
- /**
- * @tests java.util.Properties#getProperty(java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getProperty",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_getPropertyLjava_lang_StringLjava_lang_String() {
- assertEquals("Did not retrieve property", "this is a test property",
- tProps.getProperty("test.prop", "Blarg"));
- assertEquals("Did not return default value", "Gabba", tProps
- .getProperty("notInThere.prop", "Gabba"));
- assertNull(tProps.getProperty("", null));
- }
-
- /**
- * @tests java.util.Properties#getProperty(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test.",
- method = "getProperty",
- args = {java.lang.String.class}
- )
- public void test_getPropertyLjava_lang_String2() {
- // regression test for HARMONY-3518
- MyProperties props = new MyProperties();
- assertNull(props.getProperty("key"));
- }
-
- /**
- * @tests java.util.Properties#getProperty(java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test.",
- method = "getProperty",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_getPropertyLjava_lang_StringLjava_lang_String2() {
- // regression test for HARMONY-3518
- MyProperties props = new MyProperties();
- assertEquals(props.getProperty("key", "defaultValue"), "defaultValue");
- }
-
- // regression testing for HARMONY-3518
- static class MyProperties extends Properties {
- public synchronized Object get(Object key) {
- return getProperty((String) key); // assume String
- }
- }
-
- /**
- * @tests java.util.Properties#list(java.io.PrintStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "list",
- args = {java.io.PrintStream.class}
- )
- public void test_listLjava_io_PrintStream() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(baos);
- Properties myProps = new Properties();
- String propList;
- myProps.setProperty("Abba", "Cadabra");
- myProps.setProperty("Open", "Sesame");
- myProps.list(ps);
- ps.flush();
- propList = baos.toString();
- assertTrue("Property list innacurate", (propList
- .indexOf("Abba=Cadabra") >= 0)
- && (propList.indexOf("Open=Sesame") >= 0));
- }
-
- /**
- * @tests java.util.Properties#list(java.io.PrintWriter)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "list",
- args = {java.io.PrintWriter.class}
- )
- public void test_listLjava_io_PrintWriter() {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintWriter pw = new PrintWriter(baos);
- Properties myProps = new Properties();
- String propList;
- myProps.setProperty("Abba", "Cadabra");
- myProps.setProperty("Open", "Sesame");
- myProps.list(pw);
- pw.flush();
- propList = baos.toString();
- assertTrue("Property list innacurate", (propList
- .indexOf("Abba=Cadabra") >= 0)
- && (propList.indexOf("Open=Sesame") >= 0));
- }
-
- /**
- * @throws IOException
- * @tests java.util.Properties#load(java.io.InputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "load",
- args = {java.io.InputStream.class}
- )
- public void test_loadLjava_io_InputStream() throws IOException {
- Properties prop = new Properties();
- InputStream is = new ByteArrayInputStream(writeProperties());
- prop.load(is);
- is.close();
-
- assertEquals("Failed to load correct properties", "harmony.tests", prop
- .getProperty("test.pkg"));
- assertNull("Load failed to parse incorrectly", prop
- .getProperty("commented.entry"));
-
- prop = new Properties();
- prop.load(new ByteArrayInputStream("=".getBytes()));
- assertTrue("Failed to add empty key", prop.get("").equals(""));
-
- prop = new Properties();
- prop.load(new ByteArrayInputStream(" = ".getBytes()));
- assertTrue("Failed to add empty key2", prop.get("").equals(""));
-
- prop = new Properties();
- prop.load(new ByteArrayInputStream(" a= b".getBytes()));
- assertEquals("Failed to ignore whitespace", "b", prop.get("a"));
-
- prop = new Properties();
- prop.load(new ByteArrayInputStream(" a b".getBytes()));
- assertEquals("Failed to interpret whitespace as =", "b", prop.get("a"));
-
- prop = new Properties();
- prop.load(new ByteArrayInputStream("#\u008d\u00d2\na=\u008d\u00d3"
- .getBytes("ISO8859_1")));
- assertEquals("Failed to parse chars >= 0x80", "\u008d\u00d3", prop
- .get("a"));
-
- prop = new Properties();
- prop.load(new ByteArrayInputStream(
- "#properties file\r\nfred=1\r\n#last comment"
- .getBytes("ISO8859_1")));
- assertEquals("Failed to load when last line contains a comment", "1",
- prop.get("fred"));
-
- ByteArrayInputStream bais = new ByteArrayInputStream(new byte[]{'\\', 'u', 'x', 'x', 'x', 'x'});
- try {
- prop.load(bais);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Properties#load(java.io.InputStream)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify IOException, IllegalArgumentException.",
- method = "load",
- args = {java.io.InputStream.class}
- )
- public void test_loadLjava_io_InputStream_subtest0() throws IOException {
- InputStream is = Support_Resources
- .getStream("hyts_PropertiesTest.properties");
- Properties props = new Properties();
- props.load(is);
- is.close();
- assertEquals("1", "\n \t \f", props.getProperty(" \r"));
- assertEquals("2", "a", props.getProperty("a"));
- assertEquals("3", "bb as,dn ", props.getProperty("b"));
- assertEquals("4", ":: cu", props.getProperty("c\r \t\nu"));
- assertEquals("5", "bu", props.getProperty("bu"));
- assertEquals("6", "d\r\ne=e", props.getProperty("d"));
- assertEquals("7", "fff", props.getProperty("f"));
- assertEquals("8", "g", props.getProperty("g"));
- assertEquals("9", "", props.getProperty("h h"));
- assertEquals("10", "i=i", props.getProperty(" "));
- assertEquals("11", " j", props.getProperty("j"));
- assertEquals("12", " c", props.getProperty("space"));
- assertEquals("13", "\\", props.getProperty("dblbackslash"));
- }
-
- /**
- * @throws IOException
- * @tests java.util.Properties#save(java.io.OutputStream, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "save",
- args = {java.io.OutputStream.class, java.lang.String.class}
- )
- public void test_saveLjava_io_OutputStreamLjava_lang_String()
- throws IOException {
- Properties myProps = new Properties();
- myProps.setProperty("Property A", "aye");
- myProps.setProperty("Property B", "bee");
- myProps.setProperty("Property C", "see");
-
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- myProps.save(out, "A Header");
- out.close();
-
- Properties myProps2 = new Properties();
- ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
- myProps2.load(in);
- in.close();
-
- Enumeration e = myProps.propertyNames();
- while (e.hasMoreElements()) {
- String nextKey = (String) e.nextElement();
- assertTrue("Stored property list not equal to original", myProps2
- .getProperty(nextKey).equals(myProps.getProperty(nextKey)));
- }
- }
-
- /**
- * @tests java.util.Properties#setProperty(java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setProperty",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_setPropertyLjava_lang_StringLjava_lang_String() {
- Properties myProps = new Properties();
- myProps.setProperty("Yoink", "Yabba");
- assertEquals("Failed to set property", "Yabba", myProps
- .getProperty("Yoink"));
- myProps.setProperty("Yoink", "Gab");
- assertEquals("Failed to reset property", "Gab", myProps
- .getProperty("Yoink"));
- }
-
- /**
- * @throws IOException
- * @tests java.util.Properties#store(java.io.OutputStream, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "store",
- args = {java.io.OutputStream.class, java.lang.String.class}
- )
- public void test_storeLjava_io_OutputStreamLjava_lang_String()
- throws IOException {
- Properties myProps = new Properties();
- myProps.put("Property A", " aye\\\f\t\n\r\b");
- myProps.put("Property B", "b ee#!=:");
- myProps.put("Property C", "see");
-
- Properties myProps2 = new Properties();
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- myProps.store(out, "A Header");
- myProps.store(out, null);
- out.close();
-
- ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
- myProps2.load(in);
- in.close();
-
- Enumeration e = myProps.propertyNames();
- while (e.hasMoreElements()) {
- String nextKey = (String) e.nextElement();
- assertTrue("Stored property list not equal to original", myProps2
- .getProperty(nextKey).equals(myProps.getProperty(nextKey)));
- }
-
- try {
- myProps.store(null, "String");
- fail("NullPointerException expected");
- } catch (NullPointerException ee){
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Properties#loadFromXML(java.io.InputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "loadFromXML",
- args = {java.io.InputStream.class}
- )
- @KnownFailure("ToT fixed?")
- public void test_loadFromXMLLjava_io_InputStream() throws IOException {
- Properties myProps = new Properties();
- myProps.put("Property A", " aye\\\f\t\n\r\b");
- myProps.put("Property B", "b ee#!=:");
- myProps.put("Property C", "see");
-
- Properties myProps2 = new Properties();
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- myProps.storeToXML(out, "A Header");
- out.close();
-
- ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
- try {
- myProps2.loadFromXML(in);
- fail("InvalidPropertiesFormatException expected");
- } catch (InvalidPropertiesFormatException e) {
- //expected
- }
- in.close();
-
-
- Properties prop = new Properties();
- InputStream is = new ByteArrayInputStream(writePropertiesXML("UTF-8"));
- prop.loadFromXML(is);
- is.close();
-
- assertEquals("Failed to load correct properties", "value3", prop
- .getProperty("key3"));
- assertEquals("Failed to load correct properties", "value1", prop
- .getProperty("key1"));
-
- prop = new Properties();
- is = new ByteArrayInputStream(writePropertiesXML("ISO-8859-1"));
- prop.loadFromXML(is);
- is.close();
-
- assertEquals("Failed to load correct properties", "value2", prop
- .getProperty("key2"));
- assertEquals("Failed to load correct properties", "value1", prop
- .getProperty("key1"));
-
- try {
- prop.loadFromXML(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Properties#storeToXML(java.io.OutputStream,
- * java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "storeToXML",
- args = {java.io.OutputStream.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_storeToXMLLjava_io_OutputStreamLjava_lang_StringLjava_lang_String()
- throws IOException {
- Properties myProps = new Properties();
- myProps.setProperty("key1", "value1");
- myProps.setProperty("key2", "value2");
- myProps.setProperty("key3", "value3");
- myProps.setProperty("<a>key4</a>", "\"value4");
- myProps.setProperty("key5 ", "<h>value5</h>");
- myProps.setProperty("<a>key6</a>", " <h>value6</h> ");
- myProps.setProperty("<comment>key7</comment>", "value7");
- myProps.setProperty(" key8 ", "<comment>value8</comment>");
- myProps.setProperty("&lt;key9&gt;", "\u0027value9");
- myProps.setProperty("key10\"", "&lt;value10&gt;");
- myProps.setProperty("&amp;key11&amp;", "value11");
- myProps.setProperty("key12", "&amp;value12&amp;");
- myProps.setProperty("<a>&amp;key13&lt;</a>",
- "&amp;&value13<b>&amp;</b>");
-
- // store in UTF-8 encoding
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- myProps.storeToXML(out, "comment");
- out.close();
-
- ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
- Properties myProps2 = new Properties();
- myProps2.loadFromXML(in);
- in.close();
-
- Enumeration e = myProps.propertyNames();
- while (e.hasMoreElements()) {
- String nextKey = (String) e.nextElement();
- assertTrue("Stored property list not equal to original", myProps2
- .getProperty(nextKey).equals(myProps.getProperty(nextKey)));
- }
-
- // store in ISO-8859-1 encoding
- out = new ByteArrayOutputStream();
- myProps.storeToXML(out, "comment", "ISO-8859-1");
- out.close();
-
- in = new ByteArrayInputStream(out.toByteArray());
- myProps2 = new Properties();
- myProps2.loadFromXML(in);
- in.close();
-
- e = myProps.propertyNames();
- while (e.hasMoreElements()) {
- String nextKey = (String) e.nextElement();
- assertTrue("Stored property list not equal to original", myProps2
- .getProperty(nextKey).equals(myProps.getProperty(nextKey)));
- }
-
- out = new ByteArrayOutputStream();
- myProps.storeToXML(out, "comment", "ISO-8859-1");
- myProps.storeToXML(out, null, "ISO-8859-1");
- out.close();
-
- try {
- myProps.storeToXML(out, "comment", null);
- fail("NulPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- try {
- myProps.storeToXML(null, "comment", "ISO-8859-1");
- fail("NulPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "storeToXML",
- args = {java.io.OutputStream.class, java.lang.String.class}
- )
- public void test_storeToXMLLjava_io_OutputStreamLjava_lang_String()
- throws IOException {
- Properties myProps = new Properties();
- myProps.put("Property A", "value 1");
- myProps.put("Property B", "value 2");
- myProps.put("Property C", "value 3");
-
- Properties myProps2 = new Properties();
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- myProps.storeToXML(out, "A Header");
- out.close();
-
- ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
- myProps2.loadFromXML(in);
- in.close();
-
- Enumeration e = myProps.propertyNames();
- while (e.hasMoreElements()) {
- String nextKey = (String) e.nextElement();
- assertTrue("Stored property list not equal to original", myProps2
- .getProperty(nextKey).equals(myProps.getProperty(nextKey)));
- }
-
- try {
- myProps.storeToXML(null, "String");
- fail("NullPointerException expected");
- } catch (NullPointerException ee){
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "propertyNames",
- args = {}
- )
- public void test_propertyNames() {
- Properties myProps = new Properties();
- myProps.put("Property A", "value 1");
- myProps.put("Property B", "value 2");
- myProps.put("Property C", "value 3");
-
- Enumeration e = myProps.propertyNames();
-
- int count = 0;
- while (e.hasMoreElements()) {
- count++;
- assertTrue(myProps.containsKey(e.nextElement()));
- }
-
- assertTrue(myProps.size() == count);
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() throws Exception {
- super.setUp();
- tProps = new Properties();
- tProps.put("test.prop", "this is a test property");
- tProps.put("bogus.prop", "bogus");
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() throws Exception {
- tProps = null;
- super.tearDown();
- }
-
- protected byte[] writeProperties() throws IOException {
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(bout);
- ps.println("#commented.entry=Bogus");
- ps.println("test.pkg=harmony.tests");
- ps.println("test.proj=Automated Tests");
- ps.close();
- return bout.toByteArray();
- }
-
- protected byte[] writePropertiesXML(String encoding) throws IOException {
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
- PrintStream ps = new PrintStream(bout, true, encoding);
- ps.println("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>");
- ps
- .println("<!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\">");
- ps.println("<properties>");
- ps.println("<comment>comment</comment>");
- ps.println("<entry key=\"key4\">value4</entry>");
- ps.println("<entry key=\"key3\">value3</entry>");
- ps.println("<entry key=\"key2\">value2</entry>");
- ps.println("<entry key=\"key1\"><!-- xml comment -->value1</entry>");
- ps.println("</properties>");
- ps.close();
- return bout.toByteArray();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/PropertyPermissionTest.java b/luni/src/test/java/tests/api/java/util/PropertyPermissionTest.java
deleted file mode 100644
index 46cdb17..0000000
--- a/luni/src/test/java/tests/api/java/util/PropertyPermissionTest.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.Serializable;
-import java.util.Enumeration;
-import java.util.PropertyPermission;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-
-@TestTargetClass(PropertyPermission.class)
-public class PropertyPermissionTest extends junit.framework.TestCase {
-
- static PropertyPermission javaPP = new PropertyPermission("java.*", "read");
-
- static PropertyPermission userPP = new PropertyPermission("user.name",
- "read,write");
-
- /**
- * @tests java.util.PropertyPermission#PropertyPermission(java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PropertyPermission",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_String() {
- // Test for method java.util.PropertyPermission(java.lang.String,
- // java.lang.String)
- assertTrue("Used to test", true);
- }
-
- /**
- * @tests java.util.PropertyPermission#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean
- // java.util.PropertyPermission.equals(java.lang.Object)
- PropertyPermission equalToJavaPP = new PropertyPermission("java.*",
- "read");
- PropertyPermission notEqualToJavaPP = new PropertyPermission("java.*",
- "read, write");
- PropertyPermission alsoNotEqualToJavaPP = new PropertyPermission(
- "java.home", "read");
-
- assertTrue("Equal returned false for equal objects", javaPP
- .equals(equalToJavaPP));
- assertTrue("Equal returned true for objects with different names",
- !javaPP.equals(notEqualToJavaPP));
- assertTrue(
- "Equal returned true for objects with different permissions",
- !javaPP.equals(alsoNotEqualToJavaPP));
- }
-
- /**
- * @tests java.util.PropertyPermission#getActions()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getActions",
- args = {}
- )
- public void test_getActions() {
- // Test for method java.lang.String
- // java.util.PropertyPermission.getActions()
- assertEquals("getActions did not return proper action", "read", javaPP
- .getActions());
- assertEquals("getActions did not return proper canonical representation of actions",
- "read,write", userPP.getActions());
- }
-
- /**
- * @tests java.util.PropertyPermission#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- // Test for method int java.util.PropertyPermission.hashCode()
- assertTrue("javaPP returned wrong hashCode",
- javaPP.hashCode() == javaPP.getName().hashCode());
- assertTrue("userPP returned wrong hashCode",
- userPP.hashCode() == userPP.getName().hashCode());
- }
-
- /**
- * @tests java.util.PropertyPermission#implies(java.security.Permission)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "implies",
- args = {java.security.Permission.class}
- )
- public void test_impliesLjava_security_Permission() {
- // Test for method boolean
- // java.util.PropertyPermission.implies(java.security.Permission)
- PropertyPermission impliedByJavaPP = new PropertyPermission(
- "java.home", "read");
- PropertyPermission notImpliedByJavaPP = new PropertyPermission(
- "java.home", "read,write");
- PropertyPermission impliedByUserPP = new PropertyPermission(
- "user.name", "read,write");
- PropertyPermission alsoImpliedByUserPP = new PropertyPermission(
- "user.name", "write");
- assertTrue("Returned false for implied permission (subset of .*)",
- javaPP.implies(impliedByJavaPP));
- assertTrue("Returned true for unimplied permission", !javaPP
- .implies(notImpliedByJavaPP));
- assertTrue("Returned false for implied permission (equal)", userPP
- .implies(impliedByUserPP));
- assertTrue("Returned false for implied permission (subset of actions)",
- userPP.implies(alsoImpliedByUserPP));
- }
-
- /**
- * @tests java.util.PropertyPermission#newPermissionCollection()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "newPermissionCollection",
- args = {}
- )
- public void test_newPermissionCollection() {
- // Test for method java.security.PermissionCollection
- // java.util.PropertyPermission.newPermissionCollection()
- java.security.PermissionCollection pc = javaPP
- .newPermissionCollection();
- pc.add(javaPP);
- Enumeration elementEnum = pc.elements();
- assertTrue("Invalid PermissionCollection returned", elementEnum
- .nextElement().equals(javaPP));
- }
-
- /**
- * @tests java.util.PropertyPermission#readObject(ObjectInputStream)
- * @tests java.util.PropertyPermission#writeObject(ObjectOutputStream)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization.",
- method = "!SerializationSelf",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization.",
- method = "!SerializationGolden",
- args = {}
- )
- })
- public void test_serialization() throws Exception{
- PropertyPermission pp = new PropertyPermission("test", "read");
- SerializationTest.verifySelf(pp, comparator);
- SerializationTest.verifyGolden(this, pp, comparator);
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-
- private static final SerializableAssert comparator = new SerializableAssert() {
-
- public void assertDeserialized(Serializable initial, Serializable deserialized) {
- PropertyPermission initialPP = (PropertyPermission) initial;
- PropertyPermission deseriaPP = (PropertyPermission) deserialized;
- assertEquals("should be equal", initialPP, deseriaPP);
- }
-
- };
-}
diff --git a/luni/src/test/java/tests/api/java/util/PropertyResourceBundleTest.java b/luni/src/test/java/tests/api/java/util/PropertyResourceBundleTest.java
deleted file mode 100644
index 85df3dd..0000000
--- a/luni/src/test/java/tests/api/java/util/PropertyResourceBundleTest.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.Enumeration;
-import java.util.MissingResourceException;
-import java.util.PropertyResourceBundle;
-import java.util.Vector;
-
-@TestTargetClass(PropertyResourceBundle.class)
-public class PropertyResourceBundleTest extends junit.framework.TestCase {
-
- static PropertyResourceBundle prb;
-
- /**
- * @tests java.util.PropertyResourceBundle#PropertyResourceBundle(java.io.InputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PropertyResourceBundle",
- args = {java.io.InputStream.class}
- )
- public void test_ConstructorLjava_io_InputStream() {
- // Test for method java.util.PropertyResourceBundle(java.io.InputStream)
- assertTrue("Used to test", true);
- }
-
- /**
- * @tests java.util.PropertyResourceBundle#getKeys()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getKeys",
- args = {}
- )
- public void test_getKeys() {
- Enumeration keyEnum = prb.getKeys();
- Vector test = new Vector();
- int keyCount = 0;
- while (keyEnum.hasMoreElements()) {
- test.addElement(keyEnum.nextElement());
- keyCount++;
- }
-
- assertEquals("Returned the wrong number of keys", 2, keyCount);
- assertTrue("Returned the wrong keys", test.contains("p1")
- && test.contains("p2"));
- }
-
- /**
- * @tests java.util.PropertyResourceBundle#handleGetObject(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "handleGetObject",
- args = {java.lang.String.class}
- )
- public void test_handleGetObjectLjava_lang_String() {
- // Test for method java.lang.Object
- // java.util.PropertyResourceBundle.handleGetObject(java.lang.String)
- try {
- assertTrue("Returned incorrect objects", prb.getObject("p1")
- .equals("one")
- && prb.getObject("p2").equals("two"));
- } catch (MissingResourceException e) {
- fail(
- "Threw MisingResourceException for a key contained in the bundle");
- }
- try {
- prb.getObject("Not in the bundle");
- } catch (MissingResourceException e) {
- return;
- }
- fail(
- "Failed to throw MissingResourceException for object not in the bundle");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- java.io.InputStream propertiesStream = new java.io.ByteArrayInputStream(
- "p1=one\np2=two".getBytes());
- try {
- prb = new PropertyResourceBundle(propertiesStream);
- } catch (java.io.IOException e) {
- fail(
- "Contruction of PropertyResourceBundle threw IOException");
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/RandomTest.java b/luni/src/test/java/tests/api/java/util/RandomTest.java
deleted file mode 100644
index 4e92eff..0000000
--- a/luni/src/test/java/tests/api/java/util/RandomTest.java
+++ /dev/null
@@ -1,376 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.Random;
-
-@TestTargetClass(Random.class)
-public class RandomTest extends junit.framework.TestCase {
-
- Random r;
-
- /**
- * @tests java.util.Random#Random()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Random",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.Random()
- assertTrue("Used to test", true);
- }
-
- /**
- * @tests java.util.Random#Random(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Random",
- args = {long.class}
- )
- public void test_ConstructorJ() {
- Random r = new Random(8409238L);
- Random r2 = new Random(8409238L);
- for (int i = 0; i < 100; i++)
- assertTrue("Values from randoms with same seed don't match", r
- .nextInt() == r2.nextInt());
- }
-
- /**
- * @tests java.util.Random#nextBoolean()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextBoolean",
- args = {}
- )
- public void test_nextBoolean() {
- // Test for method boolean java.util.Random.nextBoolean()
- boolean falseAppeared = false, trueAppeared = false;
- for (int counter = 0; counter < 100; counter++)
- if (r.nextBoolean())
- trueAppeared = true;
- else
- falseAppeared = true;
- assertTrue("Calling nextBoolean() 100 times resulted in all trues",
- falseAppeared);
- assertTrue("Calling nextBoolean() 100 times resulted in all falses",
- trueAppeared);
- }
-
- /**
- * @tests java.util.Random#nextBytes(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextBytes",
- args = {byte[].class}
- )
- public void test_nextBytes$B() {
- // Test for method void java.util.Random.nextBytes(byte [])
- boolean someDifferent = false;
- byte[] randomBytes = new byte[100];
- r.nextBytes(randomBytes);
- byte firstByte = randomBytes[0];
- for (int counter = 1; counter < randomBytes.length; counter++)
- if (randomBytes[counter] != firstByte)
- someDifferent = true;
- assertTrue(
- "nextBytes() returned an array of length 100 of the same byte",
- someDifferent);
- }
-
- /**
- * @tests java.util.Random#nextDouble()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextDouble",
- args = {}
- )
- public void test_nextDouble() {
- // Test for method double java.util.Random.nextDouble()
- double lastNum = r.nextDouble();
- double nextNum;
- boolean someDifferent = false;
- boolean inRange = true;
- for (int counter = 0; counter < 100; counter++) {
- nextNum = r.nextDouble();
- if (nextNum != lastNum)
- someDifferent = true;
- if (!(0 <= nextNum && nextNum < 1.0))
- inRange = false;
- lastNum = nextNum;
- }
- assertTrue("Calling nextDouble 100 times resulted in same number",
- someDifferent);
- assertTrue(
- "Calling nextDouble resulted in a number out of range [0,1)",
- inRange);
- }
-
- /**
- * @tests java.util.Random#nextFloat()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextFloat",
- args = {}
- )
- public void test_nextFloat() {
- // Test for method float java.util.Random.nextFloat()
- float lastNum = r.nextFloat();
- float nextNum;
- boolean someDifferent = false;
- boolean inRange = true;
- for (int counter = 0; counter < 100; counter++) {
- nextNum = r.nextFloat();
- if (nextNum != lastNum)
- someDifferent = true;
- if (!(0 <= nextNum && nextNum < 1.0))
- inRange = false;
- lastNum = nextNum;
- }
- assertTrue("Calling nextFloat 100 times resulted in same number",
- someDifferent);
- assertTrue("Calling nextFloat resulted in a number out of range [0,1)",
- inRange);
- }
-
- /**
- * @tests java.util.Random#nextGaussian()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextGaussian",
- args = {}
- )
- public void test_nextGaussian() {
- // Test for method double java.util.Random.nextGaussian()
- double lastNum = r.nextGaussian();
- double nextNum;
- boolean someDifferent = false;
- boolean someInsideStd = false;
- for (int counter = 0; counter < 100; counter++) {
- nextNum = r.nextGaussian();
- if (nextNum != lastNum)
- someDifferent = true;
- if (-1.0 <= nextNum && nextNum <= 1.0)
- someInsideStd = true;
- lastNum = nextNum;
- }
- assertTrue("Calling nextGaussian 100 times resulted in same number",
- someDifferent);
- assertTrue(
- "Calling nextGaussian 100 times resulted in no number within 1 std. deviation of mean",
- someInsideStd);
- }
-
- /**
- * @tests java.util.Random#nextInt()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextInt",
- args = {}
- )
- public void test_nextInt() {
- // Test for method int java.util.Random.nextInt()
- int lastNum = r.nextInt();
- int nextNum;
- boolean someDifferent = false;
- for (int counter = 0; counter < 100; counter++) {
- nextNum = r.nextInt();
- if (nextNum != lastNum)
- someDifferent = true;
- lastNum = nextNum;
- }
- assertTrue("Calling nextInt 100 times resulted in same number",
- someDifferent);
- }
-
- /**
- * @tests java.util.Random#nextInt(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextInt",
- args = {int.class}
- )
- public void test_nextIntI() {
- // Test for method int java.util.Random.nextInt(int)
- final int range = 10;
- int lastNum = r.nextInt(range);
- int nextNum;
- boolean someDifferent = false;
- boolean inRange = true;
- for (int counter = 0; counter < 100; counter++) {
- nextNum = r.nextInt(range);
- if (nextNum != lastNum)
- someDifferent = true;
- if (!(0 <= nextNum && nextNum < range))
- inRange = false;
- lastNum = nextNum;
- }
- assertTrue("Calling nextInt (range) 100 times resulted in same number",
- someDifferent);
- assertTrue(
- "Calling nextInt (range) resulted in a number outside of [0, range)",
- inRange);
-
- }
-
- /**
- * @tests java.util.Random#nextLong()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextLong",
- args = {}
- )
- public void test_nextLong() {
- // Test for method long java.util.Random.nextLong()
- long lastNum = r.nextLong();
- long nextNum;
- boolean someDifferent = false;
- for (int counter = 0; counter < 100; counter++) {
- nextNum = r.nextLong();
- if (nextNum != lastNum)
- someDifferent = true;
- lastNum = nextNum;
- }
- assertTrue("Calling nextLong 100 times resulted in same number",
- someDifferent);
- }
-
- /**
- * @tests java.util.Random#setSeed(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setSeed",
- args = {long.class}
- )
- public void test_setSeedJ() {
- // Test for method void java.util.Random.setSeed(long)
- long[] randomArray = new long[100];
- boolean someDifferent = false;
- final long firstSeed = 1000;
- long aLong, anotherLong, yetAnotherLong;
- Random aRandom = new Random();
- Random anotherRandom = new Random();
- Random yetAnotherRandom = new Random();
- aRandom.setSeed(firstSeed);
- anotherRandom.setSeed(firstSeed);
- for (int counter = 0; counter < randomArray.length; counter++) {
- aLong = aRandom.nextLong();
- anotherLong = anotherRandom.nextLong();
- assertTrue(
- "Two randoms with same seeds gave differing nextLong values",
- aLong == anotherLong);
- yetAnotherLong = yetAnotherRandom.nextLong();
- randomArray[counter] = aLong;
- if (aLong != yetAnotherLong)
- someDifferent = true;
- }
- assertTrue(
- "Two randoms with the different seeds gave the same chain of values",
- someDifferent);
- aRandom.setSeed(firstSeed);
- for (int counter = 0; counter < randomArray.length; counter++)
- assertTrue(
- "Reseting a random to its old seed did not result in the same chain of values as it gave before",
- aRandom.nextLong() == randomArray[counter]);
- }
-
- class Mock_Random extends Random {
- boolean nextCalled = false;
-
- public boolean getFlag () {
- boolean retVal = nextCalled;
- nextCalled = false;
- return retVal;
- }
-
- @Override
- protected int next(int bits) {
- nextCalled = true;
- return super.next(bits);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "next",
- args = {int.class}
- )
- public void test_next() {
- Mock_Random mr = new Mock_Random();
- assertFalse(mr.getFlag());
- mr.nextBoolean();
- assertTrue(mr.getFlag());
- mr.nextBytes(new byte[10]);
- assertTrue(mr.getFlag());
- mr.nextDouble();
- assertTrue(mr.getFlag());
- mr.nextFloat();
- assertTrue(mr.getFlag());
- mr.nextGaussian();
- assertTrue(mr.getFlag());
- mr.nextInt();
- assertTrue(mr.getFlag());
- mr.nextInt(10);
- assertTrue(mr.getFlag());
- mr.nextLong();
- assertTrue(mr.getFlag());
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- r = new Random();
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/ResourceBundleTest.java b/luni/src/test/java/tests/api/java/util/ResourceBundleTest.java
deleted file mode 100644
index 8fecc7e..0000000
--- a/luni/src/test/java/tests/api/java/util/ResourceBundleTest.java
+++ /dev/null
@@ -1,492 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.io.File;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.security.Permission;
-import java.util.Enumeration;
-import java.util.Locale;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-import java.util.StringTokenizer;
-import java.util.Vector;
-
-import tests.api.java.util.support.B;
-import tests.support.resource.Support_Resources;
-
-@TestTargetClass(ResourceBundle.class)
-public class ResourceBundleTest extends junit.framework.TestCase {
- SecurityManager sm = new SecurityManager() {
-
- @Override
- public void checkPermission(Permission perm) {
- }
- };
-
- /**
- * @tests java.util.ResourceBundle#getBundle(java.lang.String,
- * java.util.Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBundle",
- args = {java.lang.String.class, java.util.Locale.class}
- )
- public void test_getBundleLjava_lang_StringLjava_util_Locale() {
- ResourceBundle bundle;
- String name = "tests.support.Support_TestResource";
- Locale defLocale = Locale.getDefault();
-
- Locale.setDefault(new Locale("en", "US"));
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
- assertEquals("Wrong bundle fr_FR_VAR", "frFRVARValue4", bundle.getString("parent4")
- );
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "v1"));
- assertEquals("Wrong bundle fr_FR_v1",
- "frFRValue4", bundle.getString("parent4"));
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "US", "VAR"));
- assertEquals("Wrong bundle fr_US_var", "frValue4", bundle.getString("parent4")
- );
- bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "VAR"));
- assertEquals("Wrong bundle de_FR_var", "enUSValue4", bundle.getString("parent4")
- );
-
- Locale.setDefault(new Locale("fr", "FR", "VAR"));
- bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "v1"));
- assertEquals("Wrong bundle de_FR_var 2", "frFRVARValue4", bundle.getString("parent4")
- );
-
- Locale.setDefault(new Locale("de", "US"));
- bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "var"));
- assertEquals("Wrong bundle de_FR_var 2", "parentValue4", bundle.getString("parent4")
- );
-
- // Test with a security manager
- Locale.setDefault(new Locale("en", "US"));
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR",
- "VAR"));
- assertEquals("Security: Wrong bundle fr_FR_VAR", "frFRVARValue4", bundle.getString(
- "parent4"));
- bundle = ResourceBundle.getBundle(name,
- new Locale("fr", "FR", "v1"));
- assertEquals("Security: Wrong bundle fr_FR_v1", "frFRValue4", bundle.getString(
- "parent4"));
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "US",
- "VAR"));
- assertEquals("Security: Wrong bundle fr_US_var", "frValue4", bundle.getString(
- "parent4"));
- bundle = ResourceBundle.getBundle(name, new Locale("de", "FR",
- "VAR"));
- assertTrue("Security: Wrong bundle de_FR_var: "
- + bundle.getString("parent4"), bundle.getString("parent4")
- .equals("enUSValue4"));
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- try {
- ResourceBundle.getBundle(null, Locale.getDefault());
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- try {
- ResourceBundle.getBundle("", new Locale("xx", "yy"));
- fail("MissingResourceException expected");
- } catch (MissingResourceException ee) {
- //expected
- }
-
- Locale.setDefault(defLocale);
- }
-
- /**
- * @tests java.util.ResourceBundle#getBundle(java.lang.String,
- * java.util.Locale, java.lang.ClassLoader)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBundle",
- args = {java.lang.String.class, java.util.Locale.class, java.lang.ClassLoader.class}
- )
- public void test_getBundleLjava_lang_StringLjava_util_LocaleLjava_lang_ClassLoader() {
- String classPath = System.getProperty("java.class.path");
- StringTokenizer tok = new StringTokenizer(classPath, File.pathSeparator);
- Vector<URL> urlVec = new Vector<URL>();
- String resPackage = Support_Resources.RESOURCE_PACKAGE;
- try {
- while (tok.hasMoreTokens()) {
- String path = tok.nextToken();
- String url;
- if (new File(path).isDirectory())
- url = "file:" + path + resPackage + "subfolder/";
- else
- url = "jar:file:" + path + "!" + resPackage + "subfolder/";
- urlVec.addElement(new URL(url));
- }
- } catch (MalformedURLException e) {
- }
- URL[] urls = new URL[urlVec.size()];
- for (int i = 0; i < urlVec.size(); i++)
- urls[i] = urlVec.elementAt(i);
- URLClassLoader loader = new URLClassLoader(urls, null);
-
- String name = Support_Resources.RESOURCE_PACKAGE_NAME
- + ".hyts_resource";
- ResourceBundle bundle = ResourceBundle.getBundle(name, Locale
- .getDefault());
- assertEquals("Wrong value read", "parent", bundle.getString("property"));
- bundle = ResourceBundle.getBundle(name, Locale.getDefault(), loader);
- assertEquals("Wrong cached value",
- "resource", bundle.getString("property"));
-
- try {
- ResourceBundle.getBundle(null, Locale.getDefault(), loader);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- try {
- ResourceBundle.getBundle(name, null, loader);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- try {
- ResourceBundle.getBundle(name, Locale.getDefault(), null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- try {
- ResourceBundle.getBundle("", Locale.getDefault(), loader);
- fail("MissingResourceException expected");
- } catch (MissingResourceException ee) {
- //expected
- }
-
- // Regression test for Harmony-3823
- B bb = new B();
- String s = bb.find("nonexistent");
- s = bb.find("name");
- assertEquals("Wrong property got", "Name", s);
- }
-
- /**
- * @tests java.util.ResourceBundle#getString(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getString",
- args = {java.lang.String.class}
- )
- public void test_getStringLjava_lang_String() {
- ResourceBundle bundle;
- String name = "tests.support.Support_TestResource";
- Locale.setDefault(new Locale("en", "US"));
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
- assertEquals("Wrong value parent4",
- "frFRVARValue4", bundle.getString("parent4"));
- assertEquals("Wrong value parent3",
- "frFRValue3", bundle.getString("parent3"));
- assertEquals("Wrong value parent2",
- "frValue2", bundle.getString("parent2"));
- assertEquals("Wrong value parent1",
- "parentValue1", bundle.getString("parent1"));
- assertEquals("Wrong value child3",
- "frFRVARChildValue3", bundle.getString("child3"));
- assertEquals("Wrong value child2",
- "frFRVARChildValue2", bundle.getString("child2"));
- assertEquals("Wrong value child1",
- "frFRVARChildValue1", bundle.getString("child1"));
-
- try {
- bundle.getString(null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- try {
- bundle.getString("");
- fail("MissingResourceException expected");
- } catch (MissingResourceException ee) {
- //expected
- }
-
- try {
- bundle.getString("IntegerVal");
- fail("ClassCastException expected");
- } catch (ClassCastException ee) {
- //expected
- }
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test. Doesn't verify NullPointerException.",
- method = "getBundle",
- args = {java.lang.String.class}
- )
- public void test_getBundle_getClassName() {
- // Regression test for Harmony-1759
- Locale locale = Locale.GERMAN;
- String nonExistentBundle = "Non-ExistentBundle";
- try {
- ResourceBundle.getBundle(nonExistentBundle, locale, this.getClass()
- .getClassLoader());
- fail("MissingResourceException expected!");
- } catch (MissingResourceException e) {
- assertEquals(nonExistentBundle + "_" + locale, e.getClassName());
- }
-
- try {
- ResourceBundle.getBundle(nonExistentBundle, locale);
- fail("MissingResourceException expected!");
- } catch (MissingResourceException e) {
- assertEquals(nonExistentBundle + "_" + locale, e.getClassName());
- }
-
- locale = Locale.getDefault();
- try {
- ResourceBundle.getBundle(nonExistentBundle);
- fail("MissingResourceException expected!");
- } catch (MissingResourceException e) {
- assertEquals(nonExistentBundle + "_" + locale, e.getClassName());
- }
- }
-
- class Mock_ResourceBundle extends ResourceBundle {
- @Override
- public Enumeration<String> getKeys() {
- return null;
- }
-
- @Override
- protected Object handleGetObject(String key) {
- return null;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ResourceBundle",
- args = {}
- )
- public void test_constructor() {
- assertNotNull(new Mock_ResourceBundle());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocale",
- args = {}
- )
- public void test_getLocale() {
- ResourceBundle bundle;
- String name = "tests.support.Support_TestResource";
- Locale loc = Locale.getDefault();
- Locale.setDefault(new Locale("en", "US"));
-
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
- assertEquals("fr_FR_VAR", bundle.getLocale().toString());
-
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "v1"));
- assertEquals("fr_FR", bundle.getLocale().toString());
-
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "US", "VAR"));
- assertEquals("fr", bundle.getLocale().toString());
-
- bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "VAR"));
- assertEquals("en_US", bundle.getLocale().toString());
-
- bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "v1"));
- assertEquals("en_US", bundle.getLocale().toString());
-
- bundle = ResourceBundle.getBundle(name, new Locale("de", "FR", "var"));
- assertEquals("en_US", bundle.getLocale().toString());
-
- Locale.setDefault(loc);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getObject",
- args = {java.lang.String.class}
- )
- public void test_getObjectLjava_lang_String() {
- ResourceBundle bundle;
- String name = "tests.support.Support_TestResource";
- Locale.setDefault(new Locale("en", "US"));
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
- assertEquals("Wrong value parent4",
- "frFRVARValue4", (String)bundle.getObject("parent4"));
- assertEquals("Wrong value parent3",
- "frFRValue3", (String)bundle.getObject("parent3"));
- assertEquals("Wrong value parent2",
- "frValue2", (String)bundle.getObject("parent2"));
- assertEquals("Wrong value parent1",
- "parentValue1", (String)bundle.getObject("parent1"));
- assertEquals("Wrong value child3",
- "frFRVARChildValue3", (String)bundle.getObject("child3"));
- assertEquals("Wrong value child2",
- "frFRVARChildValue2", (String)bundle.getObject("child2"));
- assertEquals("Wrong value child1",
- "frFRVARChildValue1", (String)bundle.getObject("child1"));
- assertEquals("Wrong value IntegerVal",
- 1, bundle.getObject("IntegerVal"));
-
- try {
- bundle.getObject(null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- try {
- bundle.getObject("");
- fail("MissingResourceException expected");
- } catch (MissingResourceException ee) {
- //expected
- }
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getStringArray",
- args = {java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setParent",
- args = {java.util.ResourceBundle.class}
- )
- })
- public void test_getStringArrayLjava_lang_String() {
- ResourceBundle bundle;
- String name = "tests.support.Support_TestResource";
- Locale.setDefault(new Locale("en", "US"));
- bundle = ResourceBundle.getBundle(name, new Locale("fr", "FR", "VAR"));
-
- String[] array = bundle.getStringArray("StringArray");
- for(int i = 0; i < array.length; i++) {
- assertEquals("Str" + (i + 1), array[i]);
- }
-
- try {
- bundle.getStringArray(null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- try {
- bundle.getStringArray("");
- fail("MissingResourceException expected");
- } catch (MissingResourceException ee) {
- //expected
- }
-
- try {
- bundle.getStringArray("IntegerVal");
- fail("ClassCastException expected");
- } catch (ClassCastException ee) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBundle",
- args = {java.lang.String.class}
- )
- public void test_getBundleLjava_lang_String() {
- ResourceBundle bundle;
- String name = "tests.support.Support_TestResource";
- Locale defLocale = Locale.getDefault();
-
- Locale.setDefault(new Locale("en", "US"));
- bundle = ResourceBundle.getBundle(name);
- assertEquals("enUSValue4", bundle.getString("parent4")
- );
- Locale.setDefault(new Locale("fr", "FR", "v1"));
- bundle = ResourceBundle.getBundle(name);
- assertEquals("Wrong bundle fr_FR_v1",
- "frFRValue4", bundle.getString("parent4"));
- Locale.setDefault(new Locale("fr", "US", "VAR"));
- bundle = ResourceBundle.getBundle(name);
- assertEquals("Wrong bundle fr_US_var", "frValue4", bundle.getString("parent4")
- );
- Locale.setDefault(new Locale("de", "FR", "VAR"));
- bundle = ResourceBundle.getBundle(name);
- assertEquals("Wrong bundle de_FR_var", "parentValue4", bundle.getString("parent4")
- );
- Locale.setDefault(new Locale("de", "FR", "v1"));
- bundle = ResourceBundle.getBundle(name);
- assertEquals("Wrong bundle de_FR_var 2", "parentValue4", bundle.getString("parent4")
- );
- Locale.setDefault(new Locale("de", "FR", "var"));
- bundle = ResourceBundle.getBundle(name);
- assertEquals("Wrong bundle de_FR_var 2", "parentValue4", bundle.getString("parent4")
- );
-
- try {
- ResourceBundle.getBundle(null);
- fail("NullPointerException expected");
- } catch (NullPointerException ee) {
- //expected
- }
-
- try {
- ResourceBundle.getBundle("");
- fail("MissingResourceException expected");
- } catch (MissingResourceException ee) {
- //expected
- }
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/SampleBundleClass.java b/luni/src/test/java/tests/api/java/util/SampleBundleClass.java
deleted file mode 100644
index 25382b7..0000000
--- a/luni/src/test/java/tests/api/java/util/SampleBundleClass.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/* 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 tests.api.java.util;
-
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-/**
- * Part of the ResourceBundleTest
- */
-public class SampleBundleClass {
-
- private static SampleBundleClass singleton;
- private static ResourceBundle bundle;
-
- public SampleBundleClass() {
- super();
- if (singleton != null) {
- throw new RuntimeException();
- }
- singleton = this;
- try {
- bundle = ResourceBundle.getBundle("tests.api.simple.SampleBundleClass");
- } catch (MissingResourceException x) {
- System.out.println("Missing resource");
- bundle = null;
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/ScannerTest.java b/luni/src/test/java/tests/api/java/util/ScannerTest.java
deleted file mode 100644
index fe7a4cf..0000000
--- a/luni/src/test/java/tests/api/java/util/ScannerTest.java
+++ /dev/null
@@ -1,6796 +0,0 @@
-/* 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.KnownFailure;
-
-import java.io.Closeable;
-import java.io.EOFException;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PipedInputStream;
-import java.io.StringReader;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.SocketAddress;
-import java.nio.CharBuffer;
-import java.nio.channels.FileChannel;
-import java.nio.channels.ReadableByteChannel;
-import java.nio.channels.ServerSocketChannel;
-import java.nio.channels.SocketChannel;
-import java.nio.charset.Charset;
-import java.util.Arrays;
-import java.util.InputMismatchException;
-import java.util.Locale;
-import java.util.NoSuchElementException;
-import java.util.Scanner;
-import java.util.regex.MatchResult;
-import java.util.regex.Pattern;
-
-import tests.support.Support_PortManager;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(Scanner.class)
-public class ScannerTest extends TestCase {
- static final boolean disableRIBugs = true;
-
- private Scanner s;
-
- private ServerSocket server;
-
- private SocketAddress address;
-
- private SocketChannel client;
-
- private Socket serverSocket;
-
- private OutputStream os;
-
- private static class MockCloseable implements Closeable, Readable {
-
- public void close() throws IOException {
- throw new IOException();
- }
-
- public int read(CharBuffer cb) throws IOException {
- throw new EOFException();
- }
-
- }
-
- /**
- * @tests java.util.Scanner#Scanner(File)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Scanner",
- args = {java.io.File.class}
- )
- public void test_ConstructorLjava_io_File() throws IOException {
- File tmpFile = File.createTempFile("TestFileForScanner", ".tmp");
- s = new Scanner(tmpFile);
- assertNotNull(s);
- s.close();
- assertTrue(tmpFile.delete());
-
- try {
- s = new Scanner(tmpFile);
- fail("should throw FileNotFoundException");
- } catch (FileNotFoundException e) {
- // expected
- }
-
- tmpFile = File.createTempFile("TestFileForScanner", ".tmp");
- FileOutputStream fos = new FileOutputStream(tmpFile);
- fos.write("test".getBytes());
-
- s = new Scanner(tmpFile);
- tmpFile.delete();
-
- // Scanner(File = null)
- try {
- s = new Scanner((File) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- // TODO: test if the default charset is used.
- }
-
- /**
- * @tests java.util.Scanner#Scanner(File, String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Scanner",
- args = {java.io.File.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_io_FileLjava_lang_String()
- throws IOException {
- File tmpFile = File.createTempFile("TestFileForScanner", ".tmp");
- s = new Scanner(tmpFile, Charset.defaultCharset().name());
- assertNotNull(s);
- s.close();
- assertTrue(tmpFile.delete());
-
- try {
- s = new Scanner(tmpFile, Charset.defaultCharset().name());
- fail("should throw FileNotFoundException");
- } catch (FileNotFoundException e) {
- // expected
- }
-
- try {
- s = new Scanner(tmpFile, null);
- fail("should throw FileNotFoundException");
- } catch (FileNotFoundException e) {
- // expected
- }
-
- tmpFile = File.createTempFile("TestFileForScanner", ".tmp");
- try {
- s = new Scanner(tmpFile, "invalid charset");
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- //fail on RI. File is opened but not closed when exception is thrown on
- // RI.
- assertTrue(tmpFile.delete());
-
- // Scanner(File = null, Charset = null)
- try {
- s = new Scanner((File) null, null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- // Scanner(File = null, Charset = UTF-8)
- try {
- s = new Scanner((File) null, "UTF-8");
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- // Scanner(File = null, Charset = invalid)
- try {
- s = new Scanner((File) null, "invalid");
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- // Scanner(File, Charset = null)
- try {
- File f = File.createTempFile("test", ".tmp");
- s = new Scanner(f, null);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- // TODO: test if the specified charset is used.
- }
-
- /**
- * @tests java.util.Scanner#Scanner(InputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Scanner",
- args = {java.io.InputStream.class}
- )
- public void test_ConstructorLjava_io_InputStream() {
- s = new Scanner(new PipedInputStream());
- assertNotNull(s);
- s.close();
-
- // Scanner(InputStream)
- try {
- s = new Scanner((InputStream) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- // TODO: test if the default charset is used.
- }
-
- /**
- * @tests java.util.Scanner#Scanner(InputStream, String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Scanner",
- args = {java.io.InputStream.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_io_InputStreamLjava_lang_String() {
- s = new Scanner(new PipedInputStream(), Charset.defaultCharset().name());
- assertNotNull(s);
- s.close();
-
- try {
- s = new Scanner((PipedInputStream) null, "invalid charset");
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- s = new Scanner(new PipedInputStream(), null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- s = new Scanner(new PipedInputStream(), "invalid charset");
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- // TODO: test if the specified charset is used.
- }
-
- /**
- * @tests java.util.Scanner#Scanner(Readable)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Scanner",
- args = {java.lang.Readable.class}
- )
- public void test_ConstructorLjava_lang_Readable() {
- s = new Scanner(new StringReader("test string"));
- assertNotNull(s);
- s.close();
-
- // Scanner(Readable)
- try {
- s = new Scanner((Readable) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Scanner#Scanner(ReadableByteChannel)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Scanner",
- args = {java.nio.channels.ReadableByteChannel.class}
- )
- public void test_ConstructorLjava_nio_channels_ReadableByteChannel()
- throws IOException {
- File tmpFile = File.createTempFile("TestFileForScanner", ".tmp");
- FileChannel fc = new FileOutputStream(tmpFile).getChannel();
- s = new Scanner(fc);
- assertNotNull(s);
- s.close();
- assertTrue(tmpFile.delete());
-
- // Scanner(ReadableByteChannel)
- try {
- s = new Scanner((ReadableByteChannel) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- // TODO: test if the default charset is used.
- }
-
- /**
- * @tests java.util.Scanner#Scanner(ReadableByteChannel, String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Scanner",
- args = {java.nio.channels.ReadableByteChannel.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_nio_channels_ReadableByteChannelLjava_lang_String()
- throws IOException {
- File tmpFile = File.createTempFile("TestFileForScanner", ".tmp");
- FileChannel fc = new FileOutputStream(tmpFile).getChannel();
- s = new Scanner(fc, Charset.defaultCharset().name());
- assertNotNull(s);
- s.close();
-
- fc = new FileOutputStream(tmpFile).getChannel();
- try {
- s = new Scanner(fc, "invalid charset");
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- fc.close();
- assertTrue(tmpFile.delete());
-
- // Scanner(ReadableByteChannel = null, Charset = null)
- try {
- s = new Scanner((ReadableByteChannel) null, null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- // Scanner(ReadableByteChannel = null, Charset = invalid)
- try {
- s = new Scanner((ReadableByteChannel) null, "invalid");
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- // Scanner(ReadableByteChannel, Charset = null)
- try {
- s = new Scanner(fc, null);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- // TODO: test if the specified charset is used.
- }
-
- /**
- * @tests java.util.Scanner#Scanner(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Scanner",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- s = new Scanner("test string");
- assertNotNull(s);
- s.close();
-
- // Scanner(String)
- try {
- s = new Scanner((String) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.Scanner#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "close",
- args = {}
- )
- public void test_close() throws IOException {
- File tmpFile = File.createTempFile("TestFileForScanner", ".tmp");
- FileOutputStream fos = new FileOutputStream(tmpFile);
- FileChannel fc = fos.getChannel();
- s = new Scanner(fc);
-
- // Write out a int before the scanner is closed, should be OK.
- fos.write(12);
-
- s.close();
- assertFalse(fc.isOpen());
-
- // Write out a int after the scanner is closed, IOException should be
- // thrown out.
- try {
- fos.write(12);
- fail("Should throw IOException");
- } catch (IOException e) {
- // expected
- }
-
- s.close(); // no exception should be thrown
- assertTrue(tmpFile.delete());
- }
-
- /**
- * @tests java.util.Scanner#ioException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ioException",
- args = {}
- )
- public void test_ioException() throws IOException {
- MockCloseable mc = new MockCloseable();
- s = new Scanner(mc);
- assertNull(s.ioException()); // No operation, no exception
-
- s.close(); // IOException should be cached
- assertNotNull(s.ioException());
- assertTrue(s.ioException() instanceof IOException);
- }
-
- /**
- * @tests java.util.Scanner#delimiter()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "delimiter",
- args = {}
- )
- public void test_delimiter() {
- s = new Scanner("test");
- Pattern pattern = s.delimiter();
- assertEquals("\\p{javaWhitespace}+", pattern.toString());
- }
-
- /**
- * @tests java.util.Scanner#useDelimiter(Pattern)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "useDelimiter",
- args = {java.util.regex.Pattern.class}
- )
- public void test_useDelimiter_LPattern() {
- s = new Scanner("test");
- s.useDelimiter(Pattern.compile("\\w+"));
- assertEquals("\\w+", s.delimiter().toString());
-
- s = new Scanner("test");
- s.useDelimiter((Pattern) null);
- assertNull(s.delimiter());
- }
-
- /**
- * @tests java.util.Scanner#useDelimiter(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "useDelimiter",
- args = {java.lang.String.class}
- )
- public void test_useDelimiter_String() {
- s = new Scanner("test");
- try {
- s.useDelimiter((String) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- s = new Scanner("test");
- s.useDelimiter("\\w+");
- assertEquals("\\w+", s.delimiter().toString());
- }
-
- /**
- * @tests java.util.Scanner#locale()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "locale",
- args = {}
- )
- public void test_locale() {
- s = new Scanner("test");
- assertEquals(Locale.getDefault(), s.locale());
- }
-
- /**
- * @tests java.util.Scanner#useLocale(Locale)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "useLocale",
- args = {java.util.Locale.class}
- )
- public void test_useLocale_LLocale() {
- s = new Scanner("test");
- try {
- s.useLocale(null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- s.useLocale(new Locale("test", "test"));
- assertEquals(new Locale("test", "test"), s.locale());
- }
-
- /**
- * @tests java.util.Scanner#radix()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "radix",
- args = {}
- )
- public void test_radix() {
- s = new Scanner("test");
- assertEquals(10, s.radix());
- }
-
- /**
- * @tests java.util.Scanner#useRadix()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "useRadix",
- args = {int.class}
- )
- public void test_useRadix_I() {
- s = new Scanner("test");
- try {
- s.useRadix(Character.MIN_RADIX - 1);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- s.useRadix(Character.MAX_RADIX + 1);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- s.useRadix(11);
- assertEquals(11, s.radix());
- }
-
- /**
- * @tests java.util.Scanner#remove()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {}
- )
- public void test_remove() {
- s = new Scanner("aab*b*").useDelimiter("\\*");
- try {
- s.remove();
- fail("should throw UnsupportedOperationException");
- } catch (UnsupportedOperationException e) {
- //Expected
- }
- }
-
- /**
- * @tests java.util.Scanner#match()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "match",
- args = {}
- )
- public void test_match() {
- MatchResult result ;
- s = new Scanner("1 2 ");
- try {
- s.match();
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // Expected
- }
- assertEquals("1", s.next());
- assertEquals("2", s.next());
- result = s.match();
- assertEquals(2, result.start());
- assertEquals(3, result.end());
- assertEquals(2, result.start(0));
- assertEquals(3, result.end(0));
- assertEquals("2", result.group());
- assertEquals("2", result.group(0));
- assertEquals(0, result.groupCount());
- try {
- result.start(1);
- fail("should throw IndexOutOfBoundsException");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- try {
- s.next();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
- try {
- s.match();
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // Expected
- }
-
- s = new Scanner("True faLse");
- try {
- s.match();
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // Expected
- }
- assertTrue(s.nextBoolean());
- result = s.match();
- assertEquals(0, result.start());
- assertEquals(4, result.end());
- assertEquals(0, result.start(0));
- assertEquals(4, result.end(0));
- assertEquals("True", result.group());
- assertEquals(0, result.groupCount());
- assertFalse(s.nextBoolean());
- try {
- s.nextBoolean();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
- try {
- s.match();
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // Expected
- }
-
- s = new Scanner("True faLse");
- assertTrue(s.nextBoolean());
- result = s.match();
- assertEquals(0, result.start());
- assertEquals(4, result.end());
- assertEquals(0, result.start(0));
- assertEquals(4, result.end(0));
- assertEquals("True", result.group());
- assertEquals(0, result.groupCount());
- s.close();
- try {
- s.nextBoolean();
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // Expected
- }
- result = s.match();
- assertEquals(0, result.start());
- assertEquals(4, result.end());
- assertEquals(0, result.start(0));
- assertEquals(4, result.end(0));
- assertEquals("True", result.group());
- assertEquals(0, result.groupCount());
-
- s = new Scanner("True fase");
- assertTrue(s.nextBoolean());
- assertEquals(0, result.groupCount());
- try {
- s.nextBoolean();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
- try {
- s.match();
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // Expected
- }
-
- s = new Scanner("True fase");
- assertTrue(s.nextBoolean());
- try {
- s.next((Pattern)null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- result = s.match();
- assertEquals(0, result.start());
- assertEquals(4, result.end());
- assertEquals(0, result.start(0));
- assertEquals(4, result.end(0));
- assertEquals("True", result.group());
- assertEquals(0, result.groupCount());
-
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#next()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "next",
- args = {}
- )
- public void test_next() throws IOException {
- // use special delimiter
- s = new Scanner("1**2").useDelimiter("\\*");
- assertEquals("1", s.next());
- assertEquals("", s.next());
- assertEquals("2", s.next());
-
- s = new Scanner(" \t 1 \t 2").useDelimiter("\\s*");
- assertEquals("1", s.next());
- assertEquals("2", s.next());
- try {
- s.next();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- s = new Scanner("a").useDelimiter("a?");
- try {
- s.next();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- s = new Scanner("aa").useDelimiter("a?");
- assertEquals("", s.next());
- try {
- s.next();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
-
- s = new Scanner("word( )test( )").useDelimiter("\\( \\)");
- assertEquals("word", s.next());
- assertEquals("test", s.next());
-
- s = new Scanner("? next ").useDelimiter("( )");
- assertEquals("?", s.next());
- assertEquals("next", s.next());
- assertEquals("", s.next());
-
- s = new Scanner("word1 word2 ");
- assertEquals("word1", s.next());
- assertEquals("word2", s.next());
- // test boundary case
- try {
- s.next();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // just delimiter exists in this scanner
- s = new Scanner(" ");
- try {
- s.next();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // nothing exists in this scanner
- s = new Scanner("");
- try {
- s.next();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // no delimiter exists in this scanner
- s = new Scanner("test");
- assertEquals("test", s.next());
-
- // input resourse starts with delimiter
- s = new Scanner(" test");
- assertEquals("test", s.next());
-
- // input resource ends with delimiter
- s = new Scanner(" test ");
- assertEquals("test", s.next());
-
- // Harmony uses 1024 as default buffer size,
- // What if a sentence can not be read in all in once.
- StringBuilder longSentence = new StringBuilder(1025);
- for (int i = 0; i < 11; i++) {
- longSentence.append(" ");
- }
- for (int i = 11; i < 1026; i++) {
- longSentence.append("a");
- }
- s = new Scanner(longSentence.toString());
- assertEquals(longSentence.toString().trim(), s.next());
-
- s = new Scanner(" test test");
- assertEquals("test", s.next());
- assertEquals("test", s.next());
-
- // What if use a delimiter of length 0.
- s = new Scanner("test\ntest").useDelimiter(Pattern.compile("^",
- Pattern.MULTILINE));
- assertEquals("test\n", s.next());
- assertEquals("test", s.next());
-
- s = new Scanner("").useDelimiter(Pattern.compile("^",
- Pattern.MULTILINE));
- try {
- s.next();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- s = new Scanner("").useDelimiter(Pattern.compile("^*",
- Pattern.MULTILINE));
- try {
- s.next();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- s = new Scanner("test\ntest").useDelimiter(Pattern.compile("^*",
- Pattern.MULTILINE));
- assertEquals("t", s.next());
- assertEquals("e", s.next());
-
- s = new Scanner("\ntest\ntest").useDelimiter(Pattern.compile("$",
- Pattern.MULTILINE));
- assertEquals("\ntest", s.next());
- assertEquals("\ntest", s.next());
-
- // test socket inputStream
- // Harmony uses 1024 as default buffer size,
- // what if the leading delimiter is larger than 1023
- for (int i = 0; i < 1024; i++) {
- os.write(" ".getBytes());
- }
- os.write(" 1 2 ".getBytes());
- s = new Scanner(client);
- assertEquals("1", s.next());
- assertEquals("2", s.next());
- os.write(" 1 2".getBytes());
- serverSocket.close();
- assertEquals("1", s.next());
- assertEquals("2", s.next());
- try {
- s.next();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- s.close();
- try {
- s.next();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#next(Pattern)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "next",
- args = {java.util.regex.Pattern.class}
- )
- public void test_nextLPattern() throws IOException {
- Pattern pattern;
- s = new Scanner("aab*2*").useDelimiter("\\*");
- pattern = Pattern.compile("a*b");
- assertEquals("aab", s.next(pattern));
- try {
- s.next(pattern);
- fail("should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("word ? ");
- pattern = Pattern.compile("\\w+");
- assertEquals("word", s.next(pattern));
- try {
- s.next(pattern);
- fail("should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("word1 word2 ");
- pattern = Pattern.compile("\\w+");
- assertEquals("word1", s.next(pattern));
- assertEquals("word2", s.next(pattern));
- // test boundary case
- try {
- s.next(pattern);
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // test socket inputStream
-
- os.write("aab 2".getBytes());
- serverSocket.close();
-
- s = new Scanner(client);
- pattern = Pattern.compile("a*b");
- assertEquals("aab", s.next(pattern));
- try {
- s.next(pattern);
- fail("should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s.close();
- try {
- s.next(pattern);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#next(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "next",
- args = {java.lang.String.class}
- )
- public void test_nextLString() throws IOException {
- s = new Scanner("b*a*").useDelimiter("\\*");
- assertEquals("b", s.next("a*b"));
- try {
- s.next("a*b");
- fail("should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("word ? ");
- assertEquals("word", s.next("\\w+"));
- try {
- s.next("\\w+");
- fail("should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("word1 next ");
- assertEquals("word1", s.next("\\w+"));
- assertEquals("next", s.next("\\w+"));
- // test boundary case
- try {
- s.next("\\w+");
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // test socket inputStream
- os.write("aab 2".getBytes());
- serverSocket.close();
-
- s = new Scanner(client);
- assertEquals("aab", s.next("a*b"));
- try {
- s.next("a*b");
- fail("should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s.close();
- try {
- s.next("a*b");
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#nextBoolean()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextBoolean",
- args = {}
- )
- public void test_nextBoolean() throws IOException {
- // case insensitive
- s = new Scanner("TRue");
- assertTrue(s.nextBoolean());
-
- s = new Scanner("tRue false");
- assertTrue(s.nextBoolean());
- assertFalse(s.nextBoolean());
- try {
- s.nextBoolean();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- s = new Scanner("true1");
- try {
- s.nextBoolean();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- try {
- s = new Scanner("");
- s.nextBoolean();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // test socket inputStream
- os.write("true false".getBytes());
- serverSocket.close();
-
- s = new Scanner(client);
- assertTrue(s.nextBoolean());
- assertFalse(s.nextBoolean());
-
- // ues '*' as delimiter
- s = new Scanner("true**false").useDelimiter("\\*");
- assertTrue(s.nextBoolean());
- try {
- s.nextBoolean();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- s = new Scanner("false( )").useDelimiter("\\( \\)");
- assertFalse(s.nextBoolean());
-
- s.close();
- try {
- s.nextBoolean();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#nextInt(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextInt",
- args = {int.class}
- )
- public void test_nextIntI() throws IOException {
- s = new Scanner("123 456");
- assertEquals(123, s.nextInt(10));
- assertEquals(456, s.nextInt(10));
- try {
- s.nextInt(10);
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 456");
- assertEquals(38, s.nextInt(5));
- try {
- s.nextInt(5);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // If the number is out of range
- s = new Scanner("123456789123456789123456789123456789");
- try {
- s.nextInt(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.GERMANY);
- try {
- s.nextInt(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
- s.useLocale(Locale.ENGLISH);
- // If exception is thrown out, input will not be advanced.
- assertEquals(23456, s.nextInt(10));
- assertEquals(23456, s.nextInt(10));
-
- /*
- * ''' is used in many locales as group separator.
- */
- s = new Scanner("23'456 23'456");
- s.useLocale(Locale.GERMANY);
- try {
- s.nextInt(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
- s.useLocale(new Locale("de", "CH"));
- // If exception is thrown out, input will not be advanced.
- assertEquals(23456, s.nextInt(10));
- assertEquals(23456, s.nextInt(10));
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06602 1\u06662");
- assertEquals(102, s.nextInt(10));
- try {
- s.nextInt(5);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- assertEquals(162, s.nextInt(10));
-
- /*
- * '.' is used in many locales as group separator. The input string
- * has Arabic-Indic digits .
- */
- s = new Scanner("23.45\u0666 23.456");
- s.useLocale(Locale.CHINESE);
- try {
- s.nextInt(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
- s.useLocale(Locale.GERMANY);
- // If exception is thrown out, input will not be advanced.
- assertEquals(23456, s.nextInt(10));
- assertEquals(23456, s.nextInt(10));
-
- // The input string starts with zero
- s = new Scanner("03,456");
- s.useLocale(Locale.ENGLISH);
- try {
- s.nextInt(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
-
- s = new Scanner("03456");
- assertEquals(3456, s.nextInt(10));
-
- s = new Scanner("\u06603,456");
- s.useLocale(Locale.ENGLISH);
- assertEquals(3456, s.nextInt(10));
-
- s = new Scanner("E3456");
- assertEquals(930902, s.nextInt(16));
- // The following test case fails on RI, because RI does not support
- // letter as leading digit
- if (!disableRIBugs) {
- s = new Scanner("E3,456");
- s.useLocale(Locale.ENGLISH);
- assertEquals(930902, s.nextInt(16));
- }
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("12300");
- s.useLocale(Locale.CHINESE);
- assertEquals(12300, s.nextInt(10));
-
- s = new Scanner("123\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertEquals(12300, s.nextInt(10));
-
- s = new Scanner("123\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertEquals(12300, s.nextInt(10));
-
- /*
- * There are three types of negative prefix all in all. '' '-' '(' There
- * are three types of negative suffix all in all. '' '-' ')' '(' and ')'
- * must be used togethor. Prefix '-' and suffix '-' must be used
- * exclusively.
- */
-
- /*
- * According to Integer regular expression: Integer :: = ( [-+]? (*
- * Numeral ) ) | LocalPositivePrefix Numeral LocalPositiveSuffix |
- * LocalNegativePrefix Numeral LocalNegativeSuffix 123- should be
- * recognized by scanner with locale ar_AE, (123) shouble be recognized
- * by scanner with locale mk_MK. But this is not the case on RI.
- */
- s = new Scanner("-123 123- -123-");
- s.useLocale(new Locale("ar", "AE"));
- assertEquals(-123, s.nextInt(10));
- // The following test case fails on RI
- if (!disableRIBugs) {
- assertEquals(-123, s.nextInt(10));
- }
- try {
- s.nextInt(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
-
- s = new Scanner("-123 123- (123)");
- s.useLocale(new Locale("mk", "MK"));
- assertEquals(-123, s.nextInt(10));
- try {
- s.nextInt();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
- // Skip the un-recognizable token 123-.
- assertEquals("123-", s.next());
- // The following test case fails on RI
- if (!disableRIBugs) {
- assertEquals(-123, s.nextInt(10));
-
- // If the parameter radix is illegal, the following test cases fail on
- // RI
- try {
- s.nextInt(Character.MIN_RADIX - 1);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- try {
- s.nextInt(Character.MAX_RADIX + 1);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- }
-
- s.close();
- try {
- s.nextInt(10);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#nextInt()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextInt",
- args = {}
- )
- public void test_nextInt() throws IOException {
- s = new Scanner("123 456");
- assertEquals(123, s.nextInt());
- assertEquals(456, s.nextInt());
- try {
- s.nextInt();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 456");
- s.useRadix(5);
- assertEquals(38, s.nextInt());
- try {
- s.nextInt();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // If the number is out of range
- s = new Scanner("123456789123456789123456789123456789");
- try {
- s.nextInt();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.GERMANY);
- try {
- s.nextInt();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
- s.useLocale(Locale.ENGLISH);
- // If exception is thrown out, input will not be advanced.
- assertEquals(23456, s.nextInt());
- assertEquals(23456, s.nextInt());
-
- /*
- * ''' is used in many locales as group separator.
- */
- s = new Scanner("23'456 23'456");
- s.useLocale(Locale.GERMANY);
- try {
- s.nextInt();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
- s.useLocale(new Locale("de", "CH"));
- // If exception is thrown out, input will not be advanced.
- assertEquals(23456, s.nextInt());
- assertEquals(23456, s.nextInt());
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06602 1\u06662");
- assertEquals(102, s.nextInt());
- s.useRadix(5);
- try {
- s.nextInt();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useRadix(10);
- assertEquals(162, s.nextInt());
-
- /*
- * '.' is used in many locales as group separator. The input string
- * has Arabic-Indic digits .
- */
- s = new Scanner("23.45\u0666 23.456");
- s.useLocale(Locale.CHINESE);
- try {
- s.nextInt();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
- s.useLocale(Locale.GERMANY);
- // If exception is thrown out, input will not be advanced.
- assertEquals(23456, s.nextInt());
- assertEquals(23456, s.nextInt());
-
- // The input string starts with zero
- s = new Scanner("03,456");
- s.useLocale(Locale.ENGLISH);
- try {
- s.nextInt();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
-
- s = new Scanner("03456");
- assertEquals(3456, s.nextInt());
-
- s = new Scanner("\u06603,456");
- s.useLocale(Locale.ENGLISH);
- assertEquals(3456, s.nextInt());
-
- s = new Scanner("E3456");
- s.useRadix(16);
- assertEquals(930902, s.nextInt());
-
- // The following test case fails on RI, because RI does not support
- // letter as leading digit
- s = new Scanner("E3,456");
- s.useLocale(Locale.ENGLISH);
- s.useRadix(16);
- if (!disableRIBugs) {
- assertEquals(930902, s.nextInt());
- }
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("12300");
- s.useLocale(Locale.CHINESE);
- assertEquals(12300, s.nextInt());
-
- s = new Scanner("123\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertEquals(12300, s.nextInt());
-
- s = new Scanner("123\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertEquals(12300, s.nextInt());
-
- /*
- * There are three types of negative prefix all in all. '' '-' '(' There
- * are three types of negative suffix all in all. '' '-' ')' '(' and ')'
- * must be used togethor. Prefix '-' and suffix '-' must be used
- * exclusively.
- */
-
- /*
- * According to Integer regular expression: Integer :: = ( [-+]? (*
- * Numeral ) ) | LocalPositivePrefix Numeral LocalPositiveSuffix |
- * LocalNegativePrefix Numeral LocalNegativeSuffix 123- should be
- * recognized by scanner with locale ar_AE, (123) shouble be recognized
- * by scanner with locale mk_MK. But this is not the case on RI.
- */
- s = new Scanner("-123 123- -123-");
- s.useLocale(new Locale("ar", "AE"));
- assertEquals(-123, s.nextInt());
- // The following test case fails on RI
- if (!disableRIBugs) {
- assertEquals(-123, s.nextInt());
- }
- try {
- s.nextInt();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
-
- s = new Scanner("-123 123- (123)");
- s.useLocale(new Locale("mk", "MK"));
- assertEquals(-123, s.nextInt());
- try {
- s.nextInt();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
- // Skip the un-recognizable token 123-.
- assertEquals("123-", s.next());
- // The following test case fails on RI
- if (!disableRIBugs) {
- assertEquals(-123, s.nextInt());
- }
-
- s.close();
- try {
- s.nextInt();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#nextByte(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextByte",
- args = {int.class}
- )
- public void test_nextByteI() throws IOException {
- s = new Scanner("123 126");
- assertEquals(123, s.nextByte(10));
- assertEquals(126, s.nextByte(10));
- try {
- s.nextByte(10);
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 126");
- assertEquals(38, s.nextByte(5));
- try {
- s.nextByte(5);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // If the number is out of range
- s = new Scanner("1234");
- try {
- s.nextByte(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06602 12\u0666");
- assertEquals(102, s.nextByte(10));
- try {
- s.nextByte(5);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- assertEquals(126, s.nextByte(10));
-
- s = new Scanner("012");
- assertEquals(12, s.nextByte(10));
-
- s = new Scanner("E");
- assertEquals(14, s.nextByte(16));
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("100");
- s.useLocale(Locale.CHINESE);
- assertEquals(100, s.nextByte(10));
-
- s = new Scanner("1\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertEquals(100, s.nextByte(10));
-
- s = new Scanner("1\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertEquals(100, s.nextByte(10));
-
- s = new Scanner("-123");
- s.useLocale(new Locale("ar", "AE"));
- assertEquals(-123, s.nextByte(10));
-
-
- s = new Scanner("-123");
- s.useLocale(new Locale("mk", "MK"));
- assertEquals(-123, s.nextByte(10));
-
- s.close();
- try {
- s.nextByte(10);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#nextByte()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextByte",
- args = {}
- )
- public void test_nextByte() throws IOException {
- s = new Scanner("123 126");
- assertEquals(123, s.nextByte());
- assertEquals(126, s.nextByte());
- try {
- s.nextByte();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 126");
- s.useRadix(5);
- assertEquals(38, s.nextByte());
- try {
- s.nextByte();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // If the number is out of range
- s = new Scanner("1234");
- try {
- s.nextByte();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06602 12\u0666");
- assertEquals(102, s.nextByte());
- s.useRadix(5);
- try {
- s.nextByte();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useRadix(10);
- assertEquals(126, s.nextByte());
-
- s = new Scanner("012");
- assertEquals(12, s.nextByte());
-
- s = new Scanner("E");
- s.useRadix(16);
- assertEquals(14, s.nextByte());
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("100");
- s.useLocale(Locale.CHINESE);
- assertEquals(100, s.nextByte());
-
- s = new Scanner("1\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertEquals(100, s.nextByte());
-
- s = new Scanner("1\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertEquals(100, s.nextByte());
-
- s = new Scanner("-123");
- s.useLocale(new Locale("ar", "AE"));
- assertEquals(-123, s.nextByte());
-
- s = new Scanner("-123");
- s.useLocale(new Locale("mk", "MK"));
- assertEquals(-123, s.nextByte());
-
- s.close();
- try {
- s.nextByte();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#nextFloat()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextFloat",
- args = {}
- )
- public void test_nextFloat() throws IOException {
- s = new Scanner("123 45\u0666. 123.4 .123 ");
- s.useLocale(Locale.ENGLISH);
- assertEquals((float)123.0, s.nextFloat());
- assertEquals((float)456.0, s.nextFloat());
- assertEquals((float)123.4, s.nextFloat());
- assertEquals((float)0.123, s.nextFloat());
- try {
- s.nextFloat();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- s = new Scanner("+123.4 -456.7 123,456.789 0.1\u06623,4");
- s.useLocale(Locale.ENGLISH);
- assertEquals((float)123.4, s.nextFloat());
- assertEquals((float)-456.7, s.nextFloat());
- assertEquals((float)123456.789, s.nextFloat());
- try {
- s.nextFloat();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // Scientific notation
- s = new Scanner("+123.4E10 -456.7e+12 123,456.789E-10");
- s.useLocale(Locale.ENGLISH);
- assertEquals((float)1.234E12, s.nextFloat());
- assertEquals((float)-4.567E14, s.nextFloat());
- assertEquals((float)1.23456789E-5, s.nextFloat());
-
- s = new Scanner("NaN Infinity -Infinity");
- assertEquals(Float.NaN, s.nextFloat());
- assertEquals(Float.POSITIVE_INFINITY, s.nextFloat());
- assertEquals(Float.NEGATIVE_INFINITY, s.nextFloat());
-
- String str=String.valueOf(Float.MAX_VALUE*2);
- s=new Scanner(str);
- assertEquals(Float.POSITIVE_INFINITY,s.nextFloat());
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.ENGLISH);
- assertEquals((float)23456.0, s.nextFloat());
- s.useLocale(Locale.GERMANY);
- assertEquals((float)23.456, s.nextFloat());
-
- s = new Scanner("23.456 23.456");
- s.useLocale(Locale.ENGLISH);
- assertEquals((float)23.456, s.nextFloat());
- s.useLocale(Locale.GERMANY);
- assertEquals((float)23456.0, s.nextFloat());
-
- s = new Scanner("23,456.7 23.456,7");
- s.useLocale(Locale.ENGLISH);
- assertEquals((float)23456.7, s.nextFloat());
- s.useLocale(Locale.GERMANY);
- assertEquals((float)23456.7, s.nextFloat());
-
- s = new Scanner("-123.4 123.4- -123.4-");
- s.useLocale(new Locale("ar", "AE"));
- assertEquals((float)-123.4, s.nextFloat());
- //The following test case fails on RI
- if (!disableRIBugs) {
- assertEquals((float)-123.4, s.nextFloat());
- }
- try {
- s.nextFloat();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("(123) 123- -123");
- s.useLocale(new Locale("mk", "MK"));
- if (!disableRIBugs) {
- assertEquals((float)-123.0, s.nextFloat());
- }
- try {
- s.nextFloat();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- // Skip the un-recognizable token 123-.
- if (!disableRIBugs) {
- assertEquals("123-", s.next());
- assertEquals((float)-123.0, s.nextFloat());
- }
-
- s.close();
- try {
- s.nextFloat();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#nextBigInteger(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextBigInteger",
- args = {int.class}
- )
- @KnownFailure("nextBigInteger method doesn't work properly if input string has Arabic-Indic digits")
- public void test_nextBigIntegerI() throws IOException {
- s = new Scanner("123 456");
- assertEquals(new BigInteger("123"), s.nextBigInteger(10));
- assertEquals(new BigInteger("456"), s.nextBigInteger(10));
- try {
- s.nextBigInteger(10);
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 456");
- assertEquals(new BigInteger("38"), s.nextBigInteger(5));
- try {
- s.nextBigInteger(5);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.GERMANY);
- try {
- s.nextBigInteger(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.ENGLISH);
- // If exception is thrown out, input will not be advanced.
- assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
- assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
-
- /*
- * ''' is used in many locales as group separator.
- */
- s = new Scanner("23'456 23'456");
- s.useLocale(Locale.GERMANY);
- try {
- s.nextBigInteger(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(new Locale("de", "CH"));
- // If exception is thrown out, input will not be advanced.
- assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
- assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06602 1\u06662");
- assertEquals(new BigInteger("102"), s.nextBigInteger(10));
- try {
- s.nextBigInteger(5);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- assertEquals(new BigInteger("162"), s.nextBigInteger(10));
-
- /*
- * '.' is used in many locales as group separator. The input string
- * has Arabic-Indic digits .
- */
- s = new Scanner("23.45\u0666 23.456");
- s.useLocale(Locale.CHINESE);
- try {
- s.nextBigInteger(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.GERMANY);
- // If exception is thrown out, input will not be advanced.
- assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
- assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
-
- // The input string starts with zero
- s = new Scanner("03,456");
- s.useLocale(Locale.ENGLISH);
- try {
- s.nextBigInteger(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("03456");
- assertEquals(new BigInteger("3456"), s.nextBigInteger(10));
-
- s = new Scanner("\u06603,456");
- s.useLocale(Locale.ENGLISH);
- assertEquals(new BigInteger("3456"), s.nextBigInteger(10));
-
- s = new Scanner("E34");
- assertEquals(new BigInteger("3636"), s.nextBigInteger(16));
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("12300");
- s.useLocale(Locale.CHINESE);
- assertEquals(new BigInteger("12300"), s.nextBigInteger(10));
-
- s = new Scanner("123\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertEquals(new BigInteger("12300"), s.nextBigInteger(10));
-
- s = new Scanner("123\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertEquals(new BigInteger("12300"), s.nextBigInteger(10));
-
- s = new Scanner("-123");
- s.useLocale(new Locale("ar", "AE"));
- assertEquals(new BigInteger("-123"), s.nextBigInteger(10));
-
-
- s = new Scanner("-123");
- s.useLocale(new Locale("mk", "MK"));
- assertEquals(new BigInteger("-123"), s.nextBigInteger(10));
-
- s.close();
- try {
- s.nextBigInteger(10);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#nextBigInteger()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextBigInteger",
- args = {}
- )
- @KnownFailure("nextBigInteger method doesn't work properly if input string has Arabic-Indic digits")
- public void test_nextBigInteger() throws IOException {
- s = new Scanner("123 456");
- assertEquals(new BigInteger("123"), s.nextBigInteger());
- assertEquals(new BigInteger("456"), s.nextBigInteger());
- try {
- s.nextBigInteger();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 456");
- s.useRadix(5);
- assertEquals(new BigInteger("38"), s.nextBigInteger());
- try {
- s.nextBigInteger();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.GERMANY);
- try {
- s.nextBigInteger();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.ENGLISH);
- // If exception is thrown out, input will not be advanced.
- assertEquals(new BigInteger("23456"), s.nextBigInteger());
- assertEquals(new BigInteger("23456"), s.nextBigInteger());
-
- /*
- * ''' is used in many locales as group separator.
- */
- s = new Scanner("23'456 23'456");
- s.useLocale(Locale.GERMANY);
- try {
- s.nextBigInteger();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(new Locale("de", "CH"));
- // If exception is thrown out, input will not be advanced.
- assertEquals(new BigInteger("23456"), s.nextBigInteger());
- assertEquals(new BigInteger("23456"), s.nextBigInteger());
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06602 1\u06662");
- assertEquals(new BigInteger("102"), s.nextBigInteger());
- s.useRadix(5);
- try {
- s.nextBigInteger();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useRadix(10);
- assertEquals(new BigInteger("162"), s.nextBigInteger());
-
- /*
- * '.' is used in many locales as group separator. The input string
- * has Arabic-Indic digits .
- */
- s = new Scanner("23.45\u0666 23.456");
- s.useLocale(Locale.CHINESE);
- try {
- s.nextBigInteger();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.GERMANY);
- // If exception is thrown out, input will not be advanced.
- assertEquals(new BigInteger("23456"), s.nextBigInteger());
- assertEquals(new BigInteger("23456"), s.nextBigInteger());
-
- // The input string starts with zero
- s = new Scanner("03,456");
- s.useLocale(Locale.ENGLISH);
- try {
- s.nextBigInteger();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("03456");
- assertEquals(new BigInteger("3456"), s.nextBigInteger());
-
- s = new Scanner("\u06603,456");
- s.useLocale(Locale.ENGLISH);
- assertEquals(new BigInteger("3456"), s.nextBigInteger());
-
- s = new Scanner("E34");
- s.useRadix(16);
- assertEquals(new BigInteger("3636"), s.nextBigInteger());
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("12300");
- s.useLocale(Locale.CHINESE);
- assertEquals(new BigInteger("12300"), s.nextBigInteger());
-
- s = new Scanner("123\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertEquals(new BigInteger("12300"), s.nextBigInteger());
-
- s = new Scanner("123\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertEquals(new BigInteger("12300"), s.nextBigInteger());
-
- s = new Scanner("-123");
- s.useLocale(new Locale("ar", "AE"));
- assertEquals(new BigInteger("-123"), s.nextBigInteger());
-
- s = new Scanner("-123");
- s.useLocale(new Locale("mk", "MK"));
- assertEquals(new BigInteger("-123"), s.nextBigInteger());
-
- s.close();
- try {
- s.nextBigInteger();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#nextShort(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextShort",
- args = {int.class}
- )
- public void test_nextShortI() throws IOException {
- s = new Scanner("123 456");
- assertEquals(123, s.nextShort(10));
- assertEquals(456, s.nextShort(10));
- try {
- s.nextShort(10);
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 456");
- assertEquals(38, s.nextShort(5));
- try {
- s.nextShort(5);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // If the number is out of range
- s = new Scanner("123456789");
- try {
- s.nextShort(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.GERMANY);
- try {
- s.nextShort(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.ENGLISH);
- // If exception is thrown out, input will not be advanced.
- assertEquals(23456, s.nextShort(10));
- assertEquals(23456, s.nextShort(10));
-
- /*
- * ''' is used in many locales as group separator.
- */
- s = new Scanner("23'456 23'456");
- s.useLocale(Locale.GERMANY);
- try {
- s.nextShort(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(new Locale("de", "CH"));
- // If exception is thrown out, input will not be advanced.
- assertEquals(23456, s.nextShort(10));
- assertEquals(23456, s.nextShort(10));
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06602 1\u06662");
- assertEquals(102, s.nextShort(10));
- try {
- s.nextShort(5);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- assertEquals(162, s.nextShort(10));
-
- /*
- * '.' is used in many locales as group separator. The input string
- * has Arabic-Indic digits .
- */
- s = new Scanner("23.45\u0666 23.456");
- s.useLocale(Locale.CHINESE);
- try {
- s.nextShort(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.GERMANY);
- // If exception is thrown out, input will not be advanced.
- assertEquals(23456, s.nextShort(10));
- assertEquals(23456, s.nextShort(10));
-
- // The input string starts with zero
- s = new Scanner("03,456");
- s.useLocale(Locale.ENGLISH);
- try {
- s.nextShort(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("03456");
- assertEquals(3456, s.nextShort(10));
-
- s = new Scanner("\u06603,456");
- s.useLocale(Locale.ENGLISH);
- assertEquals(3456, s.nextShort(10));
-
- s = new Scanner("E34");
- assertEquals(3636, s.nextShort(16));
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("12300");
- s.useLocale(Locale.CHINESE);
- assertEquals(12300, s.nextShort(10));
-
- s = new Scanner("123\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertEquals(12300, s.nextShort(10));
-
- s = new Scanner("123\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertEquals(12300, s.nextShort(10));
-
- s = new Scanner("-123");
- s.useLocale(new Locale("ar", "AE"));
- assertEquals(-123, s.nextShort(10));
-
-
- s = new Scanner("-123");
- s.useLocale(new Locale("mk", "MK"));
- assertEquals(-123, s.nextShort(10));
-
- s.close();
- try {
- s.nextShort(10);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#nextShort()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextShort",
- args = {}
- )
- public void test_nextShort() throws IOException {
- s = new Scanner("123 456");
- assertEquals(123, s.nextShort());
- assertEquals(456, s.nextShort());
- try {
- s.nextShort();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 456");
- s.useRadix(5);
- assertEquals(38, s.nextShort());
- try {
- s.nextShort();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // If the number is out of range
- s = new Scanner("123456789");
- try {
- s.nextShort();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.GERMANY);
- try {
- s.nextShort();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.ENGLISH);
- // If exception is thrown out, input will not be advanced.
- assertEquals(23456, s.nextShort());
- assertEquals(23456, s.nextShort());
-
- /*
- * ''' is used in many locales as group separator.
- */
- s = new Scanner("23'456 23'456");
- s.useLocale(Locale.GERMANY);
- try {
- s.nextShort();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(new Locale("de", "CH"));
- // If exception is thrown out, input will not be advanced.
- assertEquals(23456, s.nextShort());
- assertEquals(23456, s.nextShort());
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06602 1\u06662");
- assertEquals(102, s.nextShort());
- s.useRadix(5);
- try {
- s.nextShort();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useRadix(10);
- assertEquals(162, s.nextShort());
-
- /*
- * '.' is used in many locales as group separator. The input string
- * has Arabic-Indic digits .
- */
- s = new Scanner("23.45\u0666 23.456");
- s.useLocale(Locale.CHINESE);
- try {
- s.nextShort();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.GERMANY);
- // If exception is thrown out, input will not be advanced.
- assertEquals(23456, s.nextShort());
- assertEquals(23456, s.nextShort());
-
- // The input string starts with zero
- s = new Scanner("03,456");
- s.useLocale(Locale.ENGLISH);
- try {
- s.nextShort();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("03456");
- assertEquals(3456, s.nextShort());
-
- s = new Scanner("\u06603,456");
- s.useLocale(Locale.ENGLISH);
- assertEquals(3456, s.nextShort());
-
- s = new Scanner("E34");
- s.useRadix(16);
- assertEquals(3636, s.nextShort());
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("12300");
- s.useLocale(Locale.CHINESE);
- assertEquals(12300, s.nextShort());
-
- s = new Scanner("123\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertEquals(12300, s.nextShort());
-
- s = new Scanner("123\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertEquals(12300, s.nextShort());
-
- s = new Scanner("-123");
- s.useLocale(new Locale("ar", "AE"));
- assertEquals(-123, s.nextShort());
-
- s = new Scanner("-123");
- s.useLocale(new Locale("mk", "MK"));
- assertEquals(-123, s.nextShort());
-
- s.close();
- try {
- s.nextShort();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#nextLong(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextLong",
- args = {int.class}
- )
- public void test_nextLongI() throws IOException {
- s = new Scanner("123 456");
- assertEquals(123, s.nextLong(10));
- assertEquals(456, s.nextLong(10));
- try {
- s.nextLong(10);
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 456");
- assertEquals(38, s.nextLong(5));
- try {
- s.nextLong(5);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // If the number is out of range
- s = new Scanner("123456789123456789123456789123456789");
- try {
- s.nextLong(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.GERMANY);
- try {
- s.nextLong(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.ENGLISH);
- // If exception is thrown out, input will not be advanced.
- assertEquals(23456, s.nextLong(10));
- assertEquals(23456, s.nextLong(10));
-
- /*
- * ''' is used in many locales as group separator.
- */
- s = new Scanner("23'456 23'456");
- s.useLocale(Locale.GERMANY);
- try {
- s.nextLong(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(new Locale("de", "CH"));
- // If exception is thrown out, input will not be advanced.
- assertEquals(23456, s.nextLong(10));
- assertEquals(23456, s.nextLong(10));
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06602 1\u06662");
- assertEquals(102, s.nextLong(10));
- try {
- s.nextLong(5);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- assertEquals(162, s.nextLong(10));
-
- /*
- * '.' is used in many locales as group separator. The input string
- * has Arabic-Indic digits .
- */
- s = new Scanner("23.45\u0666 23.456");
- s.useLocale(Locale.CHINESE);
- try {
- s.nextLong(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.GERMANY);
- // If exception is thrown out, input will not be advanced.
- assertEquals(23456, s.nextLong(10));
- assertEquals(23456, s.nextLong(10));
-
- // The input string starts with zero
- s = new Scanner("03,456");
- s.useLocale(Locale.ENGLISH);
- try {
- s.nextLong(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("03456");
- assertEquals(3456, s.nextLong(10));
-
- s = new Scanner("\u06603,456");
- s.useLocale(Locale.ENGLISH);
- assertEquals(3456, s.nextLong(10));
-
- s = new Scanner("E34");
- assertEquals(3636, s.nextLong(16));
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("12300");
- s.useLocale(Locale.CHINESE);
- assertEquals(12300, s.nextLong(10));
-
- s = new Scanner("123\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertEquals(12300, s.nextLong(10));
-
- s = new Scanner("123\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertEquals(12300, s.nextLong(10));
-
- s = new Scanner("-123");
- s.useLocale(new Locale("ar", "AE"));
- assertEquals(-123, s.nextLong(10));
-
-
- s = new Scanner("-123");
- s.useLocale(new Locale("mk", "MK"));
- assertEquals(-123, s.nextLong(10));
-
- s.close();
- try {
- s.nextLong(10);
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#nextLong()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextLong",
- args = {}
- )
- public void test_nextLong() throws IOException {
- s = new Scanner("123 456");
- assertEquals(123, s.nextLong());
- assertEquals(456, s.nextLong());
- try {
- s.nextLong();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 456");
- s.useRadix(5);
- assertEquals(38, s.nextLong());
- try {
- s.nextLong();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // If the number is out of range
- s = new Scanner("123456789123456789123456789123456789");
- try {
- s.nextLong();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.GERMANY);
- try {
- s.nextLong();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.ENGLISH);
- // If exception is thrown out, input will not be advanced.
- assertEquals(23456, s.nextLong());
- assertEquals(23456, s.nextLong());
-
- /*
- * ''' is used in many locales as group separator.
- */
- s = new Scanner("23'456 23'456");
- s.useLocale(Locale.GERMANY);
- try {
- s.nextLong();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(new Locale("de", "CH"));
- // If exception is thrown out, input will not be advanced.
- assertEquals(23456, s.nextLong());
- assertEquals(23456, s.nextLong());
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06602 1\u06662");
- assertEquals(102, s.nextLong());
- s.useRadix(5);
- try {
- s.nextLong();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useRadix(10);
- assertEquals(162, s.nextLong());
-
- /*
- * '.' is used in many locales as group separator. The input string
- * has Arabic-Indic digits .
- */
- s = new Scanner("23.45\u0666 23.456");
- s.useLocale(Locale.CHINESE);
- try {
- s.nextLong();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.GERMANY);
- // If exception is thrown out, input will not be advanced.
- assertEquals(23456, s.nextLong());
- assertEquals(23456, s.nextLong());
-
- // The input string starts with zero
- s = new Scanner("03,456");
- s.useLocale(Locale.ENGLISH);
- try {
- s.nextLong();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("03456");
- assertEquals(3456, s.nextLong());
-
- s = new Scanner("\u06603,456");
- s.useLocale(Locale.ENGLISH);
- assertEquals(3456, s.nextLong());
-
- s = new Scanner("E34");
- s.useRadix(16);
- assertEquals(3636, s.nextLong());
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("12300");
- s.useLocale(Locale.CHINESE);
- assertEquals(12300, s.nextLong());
-
- s = new Scanner("123\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertEquals(12300, s.nextLong());
-
- s = new Scanner("123\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertEquals(12300, s.nextLong());
-
- s = new Scanner("-123");
- s.useLocale(new Locale("ar", "AE"));
- assertEquals(-123, s.nextLong());
-
- s = new Scanner("-123");
- s.useLocale(new Locale("mk", "MK"));
- assertEquals(-123, s.nextLong());
-
- s.close();
- try {
- s.nextLong();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNext()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasNext",
- args = {}
- )
- public void test_hasNext() throws IOException {
- s = new Scanner("1##2").useDelimiter("\\#");
- assertTrue(s.hasNext());
- assertEquals("1", s.next());
- assertEquals("", s.next());
- assertEquals("2", s.next());
- assertFalse(s.hasNext());
- s.close();
- try {
- s.hasNext();
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- s = new Scanner("1( )2( )").useDelimiter("\\( \\)");
- assertTrue(s.hasNext());
- assertTrue(s.hasNext());
- assertEquals("1", s.next());
- assertEquals("2", s.next());
-
- s = new Scanner("1 2 ").useDelimiter("( )");
- assertEquals("1", s.next());
- assertEquals("2", s.next());
- assertTrue(s.hasNext());
- assertEquals("", s.next());
-
- s = new Scanner("1\n2 ");
- assertEquals("1", s.next());
- assertTrue(s.hasNext());
- assertEquals("2", s.next());
- assertFalse(s.hasNext());
- // test boundary case
- try {
- s.next();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- s = new Scanner("1'\n'2 ");
- assertEquals("1'", s.next());
- assertTrue(s.hasNext());
- assertEquals("'2", s.next());
- assertFalse(s.hasNext());
- // test boundary case
- try {
- s.next();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- s = new Scanner(" ");
- assertFalse(s.hasNext());
-
- // test socket inputStream
-
- os.write("1 2".getBytes());
- serverSocket.close();
-
- s = new Scanner(client);
- assertEquals("1", s.next());
- assertTrue(s.hasNext());
- assertEquals("2", s.next());
- assertFalse(s.hasNext());
- try {
- s.next();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNext(Pattern)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasNext",
- args = {java.util.regex.Pattern.class}
- )
- public void test_hasNextLPattern() throws IOException {
- Pattern pattern;
- s = new Scanner("aab@2@abb@").useDelimiter("\\@");
- pattern = Pattern.compile("a*b");
- assertTrue(s.hasNext(pattern));
- assertEquals("aab", s.next(pattern));
- assertFalse(s.hasNext(pattern));
- try {
- s.next(pattern);
- fail("should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("word ? ");
- pattern = Pattern.compile("\\w+");
- assertTrue(s.hasNext(pattern));
- assertEquals("word", s.next(pattern));
- assertFalse(s.hasNext(pattern));
- try {
- s.next(pattern);
- fail("should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("word1 WorD2 ");
- pattern = Pattern.compile("\\w+");
- assertTrue(s.hasNext(pattern));
- assertEquals("word1", s.next(pattern));
- assertTrue(s.hasNext(pattern));
- assertEquals("WorD2", s.next(pattern));
- assertFalse(s.hasNext(pattern));
- try {
- s.next(pattern);
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- s = new Scanner("word1 WorD2 ");
- pattern = Pattern.compile("\\w+");
- try {
- s.hasNext((Pattern) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- s.close();
- try {
- s.hasNext(pattern);
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- // test socket inputStream
- os.write("aab b".getBytes());
- serverSocket.close();
-
- s = new Scanner(client);
- pattern = Pattern.compile("a+b");
- assertTrue(s.hasNext(pattern));
- assertEquals("aab", s.next(pattern));
- assertFalse(s.hasNext(pattern));
- try {
- s.next(pattern);
- fail("should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNext(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasNext",
- args = {java.lang.String.class}
- )
- public void test_hasNextLString() throws IOException {
- s = new Scanner("aab@2@abb@").useDelimiter("\\@");
- try {
- s.hasNext((String)null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- s = new Scanner("aab*b*").useDelimiter("\\*");
- assertTrue(s.hasNext("a+b"));
- assertEquals("aab", s.next("a+b"));
- assertFalse(s.hasNext("a+b"));
- try {
- s.next("a+b");
- fail("should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.close();
- try {
- s.hasNext("a+b");
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- s = new Scanner("WORD ? ");
- assertTrue(s.hasNext("\\w+"));
- assertEquals("WORD", s.next("\\w+"));
- assertFalse(s.hasNext("\\w+"));
- try {
- s.next("\\w+");
- fail("should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("word1 word2 ");
- assertEquals("word1", s.next("\\w+"));
- assertEquals("word2", s.next("\\w+"));
- // test boundary case
- try {
- s.next("\\w+");
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // test socket inputStream
-
- os.write("aab 2".getBytes());
- serverSocket.close();
-
- s = new Scanner(client);
- assertTrue(s.hasNext("a*b"));
- assertEquals("aab", s.next("a*b"));
- assertFalse(s.hasNext("a*b"));
- try {
- s.next("a*b");
- fail("should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNextBoolean()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasNextBoolean",
- args = {}
- )
- public void test_hasNextBoolean() throws IOException {
-
- s = new Scanner("TRue");
- assertTrue(s.hasNextBoolean());
- assertTrue(s.nextBoolean());
-
- s = new Scanner("tRue false");
- assertTrue(s.hasNextBoolean());
- assertTrue(s.nextBoolean());
- assertTrue(s.hasNextBoolean());
- assertFalse(s.nextBoolean());
-
- s = new Scanner("");
- assertFalse(s.hasNextBoolean());
-
- // test socket inputStream
-
- os.write("true false ".getBytes());
- serverSocket.close();
-
- s = new Scanner(client);
- assertTrue(s.hasNextBoolean());
- assertTrue(s.nextBoolean());
-
- // ues '*' as delimiter
- s = new Scanner("true**false").useDelimiter("\\*");
- assertTrue(s.hasNextBoolean());
- assertTrue(s.nextBoolean());
- assertFalse(s.hasNextBoolean());
- try {
- s.nextBoolean();
- fail("should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- s = new Scanner("false( )").useDelimiter("\\( \\)");
- assertTrue(s.hasNextBoolean());
- assertFalse(s.nextBoolean());
- assertFalse(s.hasNextBoolean());
-
- s.close();
- try {
- s.hasNextBoolean();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNextByte(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IllegalStateException checking missed.",
- method = "hasNextByte",
- args = {int.class}
- )
- public void test_hasNextByteI() throws IOException {
- s = new Scanner("123 126");
- assertTrue(s.hasNextByte(10));
- assertEquals(123, s.nextByte(10));
- assertTrue(s.hasNextByte(10));
- assertEquals(126, s.nextByte(10));
- assertFalse(s.hasNextByte(10));
- try {
- s.nextByte(10);
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 126");
- assertTrue(s.hasNextByte(5));
- assertEquals(38, s.nextByte(5));
- assertFalse(s.hasNextByte(5));
- try {
- s.nextByte(5);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // If the number is out of range
- s = new Scanner("1234");
- assertFalse(s.hasNextByte(10));
- try {
- s.nextByte(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06602 12\u0666");
- assertTrue(s.hasNextByte(10));
- assertEquals(102, s.nextByte(10));
- assertFalse(s.hasNextByte(5));
- try {
- s.nextByte(5);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- assertTrue(s.hasNextByte(10));
- assertEquals(126, s.nextByte(10));
-
- s = new Scanner("012");
- assertTrue(s.hasNextByte(10));
- assertEquals(12, s.nextByte(10));
-
- s = new Scanner("E");
- assertTrue(s.hasNextByte(16));
- assertEquals(14, s.nextByte(16));
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("100");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextByte(10));
- assertEquals(100, s.nextByte(10));
-
- s = new Scanner("1\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextByte(10));
- assertEquals(100, s.nextByte(10));
-
- s = new Scanner("1\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextByte(10));
- assertEquals(100, s.nextByte(10));
-
- s = new Scanner("-123");
- s.useLocale(new Locale("ar", "AE"));
- assertTrue(s.hasNextByte(10));
- assertEquals(-123, s.nextByte(10));
-
-
- s = new Scanner("-123");
- s.useLocale(new Locale("mk", "MK"));
- assertTrue(s.hasNextByte(10));
- assertEquals(-123, s.nextByte(10));
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNextByte(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test.",
- method = "hasNextByte",
- args = {int.class}
- )
- public void test_hasNextByteI_cache() throws IOException{
- //regression for HARMONY-2063
- s = new Scanner("123 45");
- assertTrue(s.hasNextByte(8));
- assertEquals(83, s.nextByte());
- assertEquals(45, s.nextByte());
-
- s = new Scanner("123 45");
- assertTrue(s.hasNextByte(10));
- assertTrue(s.hasNextByte(8));
- assertEquals(83, s.nextByte());
- assertEquals(45, s.nextByte());
-
- s = new Scanner("-123 -45");
- assertTrue(s.hasNextByte(8));
- assertEquals(-123, s.nextInt());
- assertEquals(-45, s.nextByte());
-
- s = new Scanner("123 45");
- assertTrue(s.hasNextByte());
- s.close();
- try {
- s.nextByte();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- }
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNextByte()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasNextByte",
- args = {}
- )
- public void test_hasNextByte() throws IOException {
- s = new Scanner("123 126");
- assertTrue(s.hasNextByte());
- assertEquals(123, s.nextByte());
- assertTrue(s.hasNextByte());
- assertEquals(126, s.nextByte());
- assertFalse(s.hasNextByte());
- try {
- s.nextByte();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 126");
- s.useRadix(5);
- assertTrue(s.hasNextByte());
- assertEquals(38, s.nextByte());
- assertFalse(s.hasNextByte());
- try {
- s.nextByte();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // If the number is out of range
- s = new Scanner("1234");
- assertFalse(s.hasNextByte());
- try {
- s.nextByte();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06602 12\u0666");
- assertTrue(s.hasNextByte());
- assertEquals(102, s.nextByte());
- s.useRadix(5);
- assertFalse(s.hasNextByte());
- try {
- s.nextByte();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useRadix(10);
- assertTrue(s.hasNextByte());
- assertEquals(126, s.nextByte());
-
- s = new Scanner("012");
- assertEquals(12, s.nextByte());
-
- s = new Scanner("E");
- s.useRadix(16);
- assertTrue(s.hasNextByte());
- assertEquals(14, s.nextByte());
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("100");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextByte());
- assertEquals(100, s.nextByte());
-
- s = new Scanner("1\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextByte());
- assertEquals(100, s.nextByte());
-
- s = new Scanner("1\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextByte());
- assertEquals(100, s.nextByte());
-
- s = new Scanner("-123");
- s.useLocale(new Locale("ar", "AE"));
- assertTrue(s.hasNextByte());
- assertEquals(-123, s.nextByte());
-
- s = new Scanner("-123");
- s.useLocale(new Locale("mk", "MK"));
- assertTrue(s.hasNextByte());
- assertEquals(-123, s.nextByte());
-
- s.close();
- try {
- s.hasNextByte();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNextBigInteger(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IllegalStateException checking missed.",
- method = "hasNextBigInteger",
- args = {int.class}
- )
- @KnownFailure("hasNextBigInteger method doesn't work properly if input string has Arabic-Indic digits")
- public void test_hasNextBigIntegerI() throws IOException {
- s = new Scanner("123 456");
- assertTrue(s.hasNextBigInteger(10));
- assertEquals(new BigInteger("123"), s.nextBigInteger(10));
- assertTrue(s.hasNextBigInteger(10));
- assertEquals(new BigInteger("456"), s.nextBigInteger(10));
- assertFalse(s.hasNextBigInteger(10));
- try {
- s.nextBigInteger(10);
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 456");
- assertTrue(s.hasNextBigInteger(5));
- assertEquals(new BigInteger("38"), s.nextBigInteger(5));
- assertFalse(s.hasNextBigInteger(5));
- try {
- s.nextBigInteger(5);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.GERMANY);
- assertFalse(s.hasNextBigInteger(10));
- try {
- s.nextBigInteger(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.ENGLISH);
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextBigInteger(10));
- assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
- assertTrue(s.hasNextBigInteger(10));
- assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
-
- /*
- * ''' is used in many locales as group separator.
- */
- s = new Scanner("23'456 23'456");
- s.useLocale(Locale.GERMANY);
- assertFalse(s.hasNextBigInteger(10));
- try {
- s.nextBigInteger(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(new Locale("de", "CH"));
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextBigInteger(10));
- assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
- assertTrue(s.hasNextBigInteger(10));
- assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06602 1\u06662");
- assertTrue(s.hasNextBigInteger(10));
- assertEquals(new BigInteger("102"), s.nextBigInteger(10));
- assertFalse(s.hasNextBigInteger(5));
- try {
- s.nextBigInteger(5);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- assertTrue(s.hasNextBigInteger(10));
- assertEquals(new BigInteger("162"), s.nextBigInteger(10));
-
- /*
- * '.' is used in many locales as group separator. The input string
- * has Arabic-Indic digits .
- */
- s = new Scanner("23.45\u0666 23.456");
- s.useLocale(Locale.CHINESE);
- assertFalse(s.hasNextBigInteger(10));
- try {
- s.nextBigInteger(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.GERMANY);
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextBigInteger(10));
- assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
- assertTrue(s.hasNextBigInteger(10));
- assertEquals(new BigInteger("23456"), s.nextBigInteger(10));
-
- // The input string starts with zero
- s = new Scanner("03,456");
- s.useLocale(Locale.ENGLISH);
- assertFalse(s.hasNextBigInteger(10));
- try {
- s.nextBigInteger(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("03456");
- assertTrue(s.hasNextBigInteger(10));
- assertEquals(new BigInteger("3456"), s.nextBigInteger(10));
-
- s = new Scanner("\u06603,456");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextBigInteger(10));
- assertEquals(new BigInteger("3456"), s.nextBigInteger(10));
-
- s = new Scanner("E34");
- assertTrue(s.hasNextBigInteger(16));
- assertEquals(new BigInteger("3636"), s.nextBigInteger(16));
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("12300");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextBigInteger(10));
- assertEquals(new BigInteger("12300"), s.nextBigInteger(10));
-
- s = new Scanner("123\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextBigInteger(10));
- assertEquals(new BigInteger("12300"), s.nextBigInteger(10));
-
- s = new Scanner("123\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextBigInteger(10));
- assertEquals(new BigInteger("12300"), s.nextBigInteger(10));
-
- s = new Scanner("-123");
- s.useLocale(new Locale("ar", "AE"));
- assertTrue(s.hasNextBigInteger(10));
- assertEquals(new BigInteger("-123"), s.nextBigInteger(10));
-
-
- s = new Scanner("-123");
- s.useLocale(new Locale("mk", "MK"));
- assertTrue(s.hasNextBigInteger(10));
- assertEquals(new BigInteger("-123"), s.nextBigInteger(10));
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNextBigInteger(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test.",
- method = "hasNextBigInteger",
- args = {int.class}
- )
- public void test_hasNextBigIntegerI_cache() throws IOException {
- //regression for HARMONY-2063
- s = new Scanner("123 123456789123456789");
- assertTrue(s.hasNextBigInteger(16));
- assertEquals(new BigInteger("291"), s.nextBigInteger());
- assertEquals(new BigInteger("123456789123456789"), s.nextBigInteger());
-
- s = new Scanner("123456789123456789 456");
- assertTrue(s.hasNextBigInteger(16));
- assertTrue(s.hasNextBigInteger(10));
- assertEquals(new BigInteger("123456789123456789"), s.nextBigInteger());
- assertEquals(new BigInteger("456"), s.nextBigInteger());
-
- s = new Scanner("-123 -123456789123456789");
- assertTrue(s.hasNextBigInteger(8));
- assertEquals(-123, s.nextShort());
- assertEquals(new BigInteger("-123456789123456789"), s.nextBigInteger());
-
- s = new Scanner("123 456");
- assertTrue(s.hasNextBigInteger());
- s.close();
- try {
- s.nextBigInteger();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNextBigInteger()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasNextBigInteger",
- args = {}
- )
- @KnownFailure("nextBigInteger method doesn't work properly if input string has Arabic-Indic digits")
- public void test_hasNextBigInteger() throws IOException {
- s = new Scanner("123 456");
- assertTrue(s.hasNextBigInteger());
- assertEquals(new BigInteger("123"), s.nextBigInteger());
- assertTrue(s.hasNextBigInteger());
- assertEquals(new BigInteger("456"), s.nextBigInteger());
- assertFalse(s.hasNextBigInteger());
- try {
- s.nextBigInteger();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 456");
- s.useRadix(5);
- assertTrue(s.hasNextBigInteger());
- assertEquals(new BigInteger("38"), s.nextBigInteger());
- assertFalse(s.hasNextBigInteger());
- try {
- s.nextBigInteger();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.GERMANY);
- assertFalse(s.hasNextBigInteger());
- try {
- s.nextBigInteger();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.ENGLISH);
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextBigInteger());
- assertEquals(new BigInteger("23456"), s.nextBigInteger());
- assertTrue(s.hasNextBigInteger());
- assertEquals(new BigInteger("23456"), s.nextBigInteger());
-
- /*
- * ''' is used in many locales as group separator.
- */
- s = new Scanner("23'456 23'456");
- s.useLocale(Locale.GERMANY);
- assertFalse(s.hasNextBigInteger());
- try {
- s.nextBigInteger();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(new Locale("de", "CH"));
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextBigInteger());
- assertEquals(new BigInteger("23456"), s.nextBigInteger());
- assertTrue(s.hasNextBigInteger());
- assertEquals(new BigInteger("23456"), s.nextBigInteger());
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06602 1\u06662");
- assertEquals(new BigInteger("102"), s.nextBigInteger());
- s.useRadix(5);
- assertFalse(s.hasNextBigInteger());
- try {
- s.nextBigInteger();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useRadix(10);
- assertTrue(s.hasNextBigInteger());
- assertEquals(new BigInteger("162"), s.nextBigInteger());
-
- /*
- * '.' is used in many locales as group separator. The input string
- * has Arabic-Indic digits .
- */
- s = new Scanner("23.45\u0666 23.456");
- s.useLocale(Locale.CHINESE);
- assertFalse(s.hasNextBigInteger());
- try {
- s.nextBigInteger();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.GERMANY);
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextBigInteger());
- assertEquals(new BigInteger("23456"), s.nextBigInteger());
- assertTrue(s.hasNextBigInteger());
- assertEquals(new BigInteger("23456"), s.nextBigInteger());
-
- // The input string starts with zero
- s = new Scanner("03,456");
- s.useLocale(Locale.ENGLISH);
- assertFalse(s.hasNextBigInteger());
- try {
- s.nextBigInteger();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("03456");
- assertTrue(s.hasNextBigInteger());
- assertEquals(new BigInteger("3456"), s.nextBigInteger());
-
- s = new Scanner("\u06603,456");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextBigInteger());
- assertEquals(new BigInteger("3456"), s.nextBigInteger());
-
- s = new Scanner("E34");
- s.useRadix(16);
- assertTrue(s.hasNextBigInteger());
- assertEquals(new BigInteger("3636"), s.nextBigInteger());
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("12300");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextBigInteger());
- assertEquals(new BigInteger("12300"), s.nextBigInteger());
-
- s = new Scanner("123\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextBigInteger());
- assertEquals(new BigInteger("12300"), s.nextBigInteger());
-
- s = new Scanner("123\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextBigInteger());
- assertEquals(new BigInteger("12300"), s.nextBigInteger());
-
- s = new Scanner("-123");
- s.useLocale(new Locale("ar", "AE"));
- assertTrue(s.hasNextBigInteger());
- assertEquals(new BigInteger("-123"), s.nextBigInteger());
-
- s = new Scanner("-123");
- s.useLocale(new Locale("mk", "MK"));
- assertTrue(s.hasNextBigInteger());
- assertEquals(new BigInteger("-123"), s.nextBigInteger());
-
- s.close();
- try {
- s.hasNextBigInteger();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNextInt(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IllegalStateException checking missed.",
- method = "hasNextInt",
- args = {int.class}
- )
- public void test_hasNextIntI() throws IOException {
- s = new Scanner("123 456");
- assertEquals(123, s.nextInt(10));
- assertTrue(s.hasNextInt(10));
- assertEquals(456, s.nextInt(10));
- assertFalse(s.hasNextInt(10));
- try {
- s.nextInt(10);
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 456");
- assertTrue(s.hasNextInt(5));
- assertEquals(38, s.nextInt(5));
- assertFalse(s.hasNextInt(5));
- try {
- s.nextInt(5);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // If the number is out of range
- s = new Scanner("123456789123456789123456789123456789");
- assertFalse(s.hasNextInt(10));
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456");
- s.useLocale(Locale.GERMANY);
- assertFalse(s.hasNextInt(10));
- s.useLocale(Locale.ENGLISH);
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextInt(10));
- /*
- * ''' is used in many locales as group separator.
- */
- s = new Scanner("23'456");
- s.useLocale(Locale.GERMANY);
- assertFalse(s.hasNextInt(10));
- s.useLocale(new Locale("de", "CH"));
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextInt(10));
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06662");
- assertTrue(s.hasNextInt(10));
- assertFalse(s.hasNextInt(5));
-
- /*
- * '.' is used in many locales as group separator. The input string
- * has Arabic-Indic digits .
- */
- s = new Scanner("23.45\u0666");
- s.useLocale(Locale.CHINESE);
- assertFalse(s.hasNextInt(10));
- try {
- s.nextInt(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
- s.useLocale(Locale.GERMANY);
- assertTrue(s.hasNextInt(10));
-
- // The input string starts with zero
- s = new Scanner("03,456");
- s.useLocale(Locale.ENGLISH);
- assertFalse(s.hasNextInt(10));
- try {
- s.nextInt(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
-
- s = new Scanner("03456");
- assertTrue(s.hasNextInt(10));
- assertEquals(3456, s.nextInt(10));
-
- s = new Scanner("\u06603,456");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextInt(10));
- assertEquals(3456, s.nextInt(10));
-
- s = new Scanner("E3456");
- assertTrue(s.hasNextInt(16));
- assertEquals(930902, s.nextInt(16));
- // The following test case fails on RI, because RI does not support
- // letter as leading digit
- s = new Scanner("E3,456");
- s.useLocale(Locale.ENGLISH);
- if (!disableRIBugs) {
- assertTrue(s.hasNextInt(16));
- assertEquals(930902, s.nextInt(16));
-
- // If parameter radix is illegal, the following test case fails on RI
- try {
- s.hasNextInt(Character.MIN_RADIX - 1);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- }
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("12300");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextInt(10));
- assertEquals(12300, s.nextInt(10));
-
- s = new Scanner("123\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextInt(10));
- assertEquals(12300, s.nextInt(10));
-
- s = new Scanner("123\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextInt(10));
- assertEquals(12300, s.nextInt(10));
-
- /*
- * There are three types of negative prefix all in all. '' '-' '(' There
- * are three types of negative suffix all in all. '' '-' ')' '(' and ')'
- * must be used togethor. Prefix '-' and suffix '-' must be used
- * exclusively.
- */
-
- /*
- * According to Integer regular expression: Integer :: = ( [-+]? (*
- * Numeral ) ) | LocalPositivePrefix Numeral LocalPositiveSuffix |
- * LocalNegativePrefix Numeral LocalNegativeSuffix 123- should be
- * recognized by scanner with locale ar_AE, (123) shouble be recognized
- * by scanner with locale mk_MK. But this is not the case on RI.
- */
- s = new Scanner("-123 123- -123-");
- s.useLocale(new Locale("ar", "AE"));
- assertTrue(s.hasNextInt(10));
- assertEquals(-123, s.nextInt(10));
- // The following test case fails on RI
- if (!disableRIBugs) {
- assertTrue(s.hasNextInt(10));
- assertEquals(-123, s.nextInt(10));
- }
- assertFalse(s.hasNextInt(10));
- try {
- s.nextInt(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
-
- s = new Scanner("-123 123- (123)");
- s.useLocale(new Locale("mk", "MK"));
- assertTrue(s.hasNextInt(10));
- assertEquals(-123, s.nextInt(10));
- assertFalse(s.hasNextInt(10));
- try {
- s.nextInt();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
- // Skip the un-recognizable token 123-.
- assertEquals("123-", s.next());
- // The following test case fails on RI
- if (!disableRIBugs) {
- assertTrue(s.hasNextInt(10));
- assertEquals(-123, s.nextInt(10));
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNextInt(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test",
- method = "hasNextInt",
- args = {int.class}
- )
- public void test_hasNextIntI_cache() throws IOException {
- //regression for HARMONY-2063
- s = new Scanner("123 456");
- assertTrue(s.hasNextInt(16));
- assertEquals(291, s.nextInt(10));
- assertEquals(456, s.nextInt());
-
- s = new Scanner("123 456");
- assertTrue(s.hasNextInt(16));
- assertTrue(s.hasNextInt(8));
- assertEquals(83, s.nextInt());
- assertEquals(456, s.nextInt());
-
- s = new Scanner("-123 -456 -789");
- assertTrue(s.hasNextInt(8));
- assertEquals(-123, s.nextShort());
- assertEquals(-456, s.nextInt());
- assertTrue(s.hasNextShort(16));
- assertEquals(-789, s.nextInt());
-
- s = new Scanner("123 456");
- assertTrue(s.hasNextInt());
- s.close();
- try {
- s.nextInt();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- }
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNextInt()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasNextInt",
- args = {}
- )
- public void test_hasNextInt() throws IOException {
- s = new Scanner("123 456");
- assertTrue(s.hasNextInt());
- assertEquals(123, s.nextInt());
- assertEquals(456, s.nextInt());
- assertFalse(s.hasNextInt());
- try {
- s.nextInt();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 456");
- s.useRadix(5);
- assertTrue(s.hasNextInt());
- assertEquals(38, s.nextInt());
- assertFalse(s.hasNextInt());
- try {
- s.nextInt();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // If the number is out of range
- s = new Scanner("123456789123456789123456789123456789");
- assertFalse(s.hasNextInt());
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456");
- s.useLocale(Locale.GERMANY);
- assertFalse(s.hasNextInt());
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextInt());
-
- /*
- * ''' is used in many locales as group separator.
- */
- s = new Scanner("23'456");
- s.useLocale(Locale.GERMANY);
- assertFalse(s.hasNextInt());
- s.useLocale(new Locale("de", "CH"));
- assertTrue(s.hasNextInt());
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06662");
- s.useRadix(5);
- assertFalse(s.hasNextInt());
-
- /*
- * '.' is used in many locales as group separator. The input string
- * has Arabic-Indic digits .
- */
- s = new Scanner("23.45\u0666");
- s.useLocale(Locale.CHINESE);
- assertFalse(s.hasNextInt());
- s.useLocale(Locale.GERMANY);
- assertTrue(s.hasNextInt());
-
- // The input string starts with zero
- s = new Scanner("03,456");
- s.useLocale(Locale.ENGLISH);
- assertFalse(s.hasNextInt());
- try {
- s.nextInt();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
-
- s = new Scanner("03456");
- assertTrue(s.hasNextInt());
- assertEquals(3456, s.nextInt());
-
- s = new Scanner("\u06603,456");
- s.useLocale(Locale.ENGLISH);
- assertEquals(3456, s.nextInt());
-
- s = new Scanner("E3456");
- s.useRadix(16);
- assertTrue(s.hasNextInt());
- assertEquals(930902, s.nextInt());
-
- // The following test case fails on RI, because RI does not support
- // letter as leading digit
- s = new Scanner("E3,456");
- s.useLocale(Locale.ENGLISH);
- s.useRadix(16);
- if (!disableRIBugs) {
- assertTrue(s.hasNextInt());
- assertEquals(930902, s.nextInt());
- }
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("12300");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextInt());
- assertEquals(12300, s.nextInt());
-
- s = new Scanner("123\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextInt());
- assertEquals(12300, s.nextInt());
-
- s = new Scanner("123\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextInt());
- assertEquals(12300, s.nextInt());
-
- /*
- * There are three types of negative prefix all in all. '' '-' '(' There
- * are three types of negative suffix all in all. '' '-' ')' '(' and ')'
- * must be used togethor. Prefix '-' and suffix '-' must be used
- * exclusively.
- */
-
- /*
- * According to Integer regular expression: Integer :: = ( [-+]? (*
- * Numeral ) ) | LocalPositivePrefix Numeral LocalPositiveSuffix |
- * LocalNegativePrefix Numeral LocalNegativeSuffix 123- should be
- * recognized by scanner with locale ar_AE, (123) shouble be recognized
- * by scanner with locale mk_MK. But this is not the case on RI.
- */
- s = new Scanner("-123 123- -123-");
- s.useLocale(new Locale("ar", "AE"));
- assertTrue(s.hasNextInt());
- assertEquals(-123, s.nextInt());
- // The following test case fails on RI
- if (!disableRIBugs) {
- assertTrue(s.hasNextInt());
- assertEquals(-123, s.nextInt());
- }
- assertFalse(s.hasNextInt());
- try {
- s.nextInt();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
-
- s = new Scanner("-123 123- (123)");
- s.useLocale(new Locale("mk", "MK"));
- assertTrue(s.hasNextInt());
- assertEquals(-123, s.nextInt());
- try {
- s.nextInt();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // expected
- }
- // Skip the un-recognizable token 123-.
- assertEquals("123-", s.next());
- // The following test case fails on RI
- if (!disableRIBugs) {
- assertTrue(s.hasNextInt());
- assertEquals(-123, s.nextInt());
- }
-
- s.close();
- try {
- s.hasNextInt();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNextFloat()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasNextFloat",
- args = {}
- )
- public void test_hasNextFloat() throws IOException {
- s = new Scanner("123 45\u0666. 123.4 .123 ");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextFloat());
- assertEquals((float)123.0, s.nextFloat());
- assertTrue(s.hasNextFloat());
- assertEquals((float)456.0, s.nextFloat());
- assertTrue(s.hasNextFloat());
- assertEquals((float)123.4, s.nextFloat());
- assertTrue(s.hasNextFloat());
- assertEquals((float)0.123, s.nextFloat());
- assertFalse(s.hasNextFloat());
- try {
- s.nextFloat();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- s = new Scanner("+123.4 -456.7 123,456.789 0.1\u06623,4");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextFloat());
- assertEquals((float)123.4, s.nextFloat());
- assertTrue(s.hasNextFloat());
- assertEquals((float)-456.7, s.nextFloat());
- assertTrue(s.hasNextFloat());
- assertEquals((float)123456.789, s.nextFloat());
- assertFalse(s.hasNextFloat());
- try {
- s.nextFloat();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // Scientific notation
- s = new Scanner("+123.4E10 -456.7e+12 123,456.789E-10");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextFloat());
- assertEquals((float)1.234E12, s.nextFloat());
- assertTrue(s.hasNextFloat());
- assertEquals((float)-4.567E14, s.nextFloat());
- assertTrue(s.hasNextFloat());
- assertEquals((float)1.23456789E-5, s.nextFloat());
-
- s = new Scanner("NaN Infinity -Infinity");
- assertTrue(s.hasNextFloat());
- assertEquals(Float.NaN, s.nextFloat());
- assertTrue(s.hasNextFloat());
- assertEquals(Float.POSITIVE_INFINITY, s.nextFloat());
- assertTrue(s.hasNextFloat());
- assertEquals(Float.NEGATIVE_INFINITY, s.nextFloat());
-
- String str=String.valueOf(Float.MAX_VALUE*2);
- s=new Scanner(str);
- assertTrue(s.hasNextFloat());
- assertEquals(Float.POSITIVE_INFINITY,s.nextFloat());
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextFloat());
- assertEquals((float)23456.0, s.nextFloat());
- s.useLocale(Locale.GERMANY);
- assertTrue(s.hasNextFloat());
- assertEquals((float)23.456, s.nextFloat());
-
- s = new Scanner("23.456 23.456");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextFloat());
- assertEquals((float)23.456, s.nextFloat());
- s.useLocale(Locale.GERMANY);
- assertTrue(s.hasNextFloat());
- assertEquals((float)23456.0, s.nextFloat());
-
- s = new Scanner("23,456.7 23.456,7");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextFloat());
- assertEquals((float)23456.7, s.nextFloat());
- s.useLocale(Locale.GERMANY);
- assertTrue(s.hasNextFloat());
- assertEquals((float)23456.7, s.nextFloat());
-
- s = new Scanner("-123.4 123.4- -123.4-");
- s.useLocale(new Locale("ar", "AE"));
- assertTrue(s.hasNextFloat());
- assertEquals((float)-123.4, s.nextFloat());
- //The following test case fails on RI
- if (!disableRIBugs) {
- assertTrue(s.hasNextFloat());
- assertEquals((float)-123.4, s.nextFloat());
- }
- try {
- s.nextFloat();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("(123) 123- -123");
- s.useLocale(new Locale("mk", "MK"));
- if (!disableRIBugs) {
- assertTrue(s.hasNextFloat());
- assertEquals((float)-123.0, s.nextFloat());
- }
- assertFalse(s.hasNextFloat());
- try {
- s.nextFloat();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- // Skip the un-recognizable token 123-.
- if (!disableRIBugs) {
- assertEquals("123-", s.next());
- assertTrue(s.hasNextFloat());
- assertEquals((float)-123.0, s.nextFloat());
- }
-
- s = new Scanner("+123.4 -456.7");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextFloat());
- s.close();
- try{
- s.nextFloat();
- fail("Should throw IllegalStateException");
- }catch(IllegalStateException e){
- //expected
- }
-
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNextShort(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IllegalStateException checking missed.",
- method = "hasNextShort",
- args = {int.class}
- )
- public void test_hasNextShortI() throws IOException {
- s = new Scanner("123 456");
- assertTrue(s.hasNextShort(10));
- assertEquals(123, s.nextShort(10));
- assertTrue(s.hasNextShort(10));
- assertEquals(456, s.nextShort(10));
- assertFalse(s.hasNextShort(10));
- try {
- s.nextShort(10);
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 456");
- assertTrue(s.hasNextShort(5));
- assertEquals(38, s.nextShort(5));
- assertFalse(s.hasNextShort(5));
- try {
- s.nextShort(5);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // If the number is out of range
- s = new Scanner("123456789");
- assertFalse(s.hasNextShort(10));
- try {
- s.nextShort(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.GERMANY);
- assertFalse(s.hasNextShort(10));
- try {
- s.nextShort(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.ENGLISH);
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextShort(10));
- assertEquals(23456, s.nextInt(10));
- assertTrue(s.hasNextShort(10));
- assertEquals(23456, s.nextInt(10));
-
- /*
- * ''' is used in many locales as group separator.
- */
- s = new Scanner("23'456 23'456");
- s.useLocale(Locale.GERMANY);
- assertFalse(s.hasNextShort(10));
- try {
- s.nextShort(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(new Locale("de", "CH"));
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextShort(10));
- assertEquals(23456, s.nextShort(10));
- assertTrue(s.hasNextShort(10));
- assertEquals(23456, s.nextShort(10));
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06602 1\u06662");
- assertTrue(s.hasNextShort(10));
- assertEquals(102, s.nextShort(10));
- assertFalse(s.hasNextShort(5));
- try {
- s.nextShort(5);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- assertTrue(s.hasNextShort(10));
- assertEquals(162, s.nextShort(10));
-
- /*
- * '.' is used in many locales as group separator. The input string
- * has Arabic-Indic digits .
- */
- s = new Scanner("23.45\u0666 23.456");
- s.useLocale(Locale.CHINESE);
- assertFalse(s.hasNextShort(10));
- try {
- s.nextShort(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.GERMANY);
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextShort(10));
- assertEquals(23456, s.nextShort(10));
- assertTrue(s.hasNextShort(10));
- assertEquals(23456, s.nextShort(10));
-
- // The input string starts with zero
- s = new Scanner("03,456");
- s.useLocale(Locale.ENGLISH);
- assertFalse(s.hasNextShort(10));
- try {
- s.nextShort(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("03456");
- assertTrue(s.hasNextShort(10));
- assertEquals(3456, s.nextShort(10));
-
- s = new Scanner("\u06603,456");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextShort(10));
- assertEquals(3456, s.nextShort(10));
-
- s = new Scanner("E34");
- assertTrue(s.hasNextShort(16));
- assertEquals(3636, s.nextShort(16));
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("12300");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextShort(10));
- assertEquals(12300, s.nextShort(10));
-
- s = new Scanner("123\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextShort(10));
- assertEquals(12300, s.nextShort(10));
-
- s = new Scanner("123\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextShort(10));
- assertEquals(12300, s.nextShort(10));
-
- s = new Scanner("-123");
- s.useLocale(new Locale("ar", "AE"));
- assertTrue(s.hasNextShort(10));
- assertEquals(-123, s.nextShort(10));
-
-
- s = new Scanner("-123");
- s.useLocale(new Locale("mk", "MK"));
- assertTrue(s.hasNextShort(10));
- assertEquals(-123, s.nextShort(10));
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNextShort()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasNextShort",
- args = {}
- )
- public void test_hasNextShort() throws IOException {
- s = new Scanner("123 456");
- assertTrue(s.hasNextShort());
- assertEquals(123, s.nextShort());
- assertTrue(s.hasNextShort());
- assertEquals(456, s.nextShort());
- assertFalse(s.hasNextShort());
- try {
- s.nextShort();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 456");
- s.useRadix(5);
- assertTrue(s.hasNextShort());
- assertEquals(38, s.nextShort());
- assertFalse(s.hasNextShort());
- try {
- s.nextShort();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // If the number is out of range
- s = new Scanner("123456789");
- assertFalse(s.hasNextShort());
- try {
- s.nextShort();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.GERMANY);
- assertFalse(s.hasNextShort());
- try {
- s.nextShort();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.ENGLISH);
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextShort());
- assertEquals(23456, s.nextShort());
- assertTrue(s.hasNextShort());
- assertEquals(23456, s.nextShort());
-
- /*
- * ''' is used in many locales as group separator.
- */
- s = new Scanner("23'456 23'456");
- s.useLocale(Locale.GERMANY);
- assertFalse(s.hasNextShort());
- try {
- s.nextShort();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(new Locale("de", "CH"));
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextShort());
- assertEquals(23456, s.nextShort());
- assertTrue(s.hasNextShort());
- assertEquals(23456, s.nextShort());
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06602 1\u06662");
- assertEquals(102, s.nextShort());
- s.useRadix(5);
- assertFalse(s.hasNextShort());
- try {
- s.nextShort();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useRadix(10);
- assertTrue(s.hasNextShort());
- assertEquals(162, s.nextShort());
-
- /*
- * '.' is used in many locales as group separator. The input string
- * has Arabic-Indic digits .
- */
- s = new Scanner("23.45\u0666 23.456");
- s.useLocale(Locale.CHINESE);
- assertFalse(s.hasNextShort());
- try {
- s.nextShort();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.GERMANY);
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextShort());
- assertEquals(23456, s.nextShort());
- assertTrue(s.hasNextShort());
- assertEquals(23456, s.nextShort());
-
- // The input string starts with zero
- s = new Scanner("03,456");
- s.useLocale(Locale.ENGLISH);
- assertFalse(s.hasNextShort());
- try {
- s.nextShort();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("03456");
- assertTrue(s.hasNextShort());
- assertEquals(3456, s.nextShort());
-
- s = new Scanner("\u06603,456");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextShort());
- assertEquals(3456, s.nextShort());
-
- s = new Scanner("E34");
- s.useRadix(16);
- assertTrue(s.hasNextShort());
- assertEquals(3636, s.nextShort());
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("12300");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextShort());
- assertEquals(12300, s.nextShort());
-
- s = new Scanner("123\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextShort());
- assertEquals(12300, s.nextShort());
-
- s = new Scanner("123\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextShort());
- assertEquals(12300, s.nextShort());
-
- s = new Scanner("-123");
- s.useLocale(new Locale("ar", "AE"));
- assertTrue(s.hasNextShort());
- assertEquals(-123, s.nextShort());
-
- s = new Scanner("-123");
- s.useLocale(new Locale("mk", "MK"));
- assertTrue(s.hasNextShort());
- assertEquals(-123, s.nextShort());
-
- s.close();
- try {
- s.hasNextShort();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNextShort(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test.",
- method = "hasNextShort",
- args = {int.class}
- )
- public void test_hasNextShortI_cache() throws IOException {
- //regression for HARMONY-2063
- s = new Scanner("123 456");
- assertTrue(s.hasNextShort(16));
- assertEquals(291, s.nextShort());
- assertEquals(456, s.nextShort());
-
- s = new Scanner("123 456");
- assertTrue(s.hasNextShort(16));
- assertTrue(s.hasNextShort(8));
- assertEquals(83, s.nextShort());
- assertEquals(456, s.nextShort());
-
- s = new Scanner("-123 -456 -789");
- assertTrue(s.hasNextShort(8));
- assertEquals(-123, s.nextInt());
- assertEquals(-456, s.nextShort());
- assertTrue(s.hasNextInt(16));
- assertEquals(-789, s.nextShort());
-
- s = new Scanner("123 456");
- assertTrue(s.hasNextShort());
- s.close();
- try {
- s.nextShort();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNextLong(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IllegalStateException checking missed.",
- method = "hasNextLong",
- args = {int.class}
- )
- public void test_hasNextLongI() throws IOException {
- s = new Scanner("123 456");
- assertTrue(s.hasNextLong(10));
- assertEquals(123, s.nextLong(10));
- assertTrue(s.hasNextLong(10));
- assertEquals(456, s.nextLong(10));
- assertFalse(s.hasNextLong(10));
- try {
- s.nextLong(10);
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 456");
- assertTrue(s.hasNextLong(5));
- assertEquals(38, s.nextLong(5));
- assertFalse(s.hasNextLong(5));
- try {
- s.nextLong(5);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // If the number is out of range
- s = new Scanner("123456789123456789123456789123456789");
- assertFalse(s.hasNextLong(10));
- try {
- s.nextLong(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.GERMANY);
- assertFalse(s.hasNextShort(10));
- try {
- s.nextLong(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.ENGLISH);
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextLong(10));
- assertEquals(23456, s.nextLong(10));
- assertTrue(s.hasNextLong(10));
- assertEquals(23456, s.nextLong(10));
-
- /*
- * ''' is used in many locales as group separator.
- */
- s = new Scanner("23'456 23'456");
- s.useLocale(Locale.GERMANY);
- assertFalse(s.hasNextLong(10));
- try {
- s.nextLong(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(new Locale("de", "CH"));
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextLong(10));
- assertEquals(23456, s.nextLong(10));
- assertTrue(s.hasNextLong(10));
- assertEquals(23456, s.nextLong(10));
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06602 1\u06662");
- assertTrue(s.hasNextLong(10));
- assertEquals(102, s.nextLong(10));
- assertFalse(s.hasNextLong(5));
- try {
- s.nextLong(5);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- assertTrue(s.hasNextLong(10));
- assertEquals(162, s.nextLong(10));
-
- /*
- * '.' is used in many locales as group separator. The input string
- * has Arabic-Indic digits .
- */
- s = new Scanner("23.45\u0666 23.456");
- s.useLocale(Locale.CHINESE);
- assertFalse(s.hasNextLong(10));
- try {
- s.nextLong(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.GERMANY);
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextLong(10));
- assertEquals(23456, s.nextLong(10));
- assertTrue(s.hasNextLong(10));
- assertEquals(23456, s.nextLong(10));
-
- // The input string starts with zero
- s = new Scanner("03,456");
- s.useLocale(Locale.ENGLISH);
- assertFalse(s.hasNextLong(10));
- try {
- s.nextLong(10);
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("03456");
- assertTrue(s.hasNextLong(10));
- assertEquals(3456, s.nextLong(10));
-
- s = new Scanner("\u06603,456");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextLong(10));
- assertEquals(3456, s.nextLong(10));
-
- s = new Scanner("E34");
- assertTrue(s.hasNextLong(16));
- assertEquals(3636, s.nextLong(16));
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("12300");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextLong(10));
- assertEquals(12300, s.nextLong(10));
-
- s = new Scanner("123\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextLong(10));
- assertEquals(12300, s.nextLong(10));
-
- s = new Scanner("123\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextLong(10));
- assertEquals(12300, s.nextLong(10));
-
- s = new Scanner("-123");
- s.useLocale(new Locale("ar", "AE"));
- assertTrue(s.hasNextLong(10));
- assertEquals(-123, s.nextLong(10));
-
-
- s = new Scanner("-123");
- s.useLocale(new Locale("mk", "MK"));
- assertTrue(s.hasNextLong(10));
- assertEquals(-123, s.nextLong(10));
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNextLong(int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test.",
- method = "hasNextLong",
- args = {int.class}
- )
- public void test_hasNextLongI_cache() throws IOException {
- //regression for HARMONY-2063
- s = new Scanner("123 456");
- assertTrue(s.hasNextLong(16));
- assertEquals(291, s.nextLong());
- assertEquals(456, s.nextLong());
-
- s = new Scanner("123 456");
- assertTrue(s.hasNextLong(16));
- assertTrue(s.hasNextLong(8));
- assertEquals(83, s.nextLong());
- assertEquals(456, s.nextLong());
-
- s = new Scanner("-123 -456 -789");
- assertTrue(s.hasNextLong(8));
- assertEquals(-123, s.nextInt());
- assertEquals(-456, s.nextLong());
- assertTrue(s.hasNextShort(16));
- assertEquals(-789, s.nextLong());
-
- s = new Scanner("123 456");
- assertTrue(s.hasNextLong());
- s.close();
- try {
- s.nextLong();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNextLong()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasNextLong",
- args = {}
- )
- public void test_hasNextLong() throws IOException {
- s = new Scanner("123 456");
- assertTrue(s.hasNextLong());
- assertEquals(123, s.nextLong());
- assertTrue(s.hasNextLong());
- assertEquals(456, s.nextLong());
- assertFalse(s.hasNextLong());
- try {
- s.nextLong();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- // If the radix is different from 10
- s = new Scanner("123 456");
- s.useRadix(5);
- assertTrue(s.hasNextLong());
- assertEquals(38, s.nextLong());
- assertFalse(s.hasNextLong());
- try {
- s.nextLong();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // If the number is out of range
- s = new Scanner("123456789123456789123456789123456789");
- assertFalse(s.hasNextLong());
- try {
- s.nextLong();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.GERMANY);
- assertFalse(s.hasNextLong());
- try {
- s.nextLong();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.ENGLISH);
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextLong());
- assertEquals(23456, s.nextLong());
- assertTrue(s.hasNextLong());
- assertEquals(23456, s.nextLong());
-
- /*
- * ''' is used in many locales as group separator.
- */
- s = new Scanner("23'456 23'456");
- s.useLocale(Locale.GERMANY);
- assertFalse(s.hasNextLong());
- try {
- s.nextLong();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(new Locale("de", "CH"));
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextLong());
- assertEquals(23456, s.nextLong());
- assertTrue(s.hasNextLong());
- assertEquals(23456, s.nextLong());
-
- /*
- * The input string has Arabic-Indic digits.
- */
- s = new Scanner("1\u06602 1\u06662");
- assertEquals(102, s.nextLong());
- s.useRadix(5);
- assertFalse(s.hasNextLong());
- try {
- s.nextLong();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useRadix(10);
- assertTrue(s.hasNextLong());
- assertEquals(162, s.nextLong());
-
- /*
- * '.' is used in many locales as group separator. The input string
- * has Arabic-Indic digits .
- */
- s = new Scanner("23.45\u0666 23.456");
- s.useLocale(Locale.CHINESE);
- assertFalse(s.hasNextLong());
- try {
- s.nextLong();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
- s.useLocale(Locale.GERMANY);
- // If exception is thrown out, input will not be advanced.
- assertTrue(s.hasNextLong());
- assertEquals(23456, s.nextLong());
- assertTrue(s.hasNextLong());
- assertEquals(23456, s.nextLong());
-
- // The input string starts with zero
- s = new Scanner("03,456");
- s.useLocale(Locale.ENGLISH);
- assertFalse(s.hasNextLong());
- try {
- s.nextLong();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- s = new Scanner("03456");
- assertTrue(s.hasNextLong());
- assertEquals(3456, s.nextLong());
-
- s = new Scanner("\u06603,456");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextLong());
- assertEquals(3456, s.nextLong());
-
- s = new Scanner("E34");
- s.useRadix(16);
- assertTrue(s.hasNextLong());
- assertEquals(3636, s.nextLong());
-
- /*
- * There are 3 types of zero digit in all locales, '0' '\u0966' '\u0e50'
- * respectively, but they are not differentiated.
- */
- s = new Scanner("12300");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextLong());
- assertEquals(12300, s.nextLong());
-
- s = new Scanner("123\u0966\u0966");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextLong());
- assertEquals(12300, s.nextLong());
-
- s = new Scanner("123\u0e50\u0e50");
- s.useLocale(Locale.CHINESE);
- assertTrue(s.hasNextLong());
- assertEquals(12300, s.nextLong());
-
- s = new Scanner("-123");
- s.useLocale(new Locale("ar", "AE"));
- assertTrue(s.hasNextLong());
- assertEquals(-123, s.nextLong());
-
- s = new Scanner("-123");
- s.useLocale(new Locale("mk", "MK"));
- assertTrue(s.hasNextLong());
- assertEquals(-123, s.nextLong());
-
- s.close();
- try {
- s.hasNextLong();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#nextDouble()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasNextDouble",
- args = {}
- )
- public void test_hasNextDouble() throws IOException {
- s = new Scanner("123 45\u0666. 123.4 .123 ");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextDouble());
- assertEquals(123.0, s.nextDouble());
- assertTrue(s.hasNextDouble());
- assertEquals(456.0, s.nextDouble());
- assertTrue(s.hasNextDouble());
- assertEquals(123.4, s.nextDouble());
- assertTrue(s.hasNextDouble());
- assertEquals(0.123, s.nextDouble());
- assertFalse(s.hasNextDouble());
- try {
- s.nextDouble();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- s = new Scanner("+123.4 -456.7 123,456.789 0.1\u06623,4");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextDouble());
- assertEquals(123.4, s.nextDouble());
- assertTrue(s.hasNextDouble());
- assertEquals(-456.7, s.nextDouble());
- assertTrue(s.hasNextDouble());
- assertEquals(123456.789, s.nextDouble());
- assertFalse(s.hasNextDouble());
- try {
- s.nextDouble();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // Scientific notation
- s = new Scanner("+123.4E10 -456.7e+12 123,456.789E-10");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextDouble());
- assertEquals(1.234E12, s.nextDouble());
- assertTrue(s.hasNextDouble());
- assertEquals(-4.567E14, s.nextDouble());
- assertTrue(s.hasNextDouble());
- assertEquals(1.23456789E-5, s.nextDouble());
-
- s = new Scanner("NaN Infinity -Infinity");
- assertTrue(s.hasNextDouble());
- assertEquals(Double.NaN, s.nextDouble());
- assertTrue(s.hasNextDouble());
- assertEquals(Double.POSITIVE_INFINITY, s.nextDouble());
- assertTrue(s.hasNextDouble());
- assertEquals(Double.NEGATIVE_INFINITY, s.nextDouble());
-
- String str=String.valueOf(Double.MAX_VALUE*2);
- s=new Scanner(str);
- assertTrue(s.hasNextDouble());
- assertEquals(Double.POSITIVE_INFINITY,s.nextDouble());
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextDouble());
- assertEquals(23456.0, s.nextDouble());
- s.useLocale(Locale.GERMANY);
- assertTrue(s.hasNextDouble());
- assertEquals(23.456, s.nextDouble());
-
- s = new Scanner("23.456 23.456");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextDouble());
- assertEquals(23.456, s.nextDouble());
- s.useLocale(Locale.GERMANY);
- assertTrue(s.hasNextDouble());
- assertEquals(23456.0, s.nextDouble());
-
- s = new Scanner("23,456.7 23.456,7");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextDouble());
- assertEquals(23456.7, s.nextDouble());
- s.useLocale(Locale.GERMANY);
- assertTrue(s.hasNextDouble());
- assertEquals(23456.7, s.nextDouble());
-
- s = new Scanner("-123.4");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextDouble());
- assertEquals(-123.4, s.nextDouble());
-
- s = new Scanner("+123.4 -456.7");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextDouble());
- s.close();
- try{
- s.nextDouble();
- fail("Should throw IllegalStateException");
- }catch(IllegalStateException e){
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#hasNextBigDecimal()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasNextBigDecimal",
- args = {}
- )
- public void test_hasNextBigDecimal() throws IOException {
- s = new Scanner("123 45\u0666. 123.4 .123 ");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextBigDecimal());
- assertEquals(new BigDecimal("123"), s.nextBigDecimal());
- assertTrue(s.hasNextBigDecimal());
- assertEquals(new BigDecimal("456"), s.nextBigDecimal());
- assertTrue(s.hasNextBigDecimal());
- assertEquals(new BigDecimal("123.4"), s.nextBigDecimal());
- assertTrue(s.hasNextBigDecimal());
- assertEquals(new BigDecimal("0.123"), s.nextBigDecimal());
- assertFalse(s.hasNextBigDecimal());
- try {
- s.nextBigDecimal();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- s = new Scanner("+123.4 -456.7 123,456.789 0.1\u06623,4");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextBigDecimal());
- assertEquals(new BigDecimal("123.4"), s.nextBigDecimal());
- assertTrue(s.hasNextBigDecimal());
- assertEquals(new BigDecimal("-456.7"), s.nextBigDecimal());
- assertTrue(s.hasNextBigDecimal());
- assertEquals(new BigDecimal("123456.789"), s.nextBigDecimal());
- assertFalse(s.hasNextBigDecimal());
- try {
- s.nextBigDecimal();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // Scientific notation
- s = new Scanner("+123.4E10 -456.7e+12 123,456.789E-10");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextBigDecimal());
- assertEquals(new BigDecimal("1.234E12"), s.nextBigDecimal());
- assertTrue(s.hasNextBigDecimal());
- assertEquals(new BigDecimal("-4.567E14"), s.nextBigDecimal());
- assertTrue(s.hasNextBigDecimal());
- assertEquals(new BigDecimal("1.23456789E-5"), s.nextBigDecimal());
-
- s = new Scanner("NaN");
- assertFalse(s.hasNextBigDecimal());
- try {
- s.nextBigDecimal();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextBigDecimal());
- assertEquals(new BigDecimal("23456"), s.nextBigDecimal());
- s.useLocale(Locale.GERMANY);
- assertTrue(s.hasNextBigDecimal());
- assertEquals(new BigDecimal("23.456"), s.nextBigDecimal());
-
- s = new Scanner("23.456 23.456");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextBigDecimal());
- assertEquals(new BigDecimal("23.456"), s.nextBigDecimal());
- s.useLocale(Locale.GERMANY);
- assertTrue(s.hasNextBigDecimal());
- assertEquals(new BigDecimal("23456"), s.nextBigDecimal());
-
- s = new Scanner("23,456.7");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextBigDecimal());
- assertEquals(new BigDecimal("23456.7"), s.nextBigDecimal());
-
- s = new Scanner("-123.4");
- s.useLocale(Locale.ENGLISH);
- assertTrue(s.hasNextBigDecimal());
- assertEquals(new BigDecimal("-123.4"), s.nextBigDecimal());
-
- s.close();
- try {
- s.hasNextBigDecimal();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- private static class MockStringReader extends StringReader {
-
- public MockStringReader(String param) {
- super(param);
- }
-
- public int read(CharBuffer target) throws IOException {
- target.append('t');
- target.append('e');
- target.append('s');
- target.append('t');
- throw new IOException();
- }
-
- }
-
- private static class MockStringReader2Read extends StringReader {
- private int timesRead = 1;
-
- public MockStringReader2Read(String param) {
- super(param);
- }
-
- public int read(CharBuffer target) throws IOException {
- if (timesRead == 1) {
- target.append('1');
- target.append('2');
- target.append('3');
- timesRead++;
- return 3;
- } else if (timesRead == 2) {
- target.append('t');
- timesRead++;
- return 1;
- } else {
- throw new IOException();
- }
- }
-
- }
-
- /**
- * @tests java.util.Scanner#findWithinHorizon(Pattern, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "findWithinHorizon",
- args = {java.util.regex.Pattern.class, int.class}
- )
- @KnownFailure("findWithinHorizon method doesn't work properly")
- public void test_findWithinHorizon_LPatternI(){
-
- // This method searches through the input up to the specified search
- // horizon(exclusive).
- s = new Scanner("123test");
- String result = s.findWithinHorizon(Pattern.compile("\\p{Lower}"), 5);
- assertEquals("t", result);
- MatchResult mresult = s.match();
- assertEquals(3, mresult.start());
- assertEquals(4, mresult.end());
-
- s = new Scanner("12345test1234test next");
- /*
- * If the pattern is found the scanner advances past the input that
- * matched and returns the string that matched the pattern.
- */
- result = s.findWithinHorizon(Pattern.compile("\\p{Digit}+"), 2);
- assertEquals("12", result);
- mresult = s.match();
- assertEquals(0, mresult.start());
- assertEquals(2, mresult.end());
- // Postion is now pointing at the bar. "12|345test1234test next"
-
- result = s.findWithinHorizon(Pattern.compile("\\p{Digit}+"), 6);
- assertEquals("345", result);
-
- mresult = s.match();
- assertEquals(2, mresult.start());
- assertEquals(5, mresult.end());
- // Postion is now pointing at the bar. "12345|test1234test next"
-
- // If no such pattern is detected then the null is returned and the
- // scanner's position remains unchanged.
- result = s.findWithinHorizon(Pattern.compile("\\p{Digit}+"), 3);
- assertNull(result);
-
- try {
- s.match();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- assertEquals("345", mresult.group());
- assertEquals(2, mresult.start());
- assertEquals(5, mresult.end());
- // Postion is now still pointing at the bar. "12345|test1234test next"
-
- // If horizon is 0, then the horizon is ignored and this method
- // continues to search through the input looking for the specified
- // pattern without bound.
- result = s.findWithinHorizon(Pattern.compile("\\p{Digit}+"), 0);
- mresult = s.match();
- assertEquals(9, mresult.start());
- assertEquals(13, mresult.end());
- // Postion is now pointing at the bar. "12345test1234|test next"
-
- assertEquals("test", s.next());
- mresult = s.match();
- assertEquals(13, mresult.start());
- assertEquals(17, mresult.end());
-
- assertEquals("next", s.next());
- mresult = s.match();
- assertEquals(18, mresult.start());
- assertEquals(22, mresult.end());
-
- try {
- s.findWithinHorizon((Pattern) null, -1);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- s.findWithinHorizon(Pattern.compile("\\p{Digit}+"), -1);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- s.close();
- try {
- s.findWithinHorizon((Pattern) null, -1);
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- s = new Scanner("test");
- result = s.findWithinHorizon(Pattern.compile("\\w+"), 10);
- assertEquals("test", result);
-
- s = new Scanner("aa\n\rb");
- String patternStr = "^(a)$";
- result = s.findWithinHorizon(Pattern.compile("a"), 5);
- assertEquals("a", result);
- mresult = s.match();
- assertEquals(0, mresult.start());
- assertEquals(1, mresult.end());
-
- result = s.findWithinHorizon(Pattern.compile(patternStr,
- Pattern.MULTILINE), 5);
- assertNull(result);
-
- try {
- mresult = s.match();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- s = new Scanner("");
- result = s.findWithinHorizon(Pattern.compile("^"), 0);
- assertEquals("", result);
- MatchResult matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(0, matchResult.end());
-
- result = s.findWithinHorizon(Pattern.compile("$"), 0);
- assertEquals("", result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(0, matchResult.end());
-
- s = new Scanner("1 fish 2 fish red fish blue fish");
- result = s.findWithinHorizon(Pattern
- .compile("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)"), 10);
- assertNull(result);
-
- try {
- mresult = s.match();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- assertEquals(0, mresult.groupCount());
-
- result = s.findWithinHorizon(Pattern
- .compile("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)"), 100);
- assertEquals("1 fish 2 fish red fish blue", result);
- mresult = s.match();
- assertEquals(4, mresult.groupCount());
- assertEquals("1", mresult.group(1));
- assertEquals("2", mresult.group(2));
- assertEquals("red", mresult.group(3));
- assertEquals("blue", mresult.group(4));
-
- s = new Scanner("test");
- s.close();
- try {
- s.findWithinHorizon(Pattern.compile("test"), 1);
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- s = new Scanner("word1 WorD2 ");
- s.close();
- try {
- s.findWithinHorizon(Pattern.compile("\\d+"), 10);
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- s = new Scanner("word1 WorD2 wOrd3 ");
- Pattern pattern = Pattern.compile("\\d+");
- assertEquals("1", s.findWithinHorizon(pattern, 10));
- assertEquals("WorD2", s.next());
- assertEquals("3", s.findWithinHorizon(pattern, 15));
-
- // Regression test
- s = new Scanner(new MockStringReader("MockStringReader"));
- pattern = Pattern.compile("test");
- result = s.findWithinHorizon(pattern, 10);
- assertEquals("test", result);
-
- // Test the situation when input length is longer than buffer size.
- StringBuilder stringBuilder = new StringBuilder();
- for (int i = 0; i < 1026; i++) {
- stringBuilder.append('a');
- }
- s = new Scanner(stringBuilder.toString());
- pattern = Pattern.compile("\\p{Lower}+");
- result = s.findWithinHorizon(pattern, 1026);
- assertEquals(stringBuilder.toString(), result);
-
- // Test the situation when input length is longer than buffer size and
- // set horizon to buffer size.
- stringBuilder = new StringBuilder();
- for (int i = 0; i < 1026; i++) {
- stringBuilder.append('a');
- }
- s = new Scanner(stringBuilder.toString());
- pattern = Pattern.compile("\\p{Lower}+");
- result = s.findWithinHorizon(pattern, 1022);
- assertEquals(1022, result.length());
- assertEquals(stringBuilder.subSequence(0, 1022), result);
-
- // Test the situation, under which pattern is clipped by buffer.
- stringBuilder = new StringBuilder();
- for (int i = 0; i < 1022; i++) {
- stringBuilder.append(' ');
- }
- stringBuilder.append("bbc");
- assertEquals(1025, stringBuilder.length());
- s = new Scanner(stringBuilder.toString());
- pattern = Pattern.compile("bbc");
- result = s.findWithinHorizon(pattern, 1025);
- assertEquals(3, result.length());
- assertEquals(stringBuilder.subSequence(1022, 1025), result);
-
- stringBuilder = new StringBuilder();
- for (int i = 0; i < 1026; i++) {
- stringBuilder.append('a');
- }
- s = new Scanner(stringBuilder.toString());
- pattern = Pattern.compile("\\p{Lower}+");
- result = s.findWithinHorizon(pattern, 0);
- assertEquals(stringBuilder.toString(), result);
-
- stringBuilder = new StringBuilder();
- for (int i = 0; i < 10240; i++) {
- stringBuilder.append('-');
- }
- stringBuilder.replace(0, 2, "aa");
- s = new Scanner(stringBuilder.toString());
- result = s.findWithinHorizon(Pattern.compile("aa"), 0);
- assertEquals("aa", result);
-
- s = new Scanner("aaaa");
- result = s.findWithinHorizon(Pattern.compile("a*"), 0);
- assertEquals("aaaa", result);
- }
-
- /**
- * @tests java.util.Scanner#findWithinHorizon(String, int) Copy of Pattern
- * test for String
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "findWithinHorizon",
- args = {java.lang.String.class, int.class}
- )
- public void test_findWithinHorizon_Ljava_lang_StringI() {
-
- // This method searches through the input up to the specified search
- // horizon(exclusive).
- s = new Scanner("123test");
- String result = s.findWithinHorizon("\\p{Lower}", 5);
- assertEquals("t", result);
- MatchResult mresult = s.match();
- assertEquals(3, mresult.start());
- assertEquals(4, mresult.end());
-
- s = new Scanner("12345test1234test next");
- /*
- * If the pattern is found the scanner advances past the input that
- * matched and returns the string that matched the pattern.
- */
- result = s.findWithinHorizon("\\p{Digit}+", 2);
- assertEquals("12", result);
- mresult = s.match();
- assertEquals(0, mresult.start());
- assertEquals(2, mresult.end());
- // Postion is now pointing at the bar. "12|345test1234test next"
-
- result = s.findWithinHorizon("\\p{Digit}+", 6);
- assertEquals("345", result);
-
- mresult = s.match();
- assertEquals(2, mresult.start());
- assertEquals(5, mresult.end());
- // Postion is now pointing at the bar. "12345|test1234test next"
-
- // If no such pattern is detected then the null is returned and the
- // scanner's position remains unchanged.
- result = s.findWithinHorizon("\\p{Digit}+", 3);
- assertNull(result);
-
- try {
- s.match();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- assertEquals("345", mresult.group());
- assertEquals(2, mresult.start());
- assertEquals(5, mresult.end());
- // Postion is now still pointing at the bar. "12345|test1234test next"
-
- // If horizon is 0, then the horizon is ignored and this method
- // continues to search through the input looking for the specified
- // pattern without bound.
- result = s.findWithinHorizon("\\p{Digit}+", 0);
- mresult = s.match();
- assertEquals(9, mresult.start());
- assertEquals(13, mresult.end());
- // Postion is now pointing at the bar. "12345test1234|test next"
-
- assertEquals("test", s.next());
- mresult = s.match();
- assertEquals(13, mresult.start());
- assertEquals(17, mresult.end());
-
- assertEquals("next", s.next());
- mresult = s.match();
- assertEquals(18, mresult.start());
- assertEquals(22, mresult.end());
-
- try {
- s.findWithinHorizon((String)null, 1);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- s.findWithinHorizon("\\p{Digit}+", -1);
- fail("Should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- s.close();
- // on RI throws NullPointerException
- /*
- * try { System.out.println("fsdfs"); s.findWithinHorizon((String) null,
- * -1); System.out.println("fsdfs"); fail("Should throw
- * IllegalStateException"); } catch (IllegalStateException e) { //
- * expected }
- */
- s = new Scanner("test");
- result = s.findWithinHorizon("\\w+", 10);
- assertEquals("test", result);
-
- s = new Scanner("aa\n\rb");
- String patternStr = "^(a)$";
- result = s.findWithinHorizon("a", 5);
- assertEquals("a", result);
- mresult = s.match();
- assertEquals(0, mresult.start());
- assertEquals(1, mresult.end());
-
- result = s.findWithinHorizon(patternStr, 5);
- assertNull(result);
-
- try {
- mresult = s.match();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- s = new Scanner("");
- result = s.findWithinHorizon("^", 0);
- assertEquals("", result);
- MatchResult matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(0, matchResult.end());
-
- result = s.findWithinHorizon("$", 0);
- assertEquals("", result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(0, matchResult.end());
-
- s = new Scanner("1 fish 2 fish red fish blue fish");
- result = s.findWithinHorizon("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)", 10);
- assertNull(result);
-
- try {
- mresult = s.match();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- assertEquals(0, mresult.groupCount());
-
- result = s.findWithinHorizon("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)", 100);
- assertEquals("1 fish 2 fish red fish blue", result);
- mresult = s.match();
- assertEquals(4, mresult.groupCount());
- assertEquals("1", mresult.group(1));
- assertEquals("2", mresult.group(2));
- assertEquals("red", mresult.group(3));
- assertEquals("blue", mresult.group(4));
-
- s = new Scanner("test");
- s.close();
- try {
- s.findWithinHorizon("test", 1);
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- s = new Scanner("word1 WorD2 ");
- s.close();
- try {
- s.findWithinHorizon("\\d+", 10);
- fail("should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- s = new Scanner("word1 WorD2 wOrd3 ");
- patternStr = "\\d+";
- assertEquals("1", s.findWithinHorizon(patternStr, 10));
- assertEquals("WorD2", s.next());
- assertEquals("3", s.findWithinHorizon(patternStr, 15));
-
- // Regression test
- s = new Scanner(new MockStringReader("MockStringReader"));
- patternStr = "test";
- result = s.findWithinHorizon(patternStr, 10);
- assertEquals("test", result);
-
- // Test the situation when input length is longer than buffer size.
- StringBuilder stringBuilder = new StringBuilder();
- for (int i = 0; i < 1026; i++) {
- stringBuilder.append('a');
- }
- s = new Scanner(stringBuilder.toString());
- patternStr = "\\p{Lower}+";
- result = s.findWithinHorizon(patternStr, 1026);
- assertEquals(stringBuilder.toString(), result);
-
- // Test the situation when input length is longer than buffer size and
- // set horizon to buffer size.
- stringBuilder = new StringBuilder();
- for (int i = 0; i < 1026; i++) {
- stringBuilder.append('a');
- }
- s = new Scanner(stringBuilder.toString());
- patternStr = "\\p{Lower}+";
- result = s.findWithinHorizon(patternStr, 1022);
- assertEquals(1022, result.length());
- assertEquals(stringBuilder.subSequence(0, 1022), result);
-
- // Test the situation, under which pattern is clipped by buffer.
- stringBuilder = new StringBuilder();
- for (int i = 0; i < 1022; i++) {
- stringBuilder.append(' ');
- }
- stringBuilder.append("bbc");
- assertEquals(1025, stringBuilder.length());
- s = new Scanner(stringBuilder.toString());
- patternStr = "bbc";
- result = s.findWithinHorizon(patternStr, 1025);
- assertEquals(3, result.length());
- assertEquals(stringBuilder.subSequence(1022, 1025), result);
-
- stringBuilder = new StringBuilder();
- for (int i = 0; i < 1026; i++) {
- stringBuilder.append('a');
- }
- s = new Scanner(stringBuilder.toString());
- patternStr = "\\p{Lower}+";
- result = s.findWithinHorizon(patternStr, 0);
- assertEquals(stringBuilder.toString(), result);
-
- stringBuilder = new StringBuilder();
- for (int i = 0; i < 10240; i++) {
- stringBuilder.append('-');
- }
- stringBuilder.replace(0, 2, "aa");
- s = new Scanner(stringBuilder.toString());
- result = s.findWithinHorizon("aa", 0);
- assertEquals("aa", result);
-
- s = new Scanner("aaaa");
- result = s.findWithinHorizon("a*", 0);
- assertEquals("aaaa", result);
- }
-
- /**
- * @tests java.util.Scanner#findInLine(Pattern)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "findInLine",
- args = {java.util.regex.Pattern.class}
- )
- public void test_findInLine_LPattern() {
-
- Scanner s = new Scanner("");
- try {
- s.findInLine((Pattern) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // Expected
- }
- String result = s.findInLine(Pattern.compile("^"));
- assertEquals("", result);
- MatchResult matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(0, matchResult.end());
-
- result = s.findInLine(Pattern.compile("$"));
- assertEquals("", result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(0, matchResult.end());
-
- /*
- * When we use the operation of findInLine(Pattern), the match region
- * should not span the line separator.
- */
- s = new Scanner("aa\nb.b");
- result = s.findInLine(Pattern.compile("a\nb*"));
- assertNull(result);
-
- s = new Scanner("aa\nbb.b");
- result = s.findInLine(Pattern.compile("\\."));
- assertNull(result);
-
- s = new Scanner("abcd1234test\n");
- result = s.findInLine(Pattern.compile("\\p{Lower}+"));
- assertEquals("abcd", result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(4, matchResult.end());
-
- result = s.findInLine(Pattern.compile("\\p{Digit}{5}"));
- assertNull(result);
- try {
- matchResult = s.match();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- assertEquals(0, matchResult.start());
- assertEquals(4, matchResult.end());
-
- result = s.findInLine(Pattern.compile("\\p{Lower}+"));
- assertEquals("test", result);
- matchResult = s.match();
- assertEquals(8, matchResult.start());
- assertEquals(12, matchResult.end());
-
- char[] chars = new char[2048];
- Arrays.fill(chars, 'a');
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append(chars);
- stringBuilder.append("1234");
- s = new Scanner(stringBuilder.toString());
- result = s.findInLine(Pattern.compile("\\p{Digit}+"));
- assertEquals("1234", result);
- matchResult = s.match();
- assertEquals(2048, matchResult.start());
- assertEquals(2052, matchResult.end());
-
- s = new Scanner("test");
- s.close();
- try {
- s.findInLine((Pattern) null);
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- s = new Scanner("test1234\n1234 test");
- result = s.findInLine(Pattern.compile("test"));
- assertEquals("test", result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(4, matchResult.end());
-
- int number = s.nextInt();
- assertEquals(1234, number);
- matchResult = s.match();
- assertEquals(4, matchResult.start());
- assertEquals(8, matchResult.end());
-
- result = s.next();
- assertEquals("1234", result);
- matchResult = s.match();
- assertEquals(9, matchResult.start());
- assertEquals(13, matchResult.end());
-
- result = s.findInLine(Pattern.compile("test"));
- assertEquals("test", result);
- matchResult = s.match();
- assertEquals(14, matchResult.start());
- assertEquals(18, matchResult.end());
-
- s = new Scanner("test\u0085\ntest");
- result = s.findInLine("est");
- assertEquals("est", result);
- result = s.findInLine("est");
- assertEquals("est", result);
-
- s = new Scanner("test\ntest");
- result = s.findInLine("est");
- assertEquals("est", result);
- result = s.findInLine("est");
- assertEquals("est", result);
-
- s = new Scanner("test\n123\ntest");
- result = s.findInLine("est");
- assertEquals("est", result);
- result = s.findInLine("est");
- // RI fails. It is a RI's bug.
- if (!disableRIBugs) {
- assertNull(result);
- }
- }
-
- /**
- * @tests java.util.Scanner#findInLine(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "findInLine",
- args = {java.lang.String.class}
- )
- public void test_findInLine_LString() {
- s = new Scanner("test");
- try {
- s.findInLine((String) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- s.close();
- try {
- s.findInLine((String) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- try {
- s.findInLine("test");
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // exptected
- }
-
- s = new Scanner("");
-
- String result = s.findInLine("^");
- assertEquals("", result);
- MatchResult matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(0, matchResult.end());
-
- result = s.findInLine("$");
- assertEquals("", result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(0, matchResult.end());
-
- /*
- * When we use the operation of findInLine(Pattern), the match region
- * should not span the line separator.
- */
- s = new Scanner("aa\nb.b");
- result = s.findInLine("a\nb*");
- assertNull(result);
-
- s = new Scanner("aa\nbb.b");
- result = s.findInLine("\\.");
- assertNull(result);
-
- s = new Scanner("abcd1234test\n");
- result = s.findInLine("\\p{Lower}+");
- assertEquals("abcd", result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(4, matchResult.end());
-
- result = s.findInLine("\\p{Digit}{5}");
- assertNull(result);
- try {
- matchResult = s.match();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- assertEquals(0, matchResult.start());
- assertEquals(4, matchResult.end());
-
- result = s.findInLine("\\p{Lower}+");
- assertEquals("test", result);
- matchResult = s.match();
- assertEquals(8, matchResult.start());
- assertEquals(12, matchResult.end());
-
- char[] chars = new char[2048];
- Arrays.fill(chars, 'a');
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append(chars);
- stringBuilder.append("1234");
- s = new Scanner(stringBuilder.toString());
- result = s.findInLine("\\p{Digit}+");
- assertEquals("1234", result);
- matchResult = s.match();
- assertEquals(2048, matchResult.start());
- assertEquals(2052, matchResult.end());
-
- s = new Scanner("test1234\n1234 test");
- result = s.findInLine("test");
- assertEquals("test", result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(4, matchResult.end());
-
- int number = s.nextInt();
- assertEquals(1234, number);
- matchResult = s.match();
- assertEquals(4, matchResult.start());
- assertEquals(8, matchResult.end());
-
- result = s.next();
- assertEquals("1234", result);
- matchResult = s.match();
- assertEquals(9, matchResult.start());
- assertEquals(13, matchResult.end());
-
- result = s.findInLine("test");
- assertEquals("test", result);
- matchResult = s.match();
- assertEquals(14, matchResult.start());
- assertEquals(18, matchResult.end());
-
- s = new Scanner("test\u0085\ntest");
- result = s.findInLine("est");
- assertEquals("est", result);
- result = s.findInLine("est");
- assertEquals("est", result);
-
- s = new Scanner("test\ntest");
- result = s.findInLine("est");
- assertEquals("est", result);
- result = s.findInLine("est");
- assertEquals("est", result);
-
- s = new Scanner("test\n123\ntest");
- result = s.findInLine("est");
- assertEquals("est", result);
- result = s.findInLine("est");
- // RI fails. It is a RI's bug.
- if (!disableRIBugs) {
- assertNull(result);
- }
-
-
- }
-
- /**
- * @tests java.util.Scanner#skip(Pattern)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "skip",
- args = {java.util.regex.Pattern.class}
- )
- public void test_skip_LPattern() {
- s = new Scanner("test");
- try {
- s.skip((String) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- // If pattern does not match, NoSuchElementException will be thrown out.
- s = new Scanner("1234");
- try {
- s.skip(Pattern.compile("\\p{Lower}"));
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // expected
- }
- // Then, no matchResult will be thrown out.
- try {
- s.match();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- s.skip(Pattern.compile("\\p{Digit}"));
- MatchResult matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(1, matchResult.end());
-
- s.skip(Pattern.compile("\\p{Digit}+"));
- matchResult = s.match();
- assertEquals(1, matchResult.start());
- assertEquals(4, matchResult.end());
-
- s.close();
- try {
- s.skip(Pattern.compile("test"));
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- MockStringReader2Read reader = new MockStringReader2Read("test");
- s = new Scanner(reader);
- try {
- s.skip(Pattern.compile("\\p{Digit}{4}"));
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // expected
- }
- try {
- s.match();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- s.skip(Pattern.compile("\\p{Digit}{3}\\p{Lower}"));
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(4, matchResult.end());
-
- s.close();
- try {
- s.skip((Pattern) null);
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- StringBuilder stringBuilder = new StringBuilder();
- char [] chars = new char[1024];
- Arrays.fill(chars, 'a');
- stringBuilder.append(chars);
- stringBuilder.append('3');
- s = new Scanner(stringBuilder.toString());
- s.skip(Pattern.compile("\\p{Lower}+\\p{Digit}"));
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(1025, matchResult.end());
-
- // Large amount of input may be cached
- chars = new char[102400];
- Arrays.fill(chars, 'a');
- stringBuilder = new StringBuilder();
- stringBuilder.append(chars);
- s = new Scanner(stringBuilder.toString());
- s.skip(Pattern.compile(".*"));
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(102400, matchResult.end());
-
- // skip something without risking a NoSuchElementException
- s.skip(Pattern.compile("[ \t]*"));
- matchResult = s.match();
- assertEquals(102400, matchResult.start());
- assertEquals(102400, matchResult.end());
- }
-
- /**
- * @tests java.util.Scanner#skip(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "skip",
- args = {java.lang.String.class}
- )
- public void test_skip_LString() {
- s = new Scanner("test");
- try {
- s.skip((String) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- // If pattern does not match, NoSuchElementException will be thrown out.
- s = new Scanner("1234");
- try {
- s.skip("\\p{Lower}");
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // expected
- }
- // Then, no matchResult will be thrown out.
- try {
- s.match();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- s.skip("\\p{Digit}");
- MatchResult matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(1, matchResult.end());
-
- s.skip("\\p{Digit}+");
- matchResult = s.match();
- assertEquals(1, matchResult.start());
- assertEquals(4, matchResult.end());
-
- s.close();
- try {
- s.skip("test");
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- MockStringReader2Read reader = new MockStringReader2Read("test");
- s = new Scanner(reader);
- try {
- s.skip("\\p{Digit}{4}");
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // expected
- }
- try {
- s.match();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- s.skip("\\p{Digit}{3}\\p{Lower}");
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(4, matchResult.end());
-
- s.close();
- try {
- s.skip("");
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- StringBuilder stringBuilder = new StringBuilder();
- char [] chars = new char[1024];
- Arrays.fill(chars, 'a');
- stringBuilder.append(chars);
- stringBuilder.append('3');
- s = new Scanner(stringBuilder.toString());
- s.skip("\\p{Lower}+\\p{Digit}");
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(1025, matchResult.end());
-
- // Large amount of input may be cached
- chars = new char[102400];
- Arrays.fill(chars, 'a');
- stringBuilder = new StringBuilder();
- stringBuilder.append(chars);
- s = new Scanner(stringBuilder.toString());
- s.skip(".*");
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(102400, matchResult.end());
-
- // skip something without risking a NoSuchElementException
- s.skip("[ \t]*");
- matchResult = s.match();
- assertEquals(102400, matchResult.start());
- assertEquals(102400, matchResult.end());
-
- s = new Scanner("test");
- try {
- s.skip((String) null);
- fail("Should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#nextDouble()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextDouble",
- args = {}
- )
- public void test_nextDouble() throws IOException {
- s = new Scanner("123 45\u0666. 123.4 .123 ");
- s.useLocale(Locale.ENGLISH);
- assertEquals(123.0, s.nextDouble());
- assertEquals(456.0, s.nextDouble());
- assertEquals(123.4, s.nextDouble());
- assertEquals(0.123, s.nextDouble());
- try {
- s.nextDouble();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- s = new Scanner("+123.4 -456.7 123,456.789 0.1\u06623,4");
- s.useLocale(Locale.ENGLISH);
- assertEquals(123.4, s.nextDouble());
- assertEquals(-456.7, s.nextDouble());
- assertEquals(123456.789, s.nextDouble());
- try {
- s.nextDouble();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // Scientific notation
- s = new Scanner("+123.4E10 -456.7e+12 123,456.789E-10");
- s.useLocale(Locale.ENGLISH);
- assertEquals(1.234E12, s.nextDouble());
- assertEquals(-4.567E14, s.nextDouble());
- assertEquals(1.23456789E-5, s.nextDouble());
-
- s = new Scanner("NaN Infinity -Infinity");
- assertEquals(Double.NaN, s.nextDouble());
- assertEquals(Double.POSITIVE_INFINITY, s.nextDouble());
- assertEquals(Double.NEGATIVE_INFINITY, s.nextDouble());
-
- //The following test case fails on RI
- s=new Scanner("\u221e");
- s.useLocale(Locale.ENGLISH);
-// assertEquals(Double.POSITIVE_INFINITY, s.nextDouble());
-
- String str=String.valueOf(Double.MAX_VALUE*2);
- s=new Scanner(str);
- assertEquals(Double.POSITIVE_INFINITY,s.nextDouble());
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.ENGLISH);
- assertEquals(23456.0, s.nextDouble());
- s.useLocale(Locale.GERMANY);
- assertEquals(23.456, s.nextDouble());
-
- s = new Scanner("23.456 23.456");
- s.useLocale(Locale.ENGLISH);
- assertEquals(23.456, s.nextDouble());
- s.useLocale(Locale.GERMANY);
- assertEquals(23456.0, s.nextDouble());
-
- s = new Scanner("23,456.7 23.456,7");
- s.useLocale(Locale.ENGLISH);
- assertEquals(23456.7, s.nextDouble());
- s.useLocale(Locale.GERMANY);
- assertEquals(23456.7, s.nextDouble());
-
- s = new Scanner("-123.4");
- s.useLocale(Locale.ENGLISH);
- assertEquals(-123.4, s.nextDouble());
-
- s.close();
- try {
- s.nextDouble();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @throws IOException
- * @tests java.util.Scanner#nextBigDecimal()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextBigDecimal",
- args = {}
- )
- public void test_nextBigDecimal() throws IOException {
- s = new Scanner("123 45\u0666. 123.4 .123 ");
- s.useLocale(Locale.ENGLISH);
- assertEquals(new BigDecimal("123"), s.nextBigDecimal());
- assertEquals(new BigDecimal("456"), s.nextBigDecimal());
- assertEquals(new BigDecimal("123.4"), s.nextBigDecimal());
- assertEquals(new BigDecimal("0.123"), s.nextBigDecimal());
- try {
- s.nextBigDecimal();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // Expected
- }
-
- s = new Scanner("+123.4 -456.7 123,456.789 0.1\u06623,4");
- s.useLocale(Locale.ENGLISH);
- assertEquals(new BigDecimal("123.4"), s.nextBigDecimal());
- assertEquals(new BigDecimal("-456.7"), s.nextBigDecimal());
- assertEquals(new BigDecimal("123456.789"), s.nextBigDecimal());
- try {
- s.nextBigDecimal();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- // Scientific notation
- s = new Scanner("+123.4E10 -456.7e+12 123,456.789E-10");
- s.useLocale(Locale.ENGLISH);
- assertEquals(new BigDecimal("1.234E12"), s.nextBigDecimal());
- assertEquals(new BigDecimal("-4.567E14"), s.nextBigDecimal());
- assertEquals(new BigDecimal("1.23456789E-5"), s.nextBigDecimal());
-
- s = new Scanner("NaN");
- try {
- s.nextBigDecimal();
- fail("Should throw InputMismatchException");
- } catch (InputMismatchException e) {
- // Expected
- }
-
- /*
- * Different locale can only recognize corresponding locale sensitive
- * string. ',' is used in many locales as group separator.
- */
- s = new Scanner("23,456 23,456");
- s.useLocale(Locale.ENGLISH);
- assertEquals(new BigDecimal("23456"), s.nextBigDecimal());
- s.useLocale(Locale.GERMANY);
- assertEquals(new BigDecimal("23.456"), s.nextBigDecimal());
-
- s = new Scanner("23.456 23.456");
- s.useLocale(Locale.ENGLISH);
- assertEquals(new BigDecimal("23.456"), s.nextBigDecimal());
- s.useLocale(Locale.GERMANY);
- assertEquals(new BigDecimal("23456"), s.nextBigDecimal());
-
- s = new Scanner("23,456.7");
- s.useLocale(Locale.ENGLISH);
- assertEquals(new BigDecimal("23456.7"), s.nextBigDecimal());
-
- s = new Scanner("-123.4");
- s.useLocale(Locale.ENGLISH);
- assertEquals(new BigDecimal("-123.4"), s.nextBigDecimal());
-
- s.close();
- try {
- s.nextBigDecimal();
- fail("IllegalStateException expected");
- } catch (IllegalStateException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Scanner#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- s = new Scanner("test");
- assertNotNull(s.toString());
- }
-
- /**
- * @tests java.util.Scanner#nextLine()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextLine",
- args = {}
- )
- public void test_nextLine() {
- s = new Scanner("");
- s.close();
- try {
- s.nextLine();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- s = new Scanner("test\r\ntest");
- String result = s.nextLine();
- assertEquals("test", result);
- MatchResult matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(6, matchResult.end());
-
- s = new Scanner("\u0085");
- result = s.nextLine();
- assertEquals("", result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(1, matchResult.end());
-
- s = new Scanner("\u2028");
- result = s.nextLine();
- assertEquals("", result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(1, matchResult.end());
-
- s = new Scanner("\u2029");
- result = s.nextLine();
- assertEquals("", result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(1, matchResult.end());
-
- s = new Scanner("");
- try {
- result = s.nextLine();
- fail("Should throw NoSuchElementException");
- } catch (NoSuchElementException e) {
- // expected
- }
- try {
- s.match();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- s = new Scanner("Ttest");
- result = s.nextLine();
- assertEquals("Ttest", result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(5, matchResult.end());
-
- s = new Scanner("\r\n");
- result = s.nextLine();
- assertEquals("", result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(2, matchResult.end());
-
- char[] chars = new char[1024];
- Arrays.fill(chars, 'a');
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append(chars);
- chars = new char[] { '+', '-' };
- stringBuilder.append(chars);
- stringBuilder.append("\u2028");
- s = new Scanner(stringBuilder.toString());
- result = s.nextLine();
-
- assertEquals(stringBuilder.toString().substring(0, 1026), result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(1027, matchResult.end());
-
- chars = new char[1023];
- Arrays.fill(chars, 'a');
- stringBuilder = new StringBuilder();
- stringBuilder.append(chars);
- stringBuilder.append("\r\n");
- s = new Scanner(stringBuilder.toString());
- result = s.nextLine();
-
- assertEquals(stringBuilder.toString().substring(0, 1023), result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(1025, matchResult.end());
-
- s = new Scanner(" ");
- result = s.nextLine();
- assertEquals(" ", result);
-
- s = new Scanner("test\n\n\n");
- result = s.nextLine();
- assertEquals("test", result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(5, matchResult.end());
- result = s.nextLine();
- matchResult = s.match();
- assertEquals(5, matchResult.start());
- assertEquals(6, matchResult.end());
-
- s = new Scanner("\n\n\n");
- result = s.nextLine();
- assertEquals("", result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(1, matchResult.end());
- result = s.nextLine();
- matchResult = s.match();
- assertEquals(1, matchResult.start());
- assertEquals(2, matchResult.end());
-
- s = new Scanner("123 test\n ");
- int value = s.nextInt();
- assertEquals(123, value);
-
- result = s.nextLine();
- assertEquals(" test", result);
-
- s = new Scanner("test\n ");
- result = s.nextLine();
- assertEquals("test", result);
- }
-
- /**
- * @tests java.util.Scanner#hasNextLine()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasNextLine",
- args = {}
- )
- public void test_hasNextLine() {
-
- s = new Scanner("");
- s.close();
- try {
- s.hasNextLine();
- fail("Should throw IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
-
- s = new Scanner("test\r\ntest");
- boolean result = s.hasNextLine();
- assertTrue(result);
- MatchResult matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(6, matchResult.end());
-
- s = new Scanner("\u0085");
- result = s.hasNextLine();
- assertTrue(result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(1, matchResult.end());
-
- s = new Scanner("\u2028");
- result = s.hasNextLine();
- assertTrue(result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(1, matchResult.end());
-
- s = new Scanner("\u2029");
- result = s.hasNextLine();
- assertTrue(result);
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(1, matchResult.end());
-
- s = new Scanner("test\n");
- assertTrue(s.hasNextLine());
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(5, matchResult.end());
-
- char[] chars = new char[2048];
- Arrays.fill(chars, 'a');
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append(chars);
- s = new Scanner(stringBuilder.toString());
- result = s.hasNextLine();
- assertTrue(result);
-
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(2048, matchResult.end());
-
- s = new Scanner("\n\n\n");
- assertTrue(s.hasNextLine());
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(1, matchResult.end());
-
- // The scanner will not advance any input.
- assertTrue(s.hasNextLine());
- matchResult = s.match();
- assertEquals(0, matchResult.start());
- assertEquals(1, matchResult.end());
- }
-
- protected void setUp() throws Exception {
- super.setUp();
-
- server = new ServerSocket(0);
- address = new InetSocketAddress("127.0.0.1", server.getLocalPort());
-
- client = SocketChannel.open();
- client.connect(address);
- serverSocket = server.accept();
-
- os = serverSocket.getOutputStream();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
-
- try {
- serverSocket.close();
- } catch (Exception e) {
-
- }
- try {
- client.close();
- } catch (Exception e) {
- // do nothing
- }
- try {
- server.close();
- } catch (Exception e) {
- // do nothing
- }
- }
-
- /**
- * @tests java.util.Scanner#Scanner(ReadableByteChannel)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Scanner",
- args = {java.nio.channels.ReadableByteChannel.class}
- )
- public void test_Constructor_LReadableByteChannel()
- throws IOException {
- InetSocketAddress localAddr = new InetSocketAddress("127.0.0.1",
- Support_PortManager.getNextPort());
- ServerSocketChannel ssc = ServerSocketChannel.open();
- ssc.socket().bind(localAddr);
-
- SocketChannel sc = SocketChannel.open();
- sc.connect(localAddr);
- sc.configureBlocking(false);
- assertFalse(sc.isBlocking());
-
- ssc.accept().close();
- ssc.close();
- assertFalse(sc.isBlocking());
-
- Scanner s = new Scanner(sc);
- while (s.hasNextInt()) {
- s.nextInt();
- }
-
- sc.close();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/SimpleTimeZoneTest.java b/luni/src/test/java/tests/api/java/util/SimpleTimeZoneTest.java
deleted file mode 100644
index ab0dd0e..0000000
--- a/luni/src/test/java/tests/api/java/util/SimpleTimeZoneTest.java
+++ /dev/null
@@ -1,977 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.SimpleTimeZone;
-import java.util.TimeZone;
-
-@TestTargetClass(SimpleTimeZone.class)
-public class SimpleTimeZoneTest extends junit.framework.TestCase {
-
- SimpleTimeZone st1;
-
- SimpleTimeZone st2;
-
- /**
- * @tests java.util.SimpleTimeZone#SimpleTimeZone(int, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SimpleTimeZone",
- args = {int.class, java.lang.String.class}
- )
- public void test_ConstructorILjava_lang_String() {
- // Test for method java.util.SimpleTimeZone(int, java.lang.String)
-
- SimpleTimeZone st = new SimpleTimeZone(1000, "TEST");
- assertEquals("Incorrect TZ constructed", "TEST", st.getID());
- assertTrue("Incorrect TZ constructed: " + "returned wrong offset", st
- .getRawOffset() == 1000);
- assertTrue("Incorrect TZ constructed" + "using daylight savings", !st
- .useDaylightTime());
- }
-
- /**
- * @tests java.util.SimpleTimeZone#SimpleTimeZone(int, java.lang.String,
- * int, int, int, int, int, int, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SimpleTimeZone",
- args = {int.class, java.lang.String.class, int.class, int.class, int.class, int.class, int.class, int.class, int.class, int.class}
- )
- public void test_ConstructorILjava_lang_StringIIIIIIII() {
- // Test for method java.util.SimpleTimeZone(int, java.lang.String, int,
- // int, int, int, int, int, int, int)
- SimpleTimeZone st = new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
- 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0);
- assertTrue("Incorrect TZ constructed", st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.NOVEMBER,
- 13).getTime()));
- assertTrue("Incorrect TZ constructed", !(st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
- 13).getTime())));
- assertEquals("Incorrect TZ constructed", "TEST", st.getID());
- assertEquals("Incorrect TZ constructed", 1000, st.getRawOffset());
- assertTrue("Incorrect TZ constructed", st.useDaylightTime());
-
- try {
- new SimpleTimeZone(1000, "TEST", 12,
- 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
- 10, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
- 1, 10, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new SimpleTimeZone(1000, "TEST", Calendar.DECEMBER,
- 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -10, Calendar.SUNDAY,
- 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.SimpleTimeZone#SimpleTimeZone(int, java.lang.String,
- * int, int, int, int, int, int, int, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SimpleTimeZone",
- args = {int.class, java.lang.String.class, int.class, int.class, int.class, int.class, int.class, int.class, int.class, int.class, int.class}
- )
- public void test_ConstructorILjava_lang_StringIIIIIIIII() {
- // Test for method java.util.SimpleTimeZone(int, java.lang.String, int,
- // int, int, int, int, int, int, int, int)
- SimpleTimeZone st = new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
- 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0, 1000 * 60 * 60);
- assertTrue("Incorrect TZ constructed", st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.NOVEMBER,
- 13).getTime()));
- assertTrue("Incorrect TZ constructed", !(st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
- 13).getTime())));
- assertEquals("Incorrect TZ constructed", "TEST", st.getID());
- assertEquals("Incorrect TZ constructed", 1000, st.getRawOffset());
- assertTrue("Incorrect TZ constructed", st.useDaylightTime());
- assertTrue("Incorrect TZ constructed",
- st.getDSTSavings() == 1000 * 60 * 60);
-
- try {
- new SimpleTimeZone(1000, "TEST", 12,
- 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0, 1000 * 60 * 60);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
- 10, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0, 1000 * 60 * 60);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
- 1, 10, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0, 1000 * 60 * 60);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new SimpleTimeZone(1000, "TEST", Calendar.DECEMBER,
- 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -10, Calendar.SUNDAY,
- 0, 1000 * 60 * 60);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.SimpleTimeZone#SimpleTimeZone(int, java.lang.String,
- * int, int, int, int, int, int, int, int, int, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SimpleTimeZone",
- args = {int.class, java.lang.String.class, int.class, int.class, int.class, int.class, int.class, int.class, int.class, int.class, int.class, int.class, int.class}
- )
- public void test_ConstructorILjava_lang_StringIIIIIIIIIII() {
- // Test for method java.util.SimpleTimeZone(int, java.lang.String, int,
- // int, int, int, int, int, int, int, int, int, int)
- // TODO : Implement test
- //Regression for HARMONY-1241
- assertNotNull(new SimpleTimeZone(
- TimeZone.LONG,
- "Europe/Paris",
- SimpleTimeZone.STANDARD_TIME,
- SimpleTimeZone.STANDARD_TIME,
- SimpleTimeZone.UTC_TIME,
- SimpleTimeZone.WALL_TIME,
- SimpleTimeZone.WALL_TIME,
- TimeZone.SHORT,
- SimpleTimeZone.STANDARD_TIME,
- TimeZone.LONG,
- SimpleTimeZone.UTC_TIME,
- SimpleTimeZone.STANDARD_TIME,
- TimeZone.LONG));
- //seems RI doesn't check the startTimeMode and endTimeMode at all
- //this behavior is contradicts with spec
- assertNotNull(new SimpleTimeZone(
- TimeZone.LONG,
- "Europe/Paris",
- SimpleTimeZone.STANDARD_TIME,
- SimpleTimeZone.STANDARD_TIME,
- SimpleTimeZone.UTC_TIME,
- SimpleTimeZone.WALL_TIME,
- Integer.MAX_VALUE,
- TimeZone.SHORT,
- SimpleTimeZone.STANDARD_TIME,
- TimeZone.LONG,
- SimpleTimeZone.UTC_TIME,
- Integer.MIN_VALUE,
- TimeZone.LONG));
-
- try {
- new SimpleTimeZone(1000, "TEST", 12,
- 1, Calendar.SUNDAY, 0, Integer.MAX_VALUE, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0, Integer.MAX_VALUE, 1000 * 60 * 60);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
- 10, Calendar.SUNDAY, 0, Integer.MAX_VALUE, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0, Integer.MAX_VALUE, 1000 * 60 * 60);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
- 1, 10, 0, Calendar.NOVEMBER, Integer.MAX_VALUE, -1, Calendar.SUNDAY,
- 0, Integer.MAX_VALUE, 1000 * 60 * 60);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new SimpleTimeZone(1000, "TEST", Calendar.DECEMBER,
- 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, Integer.MAX_VALUE, -10, Calendar.SUNDAY,
- 0, Integer.MAX_VALUE, 1000 * 60 * 60);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.SimpleTimeZone#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- // Test for method java.lang.Object java.util.SimpleTimeZone.clone()
- SimpleTimeZone st1 = new SimpleTimeZone(1000, "TEST",
- Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER,
- -1, Calendar.SUNDAY, 0);
- SimpleTimeZone stA = new SimpleTimeZone(1, "Gah");
- assertTrue("Clone resulted in same reference", st1.clone() != st1);
- assertTrue("Clone resulted in unequal object", ((SimpleTimeZone) st1
- .clone()).equals(st1));
- assertTrue("Clone resulted in same reference", stA.clone() != stA);
- assertTrue("Clone resulted in unequal object", ((SimpleTimeZone) stA
- .clone()).equals(stA));
- }
-
- /**
- * @tests java.util.SimpleTimeZone#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean
- // java.util.SimpleTimeZone.equals(java.lang.Object)
- TimeZone tz = TimeZone.getTimeZone("EST");
- st1 = new SimpleTimeZone(tz.getRawOffset(), "EST");
- st2 = new SimpleTimeZone(0, "EST");
- assertFalse(st1.equals(st2));
- st1.setRawOffset(st2.getRawOffset());
- assertTrue(st1.equals(st2));
- }
-
- /**
- * @tests java.util.SimpleTimeZone#getDSTSavings()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDSTSavings",
- args = {}
- )
- public void test_getDSTSavings() {
- // Test for method int java.util.SimpleTimeZone.getDSTSavings()
- st1 = new SimpleTimeZone(0, "TEST");
-
- assertEquals("Non-zero default daylight savings",
- 0, st1.getDSTSavings());
- st1.setStartRule(0, 1, 1, 1);
- st1.setEndRule(11, 1, 1, 1);
-
- assertEquals("Incorrect default daylight savings",
- 3600000, st1.getDSTSavings());
- st1 = new SimpleTimeZone(-5 * 3600000, "EST", Calendar.APRIL, 1,
- -Calendar.SUNDAY, 2 * 3600000, Calendar.OCTOBER, -1,
- Calendar.SUNDAY, 2 * 3600000, 7200000);
- assertEquals("Incorrect daylight savings from constructor", 7200000, st1
- .getDSTSavings());
-
- }
-
- /**
- * @tests java.util.SimpleTimeZone#getOffset(int, int, int, int, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getOffset",
- args = {int.class, int.class, int.class, int.class, int.class, int.class}
- )
- public void test_getOffsetIIIIII() {
- // Test for method int java.util.SimpleTimeZone.getOffset(int, int, int,
- // int, int, int)
-// TimeZone st1 = TimeZone.getTimeZone("EST");
- st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
- assertTrue("Incorrect offset returned", st1.getOffset(
- GregorianCalendar.AD, 1998, Calendar.NOVEMBER, 11,
- Calendar.WEDNESDAY, 0) == -(5 * 60 * 60 * 1000));
-
- st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
- assertEquals("Incorrect offset returned", -(5 * 60 * 60 * 1000), st1
- .getOffset(GregorianCalendar.AD, 1998, Calendar.JUNE, 11,
- Calendar.THURSDAY, 0));
-
- // Regression for HARMONY-5459
- st1 = new SimpleTimeZone(TimeZone.getDefault().getRawOffset(), TimeZone.getDefault().getID());
- int fourHours = 4*60*60*1000;
- st1.setRawOffset(fourHours);
- assertEquals(fourHours, st1.getOffset(1, 2099, 01, 1, 5, 0));
-
- try {
- st1.getOffset(-1, 2099, 01, 1, 5, 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- st1.getOffset(1, 2099, 15, 1, 5, 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- st1.getOffset(1, 2099, 01, 100, 5, 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- st1.getOffset(1, 2099, 01, 1, 50, 0);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- st1.getOffset(1, 2099, 01, 1, 5, -10);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.SimpleTimeZone#getRawOffset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRawOffset",
- args = {}
- )
- public void test_getRawOffset() {
- // Test for method int java.util.SimpleTimeZone.getRawOffset()
- st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
- assertTrue("Incorrect offset returned",
- st1.getRawOffset() == -(5 * 60 * 60 * 1000));
-
- }
-
- /**
- * @tests java.util.SimpleTimeZone#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- // Test for method int java.util.SimpleTimeZone.hashCode()
- // For lack of a better test.
- st1 = new SimpleTimeZone(-5 * 3600000, "EST", Calendar.APRIL, 1,
- -Calendar.SUNDAY, 2 * 3600000, Calendar.OCTOBER, -1,
- Calendar.SUNDAY, 2 * 3600000);
- assertTrue(TimeZone.getTimeZone("EST").hashCode() != 0);
- assertTrue(st1.hashCode() != 0);
- }
-
- /**
- * @tests java.util.SimpleTimeZone#hasSameRules(java.util.TimeZone)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasSameRules",
- args = {java.util.TimeZone.class}
- )
- public void test_hasSameRulesLjava_util_TimeZone() {
- // Test for method boolean
- // java.util.SimpleTimeZone.hasSameRules(java.util.TimeZone)
- SimpleTimeZone st = new SimpleTimeZone(1000, "TEST", Calendar.NOVEMBER,
- 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER, -1, Calendar.SUNDAY,
- 0);
- SimpleTimeZone sameAsSt = new SimpleTimeZone(1000, "REST",
- Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0, Calendar.NOVEMBER,
- -1, Calendar.SUNDAY, 0);
- SimpleTimeZone notSameAsSt = new SimpleTimeZone(1000, "PEST",
- Calendar.NOVEMBER, 2, Calendar.SUNDAY, 0, Calendar.NOVEMBER,
- -1, Calendar.SUNDAY, 0);
- assertTrue("Time zones have same rules but return false", st
- .hasSameRules(sameAsSt));
- assertTrue("Time zones have different rules but return true", !st
- .hasSameRules(notSameAsSt));
- }
-
- /**
- * @tests java.util.SimpleTimeZone#inDaylightTime(java.util.Date)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "inDaylightTime",
- args = {java.util.Date.class}
- )
- public void test_inDaylightTimeLjava_util_Date() {
- // Test for method boolean
- // java.util.SimpleTimeZone.inDaylightTime(java.util.Date)
- TimeZone tz = TimeZone.getTimeZone("EST");
- SimpleTimeZone zone = new SimpleTimeZone(tz.getRawOffset(), "EST",
- Calendar.APRIL, 1, -Calendar.SUNDAY, 7200000, Calendar.OCTOBER, -1, Calendar.SUNDAY, 7200000, 3600000);
- GregorianCalendar gc = new GregorianCalendar(1998, Calendar.JUNE, 11);
-
- assertTrue("Returned incorrect daylight value1", zone.inDaylightTime(gc
- .getTime()));
- gc = new GregorianCalendar(1998, Calendar.NOVEMBER, 11);
- assertTrue("Returned incorrect daylight value2", !(zone
- .inDaylightTime(gc.getTime())));
- gc = new GregorianCalendar(zone);
- gc.set(1999, Calendar.APRIL, 4, 1, 59, 59);
- assertTrue("Returned incorrect daylight value3", !(zone
- .inDaylightTime(gc.getTime())));
- Date date = new Date(gc.getTime().getTime() + 1000);
- assertTrue("Returned incorrect daylight value4", zone
- .inDaylightTime(date));
- gc.set(1999, Calendar.OCTOBER, 31, 1, 0, 0);
- assertTrue("Returned incorrect daylight value5", !(zone
- .inDaylightTime(gc.getTime())));
- date = new Date(gc.getTime().getTime() - 1000);
- assertTrue("Returned incorrect daylight value6", zone
- .inDaylightTime(date));
-
- assertTrue("Returned incorrect daylight value7", !zone
- .inDaylightTime(new Date(891752400000L + 7200000 - 1)));
- assertTrue("Returned incorrect daylight value8", zone
- .inDaylightTime(new Date(891752400000L + 7200000)));
- assertTrue("Returned incorrect daylight value9", zone
- .inDaylightTime(new Date(909288000000L + 7200000 - 1)));
- assertTrue("Returned incorrect daylight value10", !zone
- .inDaylightTime(new Date(909288000000L + 7200000)));
- }
-
- /**
- * @tests java.util.SimpleTimeZone#setDSTSavings(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setDSTSavings",
- args = {int.class}
- )
- public void test_setDSTSavingsI() {
- // Test for method void java.util.SimpleTimeZone.setDSTSavings(int)
- SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
- st.setStartRule(0, 1, 1, 1);
- st.setEndRule(11, 1, 1, 1);
- st.setDSTSavings(1);
- assertEquals("Daylight savings amount not set", 1, st.getDSTSavings());
- }
-
- /**
- * @tests java.util.SimpleTimeZone#setEndRule(int, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setEndRule",
- args = {int.class, int.class, int.class}
- )
- public void test_setEndRuleIII() {
- SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
- st.setStartRule(Calendar.NOVEMBER, 1, 0);
- st.setEndRule(Calendar.NOVEMBER, 20, 0);
- assertTrue("StartRule improperly set1", st.useDaylightTime());
- assertTrue("StartRule improperly set2", st.inDaylightTime(
- new GregorianCalendar(1998, Calendar.NOVEMBER,
- 13).getTime()));
- assertTrue("StartRule improperly set3", !(st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
- 13).getTime())));
-
- try {
- st.setEndRule(13, 20, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setEndRule(1, 32, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setEndRule(1, 30, 10);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @tests java.util.SimpleTimeZone#setEndRule(int, int, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setEndRule",
- args = {int.class, int.class, int.class, int.class}
- )
- public void test_setEndRuleIIII() {
- // Test for method void java.util.SimpleTimeZone.setEndRule(int, int,
- // int, int)
- SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
- // Spec indicates that both end and start must be set or result is
- // undefined
- st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0);
- st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, 0);
- assertTrue("StartRule improperly set1", st.useDaylightTime());
- assertTrue("StartRule improperly set2", st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.NOVEMBER,
- 13).getTime()));
- assertTrue("StartRule improperly set3", !(st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
- 13).getTime())));
-
- try {
- st.setEndRule(12, -1, Calendar.SUNDAY, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setEndRule(Calendar.NOVEMBER, 10, Calendar.SUNDAY, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setEndRule(Calendar.NOVEMBER, -1, 8, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, -10);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @tests java.util.SimpleTimeZone#setEndRule(int, int, int, int, boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setEndRule",
- args = {int.class, int.class, int.class, int.class, boolean.class}
- )
- public void test_setEndRuleIIIIZ() {
- // Test for method void java.util.SimpleTimeZone.setEndRule(int, int,
- // int, int, boolean)
- SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
- // Spec indicates that both end and start must be set or result is
- // undefined
- st.setStartRule(Calendar.NOVEMBER, 8, Calendar.SUNDAY, 1, false);
- st.setEndRule(Calendar.NOVEMBER, 15, Calendar.SUNDAY, 1, true);
- assertTrue("StartRule improperly set1", st.useDaylightTime());
- assertTrue("StartRule improperly set2", st
- .inDaylightTime((new GregorianCalendar(1999, Calendar.NOVEMBER,
- 7, 12, 0).getTime())));
- assertTrue("StartRule improperly set3", st
- .inDaylightTime((new GregorianCalendar(1999, Calendar.NOVEMBER,
- 20, 12, 0).getTime())));
- assertTrue("StartRule improperly set4", !(st
- .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER,
- 6, 12, 0).getTime())));
- assertTrue("StartRule improperly set5", !(st
- .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER,
- 21, 12, 0).getTime())));
-
- try {
- st.setEndRule(20, 15, Calendar.SUNDAY, 1, true);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setEndRule(Calendar.NOVEMBER, 35, Calendar.SUNDAY, 1, true);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setEndRule(Calendar.NOVEMBER, 15, 12, 1, true);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setEndRule(Calendar.NOVEMBER, 15, Calendar.SUNDAY, -1, true);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @tests java.util.SimpleTimeZone#setRawOffset(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setRawOffset",
- args = {int.class}
- )
- public void test_setRawOffsetI() {
- // Test for method void java.util.SimpleTimeZone.setRawOffset(int)
-
- st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
- int off = st1.getRawOffset();
- st1.setRawOffset(1000);
- boolean val = st1.getRawOffset() == 1000;
- st1.setRawOffset(off);
- assertTrue("Incorrect offset set", val);
- }
-
- /**
- * @tests java.util.SimpleTimeZone#setStartRule(int, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setStartRule",
- args = {int.class, int.class, int.class}
- )
- public void test_setStartRuleIII() {
- // Test for method void java.util.SimpleTimeZone.setStartRule(int, int,
- // int)
- SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
- // Spec indicates that both end and start must be set or result is
- // undefined
- st.setStartRule(Calendar.NOVEMBER, 1, 1);
- st.setEndRule(Calendar.DECEMBER, 1, 1);
- assertTrue("StartRule improperly set", st.useDaylightTime());
- assertTrue("StartRule improperly set", st
- .inDaylightTime((new GregorianCalendar(1998, Calendar.NOVEMBER,
- 13).getTime())));
- assertTrue("StartRule improperly set", !(st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
- 13).getTime())));
-
- try {
- st.setStartRule(13, 20, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setStartRule(1, 32, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setStartRule(1, 30, 10);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @tests java.util.SimpleTimeZone#setStartRule(int, int, int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setStartRule",
- args = {int.class, int.class, int.class, int.class}
- )
- public void test_setStartRuleIIII() {
- // Test for method void java.util.SimpleTimeZone.setStartRule(int, int,
- // int, int)
- SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
- // Spec indicates that both end and start must be set or result is
- // undefined
- st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0);
- st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, 0);
- assertTrue("StartRule improperly set1", st.useDaylightTime());
- assertTrue("StartRule improperly set2", st
- .inDaylightTime((new GregorianCalendar(1998, Calendar.NOVEMBER,
- 13).getTime())));
- assertTrue("StartRule improperly set3", !(st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
- 13).getTime())));
-
- try {
- st.setStartRule(12, -1, Calendar.SUNDAY, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setStartRule(Calendar.NOVEMBER, 10, Calendar.SUNDAY, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setStartRule(Calendar.NOVEMBER, -1, 8, 0);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setStartRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, -10);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @tests java.util.SimpleTimeZone#setStartRule(int, int, int, int, boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setStartRule",
- args = {int.class, int.class, int.class, int.class, boolean.class}
- )
- public void test_setStartRuleIIIIZ() {
- // Test for method void java.util.SimpleTimeZone.setStartRule(int, int,
- // int, int, boolean)
- SimpleTimeZone st = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
- // Spec indicates that both end and start must be set or result is
- // undefined
- st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 1, true);
- st.setEndRule(Calendar.NOVEMBER, 15, Calendar.SUNDAY, 1, false);
- assertTrue("StartRule improperly set1", st.useDaylightTime());
- assertTrue("StartRule improperly set2", st
- .inDaylightTime((new GregorianCalendar(1999, Calendar.NOVEMBER,
- 7, 12, 0).getTime())));
- assertTrue("StartRule improperly set3", st
- .inDaylightTime((new GregorianCalendar(1999, Calendar.NOVEMBER,
- 13, 12, 0).getTime())));
- assertTrue("StartRule improperly set4", !(st
- .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER,
- 6, 12, 0).getTime())));
- assertTrue("StartRule improperly set5", !(st
- .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER,
- 14, 12, 0).getTime())));
-
- try {
- st.setStartRule(20, 15, Calendar.SUNDAY, 1, true);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setStartRule(Calendar.NOVEMBER, 35, Calendar.SUNDAY, 1, true);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setStartRule(Calendar.NOVEMBER, 15, 12, 1, true);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- st.setStartRule(Calendar.NOVEMBER, 15, Calendar.SUNDAY, -1, true);
- fail("IllegalArgumentException is not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @tests java.util.SimpleTimeZone#setStartYear(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setStartYear",
- args = {int.class}
- )
- public void test_setStartYearI() {
- // Test for method void java.util.SimpleTimeZone.setStartYear(int)
- SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
- st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0);
- st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, 0);
- st.setStartYear(1999);
- assertTrue("set year improperly set1", !(st
- .inDaylightTime(new GregorianCalendar(1999, Calendar.JULY, 12)
- .getTime())));
- assertTrue("set year improperly set2", !(st
- .inDaylightTime(new GregorianCalendar(1998, Calendar.OCTOBER,
- 13).getTime())));
- assertTrue("set year improperly set3", (st
- .inDaylightTime(new GregorianCalendar(1999, Calendar.NOVEMBER,
- 13).getTime())));
- }
-
- /**
- * @tests java.util.SimpleTimeZone#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.util.SimpleTimeZone.toString()
- String string = TimeZone.getTimeZone("EST").toString();
- assertNotNull("toString() returned null", string);
- assertTrue("toString() is empty", string.length() != 0);
- }
-
- /**
- * @tests java.util.SimpleTimeZone#useDaylightTime()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "useDaylightTime",
- args = {}
- )
- public void test_useDaylightTime() {
- // Test for method boolean java.util.SimpleTimeZone.useDaylightTime()
- SimpleTimeZone st = new SimpleTimeZone(1000, "Test_TZ");
- assertTrue("useDaylightTime returned incorrect value", !st
- .useDaylightTime());
- // Spec indicates that both end and start must be set or result is
- // undefined
- st.setStartRule(Calendar.NOVEMBER, 1, Calendar.SUNDAY, 0);
- st.setEndRule(Calendar.NOVEMBER, -1, Calendar.SUNDAY, 0);
- assertTrue("useDaylightTime returned incorrect value", st
- .useDaylightTime());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getOffset",
- args = {long.class}
- )
- public void test_getOffsetJ() {
- Calendar cal = Calendar.getInstance();
- cal.set(1998, Calendar.NOVEMBER, 11, 0, 0);
- st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
-
- assertTrue("Incorrect offset returned", st1.getOffset(cal.getTimeInMillis()) ==
- -(5 * 60 * 60 * 1000));
-
- st1 = new SimpleTimeZone(TimeZone.getTimeZone("EST").getRawOffset(), "EST");
- cal.set(1998, Calendar.JUNE, 11, 0, 0);
- assertEquals("Incorrect offset returned", -(5 * 60 * 60 * 1000), st1
- .getOffset(cal.getTimeInMillis()));
-
- // Regression for HARMONY-5459
- st1 = new SimpleTimeZone(TimeZone.getDefault().getRawOffset(), TimeZone.getDefault().getID());
- int fourHours = 4*60*60*1000;
- st1.setRawOffset(fourHours);
- cal.set(2099, 01, 1, 0, 0);
-
- assertEquals(fourHours, st1.getOffset(cal.getTimeInMillis()));
-
- }
-
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/StackTest.java b/luni/src/test/java/tests/api/java/util/StackTest.java
deleted file mode 100644
index 46008c6..0000000
--- a/luni/src/test/java/tests/api/java/util/StackTest.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.EmptyStackException;
-import java.util.Stack;
-
-@TestTargetClass(Stack.class)
-public class StackTest extends junit.framework.TestCase {
-
- Stack s;
-
- /**
- * @tests java.util.Stack#Stack()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Stack",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.Stack()
- assertEquals("Stack creation failed", 0, s.size());
- }
-
- /**
- * @tests java.util.Stack#empty()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "empty",
- args = {}
- )
- public void test_empty() {
- // Test for method boolean java.util.Stack.empty()
- assertTrue("New stack answers non-empty", s.empty());
- s.push("blah");
- assertTrue("Stack should not be empty but answers empty", !s.empty());
- s.pop();
- assertTrue("Stack should be empty but answers non-empty", s.empty());
- s.push(null);
- assertTrue("Stack with null should not be empty but answers empty", !s
- .empty());
- }
-
- /**
- * @tests java.util.Stack#peek()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "peek",
- args = {}
- )
- public void test_peek() {
- // Test for method java.lang.Object java.util.Stack.peek()
- String item1 = "Ichi";
- String item2 = "Ni";
- String item3 = "San";
- s.push(item1);
- assertTrue("Peek did not return top item when it was the only item", s
- .peek() == item1);
- s.push(item2);
- s.push(item3);
- assertTrue("Peek did not return top item amoung many other items", s
- .peek() == item3);
- s.pop();
- assertTrue("Peek did not return top item after a pop", s.pop() == item2);
- s.push(null);
- assertNull("Peek did not return top item (wanted: null)",
- s.peek());
- s.pop();
- s.pop();
- try {
- s.pop();
- fail("EmptyStackException expected");
- } catch (EmptyStackException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Stack#pop()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "pop",
- args = {}
- )
- public void test_pop() {
- // Test for method java.lang.Object java.util.Stack.pop()
- String item1 = "Ichi";
- String item2 = "Ni";
- Object lastPopped;
- s.push(item1);
- s.push(item2);
-
- try {
- lastPopped = s.pop();
- assertTrue("a) Pop did not return top item", lastPopped == item2);
- } catch (EmptyStackException e) {
- fail(
- "a) Pop threw EmptyStackException when stack should not have been empty");
- }
-
- try {
- lastPopped = s.pop();
- assertTrue("b) Pop did not return top item", lastPopped == item1);
- } catch (EmptyStackException e) {
- fail(
- "b) Pop threw EmptyStackException when stack should not have been empty");
- }
-
- s.push(null);
- try {
- lastPopped = s.pop();
- assertNull("c) Pop did not return top item", lastPopped);
- } catch (EmptyStackException e) {
- fail(
- "c) Pop threw EmptyStackException when stack should not have been empty");
- }
-
- try {
- lastPopped = s.pop();
- fail(
- "d) Pop did not throw EmptyStackException when stack should have been empty");
- } catch (EmptyStackException e) {
- return;
- }
-
- }
-
- /**
- * @tests java.util.Stack#push(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "push",
- args = {java.lang.Object.class}
- )
- public void test_pushLjava_lang_Object() {
- Object [] array = {new Integer(0), new Object(),
- new Float(0), new String()};
-
- Stack<Object> stack = new Stack<Object>();
- for(int i = 0; i < array.length; i++) {
- stack.push(array[i]);
- }
- for(int i = 0; i < array.length; i++) {
- assertEquals(array.length - i, stack.search(array[i]));
- }
- }
-
- /**
- * @tests java.util.Stack#search(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "search",
- args = {java.lang.Object.class}
- )
- public void test_searchLjava_lang_Object() {
- // Test for method int java.util.Stack.search(java.lang.Object)
- String item1 = "Ichi";
- String item2 = "Ni";
- String item3 = "San";
- s.push(item1);
- s.push(item2);
- s.push(item3);
- assertEquals("Search returned incorrect value for equivalent object", 3, s
- .search(item1));
- assertEquals("Search returned incorrect value for equal object", 3, s
- .search("Ichi"));
- s.pop();
- assertEquals("Search returned incorrect value for equivalent object at top of stack",
- 1, s.search(item2));
- assertEquals("Search returned incorrect value for equal object at top of stack",
- 1, s.search("Ni"));
- s.push(null);
- assertEquals("Search returned incorrect value for search for null at top of stack",
- 1, s.search(null));
- s.push("Shi");
- assertEquals("Search returned incorrect value for search for null", 2, s
- .search(null));
- s.pop();
- s.pop();
- assertEquals("Search returned incorrect value for search for null--wanted -1",
- -1, s.search(null));
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- s = new Stack();
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/StringTokenizerTest.java b/luni/src/test/java/tests/api/java/util/StringTokenizerTest.java
deleted file mode 100644
index a7ba8da..0000000
--- a/luni/src/test/java/tests/api/java/util/StringTokenizerTest.java
+++ /dev/null
@@ -1,285 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.NoSuchElementException;
-import java.util.StringTokenizer;
-
-@TestTargetClass(StringTokenizer.class)
-public class StringTokenizerTest extends junit.framework.TestCase {
-
- /**
- * @tests java.util.StringTokenizer#StringTokenizer(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StringTokenizer",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.util.StringTokenizer(java.lang.String)
- try {
- new StringTokenizer(null);
- fail("NullPointerException is not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- /**
- * @tests java.util.StringTokenizer#StringTokenizer(java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StringTokenizer",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_String() {
- // Test for method java.util.StringTokenizer(java.lang.String,
- // java.lang.String)
- StringTokenizer st = new StringTokenizer("This:is:a:test:String", ":");
- assertTrue("Created incorrect tokenizer", st.countTokens() == 5
- && (st.nextElement().equals("This")));
- st = new StringTokenizer("This:is:a:test:String", null);
-
- try {
- new StringTokenizer(null, ":");
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.StringTokenizer#StringTokenizer(java.lang.String,
- * java.lang.String, boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "StringTokenizer",
- args = {java.lang.String.class, java.lang.String.class, boolean.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_StringZ() {
- // Test for method java.util.StringTokenizer(java.lang.String,
- // java.lang.String, boolean)
- StringTokenizer st = new StringTokenizer("This:is:a:test:String", ":",
- true);
- st.nextElement();
- assertTrue("Created incorrect tokenizer", st.countTokens() == 8
- && (st.nextElement().equals(":")));
- st = new StringTokenizer("This:is:a:test:String", null, true);
- st = new StringTokenizer("This:is:a:test:String", null, false);
-
- try {
- new StringTokenizer(null, ":", true);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.StringTokenizer#countTokens()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "countTokens",
- args = {}
- )
- public void test_countTokens() {
- // Test for method int java.util.StringTokenizer.countTokens()
- StringTokenizer st = new StringTokenizer("This is a test String");
-
- assertEquals("Incorrect token count returned", 5, st.countTokens());
- }
-
- /**
- * @tests java.util.StringTokenizer#hasMoreElements()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasMoreElements",
- args = {}
- )
- public void test_hasMoreElements() {
- // Test for method boolean java.util.StringTokenizer.hasMoreElements()
-
- StringTokenizer st = new StringTokenizer("This is a test String");
- st.nextElement();
- assertTrue("hasMoreElements returned incorrect value", st
- .hasMoreElements());
- st.nextElement();
- st.nextElement();
- st.nextElement();
- st.nextElement();
- assertTrue("hasMoreElements returned incorrect value", !st
- .hasMoreElements());
- }
-
- /**
- * @tests java.util.StringTokenizer#hasMoreTokens()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasMoreTokens",
- args = {}
- )
- public void test_hasMoreTokens() {
- // Test for method boolean java.util.StringTokenizer.hasMoreTokens()
- StringTokenizer st = new StringTokenizer("This is a test String");
- for (int counter = 0; counter < 5; counter++) {
- assertTrue(
- "StringTokenizer incorrectly reports it has no more tokens",
- st.hasMoreTokens());
- st.nextToken();
- }
- assertTrue("StringTokenizer incorrectly reports it has more tokens",
- !st.hasMoreTokens());
- }
-
- /**
- * @tests java.util.StringTokenizer#nextElement()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextElement",
- args = {}
- )
- public void test_nextElement() {
- // Test for method java.lang.Object
- // java.util.StringTokenizer.nextElement()
- StringTokenizer st = new StringTokenizer("This is a test String");
- assertEquals("nextElement returned incorrect value", "This", ((String) st
- .nextElement()));
- assertEquals("nextElement returned incorrect value", "is", ((String) st
- .nextElement()));
- assertEquals("nextElement returned incorrect value", "a", ((String) st
- .nextElement()));
- assertEquals("nextElement returned incorrect value", "test", ((String) st
- .nextElement()));
- assertEquals("nextElement returned incorrect value", "String", ((String) st
- .nextElement()));
- try {
- st.nextElement();
- fail(
- "nextElement failed to throw a NoSuchElementException when it should have been out of elements");
- } catch (NoSuchElementException e) {
- return;
- }
- }
-
- /**
- * @tests java.util.StringTokenizer#nextToken()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextToken",
- args = {}
- )
- public void test_nextToken() {
- // Test for method java.lang.String
- // java.util.StringTokenizer.nextToken()
- StringTokenizer st = new StringTokenizer("This is a test String");
- assertEquals("nextToken returned incorrect value",
- "This", st.nextToken());
- assertEquals("nextToken returned incorrect value",
- "is", st.nextToken());
- assertEquals("nextToken returned incorrect value",
- "a", st.nextToken());
- assertEquals("nextToken returned incorrect value",
- "test", st.nextToken());
- assertEquals("nextToken returned incorrect value",
- "String", st.nextToken());
- try {
- st.nextToken();
- fail(
- "nextToken failed to throw a NoSuchElementException when it should have been out of elements");
- } catch (NoSuchElementException e) {
- return;
- }
- }
-
- /**
- * @tests java.util.StringTokenizer#nextToken(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "nextToken",
- args = {java.lang.String.class}
- )
- public void test_nextTokenLjava_lang_String() {
- // Test for method java.lang.String
- // java.util.StringTokenizer.nextToken(java.lang.String)
- StringTokenizer st = new StringTokenizer("This is a test String");
- assertEquals("nextToken(String) returned incorrect value with normal token String",
- "This", st.nextToken(" "));
- assertEquals("nextToken(String) returned incorrect value with custom token String",
- " is a ", st.nextToken("tr"));
- assertEquals("calling nextToken() did not use the new default delimiter list",
- "es", st.nextToken());
- st = new StringTokenizer("This:is:a:test:String", " ");
- assertTrue(st.nextToken(":").equals("This"));
- assertTrue(st.nextToken(":").equals("is"));
- assertTrue(st.nextToken(":").equals("a"));
- assertTrue(st.nextToken(":").equals("test"));
- assertTrue(st.nextToken(":").equals("String"));
-
- try {
- st.nextToken(":");
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
-
- try {
- st.nextToken(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/TimeZoneTest.java b/luni/src/test/java/tests/api/java/util/TimeZoneTest.java
deleted file mode 100644
index 87a5e87..0000000
--- a/luni/src/test/java/tests/api/java/util/TimeZoneTest.java
+++ /dev/null
@@ -1,401 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.AndroidOnly;
-
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.Locale;
-import java.util.SimpleTimeZone;
-import java.util.TimeZone;
-
-import tests.support.Support_TimeZone;
-
-@TestTargetClass(TimeZone.class)
-public class TimeZoneTest extends junit.framework.TestCase {
-
- private static final int ONE_HOUR = 3600000;
-
- /**
- * @tests java.util.TimeZone#getDefault()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDefault",
- args = {}
- )
- public void test_getDefault() {
- assertNotSame("returns identical",
- TimeZone.getDefault(), TimeZone.getDefault());
- }
-
- /**
- * @tests java.util.TimeZone#getDSTSavings()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDSTSavings",
- args = {}
- )
- @KnownFailure("method returns wrong time shift")
- public void test_getDSTSavings() {
- // Test for method int java.util.TimeZone.getDSTSavings()
-
- // test on subclass SimpleTimeZone
- TimeZone st1 = TimeZone.getTimeZone("America/New_York");
- assertEquals("T1A. Incorrect daylight savings returned",
- ONE_HOUR, st1.getDSTSavings());
-
- // a SimpleTimeZone with daylight savings different then 1 hour
- st1 = TimeZone.getTimeZone("Australia/Lord_Howe");
- assertEquals("T1B. Incorrect daylight savings returned",
- 1800000, st1.getDSTSavings());
-
- // test on subclass Support_TimeZone, an instance with daylight savings
- TimeZone tz1 = new Support_TimeZone(-5 * ONE_HOUR, true);
- assertEquals("T2. Incorrect daylight savings returned",
- ONE_HOUR, tz1.getDSTSavings());
-
- // an instance without daylight savings
- tz1 = new Support_TimeZone(3 * ONE_HOUR, false);
- assertEquals("T3. Incorrect daylight savings returned, ",
- 0, tz1.getDSTSavings());
- }
-
- /**
- * @tests java.util.TimeZone#getOffset(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getOffset",
- args = {long.class}
- )
- public void test_getOffset_long() {
- // Test for method int java.util.TimeZone.getOffset(long time)
-
- // test on subclass SimpleTimeZone
- TimeZone st1 = TimeZone.getTimeZone("EST");
- long time1 = new GregorianCalendar(1998, Calendar.NOVEMBER, 11)
- .getTimeInMillis();
- assertEquals("T1. Incorrect offset returned",
- -(5 * ONE_HOUR), st1.getOffset(time1));
-
- long time2 = new GregorianCalendar(1998, Calendar.JUNE, 11)
- .getTimeInMillis();
-// Not working as expected on RI.
-// st1 = TimeZone.getTimeZone("EST");
-// assertEquals("T2. Incorrect offset returned",
-// -(4 * ONE_HOUR), st1.getOffset(time2));
-
- // test on subclass Support_TimeZone, an instance with daylight savings
- TimeZone tz1 = new Support_TimeZone(-5 * ONE_HOUR, true);
- assertEquals("T3. Incorrect offset returned, ",
- -(5 * ONE_HOUR), tz1.getOffset(time1));
- assertEquals("T4. Incorrect offset returned, ",
- -(4 * ONE_HOUR), tz1.getOffset(time2));
-
- // an instance without daylight savings
- tz1 = new Support_TimeZone(3 * ONE_HOUR, false);
- assertEquals("T5. Incorrect offset returned, ",
- (3 * ONE_HOUR), tz1.getOffset(time1));
- assertEquals("T6. Incorrect offset returned, ",
- (3 * ONE_HOUR), tz1.getOffset(time2));
- }
-
- /**
- * @tests java.util.TimeZone#getTimeZone(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTimeZone",
- args = {java.lang.String.class}
- )
- public void test_getTimeZoneLjava_lang_String() {
- assertEquals("Must return GMT when given an invalid TimeZone id SMT-8.",
- "GMT", TimeZone.getTimeZone("SMT-8").getID());
- assertEquals("Must return GMT when given an invalid TimeZone time GMT+28:70.",
- "GMT", TimeZone.getTimeZone("GMT+28:70").getID());
- assertEquals("Must return GMT when given an invalid TimeZone time GMT+28:30.",
- "GMT", TimeZone.getTimeZone("GMT+28:30").getID());
- assertEquals("Must return GMT when given an invalid TimeZone time GMT+8:70.",
- "GMT", TimeZone.getTimeZone("GMT+8:70").getID());
- assertEquals("Must return GMT when given an invalid TimeZone time GMT+3:.",
- "GMT", TimeZone.getTimeZone("GMT+3:").getID());
- assertEquals("Must return GMT when given an invalid TimeZone time GMT+3:0.",
- "GMT", TimeZone.getTimeZone("GMT+3:0").getID());
- assertEquals("Must return GMT when given an invalid TimeZone time GMT+2360.",
- "GMT", TimeZone.getTimeZone("GMT+2360").getID());
- assertEquals("Must return GMT when given an invalid TimeZone time GMT+892.",
- "GMT", TimeZone.getTimeZone("GMT+892").getID());
- assertEquals("Must return GMT when given an invalid TimeZone time GMT+082.",
- "GMT", TimeZone.getTimeZone("GMT+082").getID());
- assertEquals("Must return GMT when given an invalid TimeZone time GMT+28.",
- "GMT", TimeZone.getTimeZone("GMT+28").getID());
- assertEquals("Must return GMT when given an invalid TimeZone time GMT+30.",
- "GMT", TimeZone.getTimeZone("GMT+30").getID());
- assertEquals("Must return GMT when given TimeZone GMT.",
- "GMT", TimeZone.getTimeZone("GMT").getID());
- assertEquals("Must return GMT when given TimeZone GMT+.",
- "GMT", TimeZone.getTimeZone("GMT+").getID());
- assertEquals("Must return GMT when given TimeZone GMT-.",
- "GMT", TimeZone.getTimeZone("GMT-").getID());
- assertEquals("Must return GMT when given an invalid TimeZone time GMT-8.45.",
- "GMT", TimeZone.getTimeZone("GMT-8.45").getID());
- assertEquals("Must return GMT when given an invalid TimeZone time GMT-123:23.",
- "GMT", TimeZone.getTimeZone("GMT-123:23").getID());
- assertEquals("Must return proper GMT formatted string for GMT+8:30 (eg. GMT+08:20).",
- "GMT+08:30", TimeZone.getTimeZone("GMT+8:30").getID());
- assertEquals("Must return proper GMT formatted string for GMT+3 (eg. GMT+08:20).",
- "GMT+03:00", TimeZone.getTimeZone("GMT+3").getID());
- assertEquals("Must return proper GMT formatted string for GMT+3:02 (eg. GMT+08:20).",
- "GMT+03:02", TimeZone.getTimeZone("GMT+3:02").getID());
- assertEquals("Must return proper GMT formatted string for GMT+2359 (eg. GMT+08:20).",
- "GMT+23:59", TimeZone.getTimeZone("GMT+2359").getID());
- assertEquals("Must return proper GMT formatted string for GMT+520 (eg. GMT+08:20).",
- "GMT+05:20", TimeZone.getTimeZone("GMT+520").getID());
- assertEquals("Must return proper GMT formatted string for GMT+052 (eg. GMT+08:20).",
- "GMT+00:52", TimeZone.getTimeZone("GMT+052").getID());
- assertEquals("Must return proper GMT formatted string for GMT-0 (eg. GMT+08:20).",
- "GMT-00:00", TimeZone.getTimeZone("GMT-0").getID());
- }
-
- /**
- * @tests java.util.TimeZone#setDefault(java.util.TimeZone)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setDefault",
- args = {java.util.TimeZone.class}
- )
- public void test_setDefaultLjava_util_TimeZone() {
- TimeZone oldDefault = TimeZone.getDefault();
- TimeZone zone = new SimpleTimeZone(45, "TEST");
- TimeZone.setDefault(zone);
- assertEquals("timezone not set", zone, TimeZone.getDefault());
- TimeZone.setDefault(null);
- assertEquals("default not restored",
- oldDefault, TimeZone.getDefault());
- }
-
- class Mock_TimeZone extends TimeZone {
- @Override
- public int getOffset(int era, int year, int month, int day, int dayOfWeek, int milliseconds) {
- return 0;
- }
-
- @Override
- public int getRawOffset() {
- return 0;
- }
-
- @Override
- public boolean inDaylightTime(Date date) {
- return false;
- }
-
- @Override
- public void setRawOffset(int offsetMillis) {
-
- }
-
- @Override
- public boolean useDaylightTime() {
- return false;
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TimeZone",
- args = {}
- )
- public void test_constructor() {
- assertNotNull(new Mock_TimeZone());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- TimeZone tz1 = TimeZone.getDefault();
- TimeZone tz2 = (TimeZone)tz1.clone();
-
- assertTrue(tz1.equals(tz2));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAvailableIDs",
- args = {}
- )
- public void test_getAvailableIDs() {
- String[] str = TimeZone.getAvailableIDs();
- assertNotNull(str);
- assertTrue(str.length != 0);
- for(int i = 0; i < str.length; i++) {
- assertNotNull(TimeZone.getTimeZone(str[i]));
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAvailableIDs",
- args = {int.class}
- )
- public void test_getAvailableIDsI() {
- String[] str = TimeZone.getAvailableIDs(0);
- assertNotNull(str);
- assertTrue(str.length != 0);
- for(int i = 0; i < str.length; i++) {
- assertNotNull(TimeZone.getTimeZone(str[i]));
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDisplayName",
- args = {}
- )
- public void test_getDisplayName() {
- TimeZone tz = TimeZone.getTimeZone("GMT-6");
- assertEquals("GMT-06:00", tz.getDisplayName());
- tz = TimeZone.getTimeZone("America/Los_Angeles");
- assertEquals("Pacific Standard Time", tz.getDisplayName());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDisplayName",
- args = {java.util.Locale.class}
- )
- public void test_getDisplayNameLjava_util_Locale() {
- TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
- assertEquals("Pacific Standard Time", tz.getDisplayName(new Locale("US")));
- assertEquals("Heure normale du Pacifique", tz.getDisplayName(Locale.FRANCE));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDisplayName",
- args = {boolean.class, int.class}
- )
- public void test_getDisplayNameZI() {
- TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
- assertEquals("PST", tz.getDisplayName(false, 0));
- assertEquals("Pacific Daylight Time", tz.getDisplayName(true, 1));
- assertEquals("Pacific Standard Time", tz.getDisplayName(false, 1));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDisplayName",
- args = {boolean.class, int.class, java.util.Locale.class}
- )
- @AndroidOnly("fail on RI. See comment below")
- public void test_getDisplayNameZILjava_util_Locale() {
- TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
- assertEquals("PST", tz.getDisplayName(false, 0, Locale.US));
- assertEquals("Pacific Daylight Time", tz.getDisplayName(true, 1, Locale.US));
- assertEquals("Pacific Standard Time", tz.getDisplayName(false, 1, Locale.UK));
- //RI fails on following line. RI always returns short time zone name as "PST"
- assertEquals("HMG-08:00", tz.getDisplayName(false, 0, Locale.FRANCE));
- assertEquals("Heure avanc\u00e9e du Pacifique", tz.getDisplayName(true, 1, Locale.FRANCE));
- assertEquals("Heure normale du Pacifique", tz.getDisplayName(false, 1, Locale.FRANCE));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getID",
- args = {}
- )
- public void test_getID() {
- TimeZone tz = TimeZone.getTimeZone("GMT-6");
- assertEquals("GMT-06:00", tz.getID());
- tz = TimeZone.getTimeZone("America/Denver");
- assertEquals("America/Denver", tz.getID());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hasSameRules",
- args = {java.util.TimeZone.class}
- )
- @KnownFailure("Arizona doesn't observe DST")
- public void test_hasSameRulesLjava_util_TimeZone() {
- TimeZone tz1 = TimeZone.getTimeZone("America/Denver");
- TimeZone tz2 = TimeZone.getTimeZone("America/Phoenix");
- assertEquals(tz1.getDisplayName(false, 0), tz2.getDisplayName(false, 0));
- // Arizona doesn't observe DST. See http://phoenix.about.com/cs/weather/qt/timezone.htm
- assertFalse(tz1.hasSameRules(tz2));
- assertFalse(tz1.hasSameRules(null));
- tz1 = TimeZone.getTimeZone("America/Montreal");
- tz2 = TimeZone.getTimeZone("America/New_York");
- assertEquals(tz1.getDisplayName(), tz2.getDisplayName());
- assertFalse(tz1.getID().equals(tz2.getID()));
- assertTrue(tz2.hasSameRules(tz1));
- assertTrue(tz1.hasSameRules(tz1));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setID",
- args = {java.lang.String.class}
- )
- public void test_setIDLjava_lang_String() {
- TimeZone tz = TimeZone.getTimeZone("GMT-6");
- assertEquals("GMT-06:00", tz.getID());
- tz.setID("New ID for GMT-6");
- assertEquals("New ID for GMT-6", tz.getID());
- }
-
- Locale loc = null;
-
- protected void setUp() {
- loc = Locale.getDefault();
- Locale.setDefault(Locale.US);
- }
-
- protected void tearDown() {
- Locale.setDefault(loc);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/TimerTaskTest.java b/luni/src/test/java/tests/api/java/util/TimerTaskTest.java
deleted file mode 100644
index 961ad87..0000000
--- a/luni/src/test/java/tests/api/java/util/TimerTaskTest.java
+++ /dev/null
@@ -1,276 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.Timer;
-import java.util.TimerTask;
-
-@TestTargetClass(TimerTask.class)
-public class TimerTaskTest extends junit.framework.TestCase {
- Object sync = new Object(), start = new Object();
-
- /**
- * Warning: These tests have the possibility to leave a VM hanging if the
- * Timer is not cancelled.
- */
- class TimerTestTask extends TimerTask {
- private int wasRun = 0;
-
- // Set this to true to see normal tests fail (or hang possibly)
- // The default is false and needs to be set by some tests
- private boolean sleepInRun = false;
-
- public void run() {
- synchronized (this) {
- wasRun++;
- }
- synchronized (start) {
- start.notify();
- }
- if (sleepInRun) {
-
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- }
- }
- synchronized (sync) {
- sync.notify();
- }
- }
-
- public synchronized int wasRun() {
- return wasRun;
- }
-
- public void sleepInRun(boolean value) {
- sleepInRun = value;
- }
- }
-
- /**
- * @tests java.util.TimerTask#TimerTask()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TimerTask",
- args = {}
- )
- public void test_Constructor() {
- // Ensure the constructor does not fail
- new TimerTestTask();
- }
-
- /**
- * @tests java.util.TimerTask#cancel()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "cancel",
- args = {}
- )
- public void test_cancel() {
- Timer t = null;
- try {
- // Ensure cancel returns false if never scheduled
- TimerTestTask testTask = new TimerTestTask();
- assertTrue("Unsheduled tasks should return false for cancel()",
- !testTask.cancel());
-
- // Ensure cancelled task never runs
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 500);
- assertTrue("TimerTask should not have run yet", testTask.cancel());
- t.cancel();
-
- // Ensure cancelling a task which has already run returns true
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 50);
- while (testTask.wasRun() == 0) {
- try {
- Thread.sleep(150);
- } catch (InterruptedException e) {
- }
- }
- assertFalse(
- "TimerTask.cancel() should return false if task has run",
- testTask.cancel());
- assertFalse(
- "TimerTask.cancel() should return false if called a second time",
- testTask.cancel());
- t.cancel();
-
- // Ensure cancelling a repeated execution task which has never run
- // returns true
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 500, 500); // should never run
- assertTrue(
- "TimerTask.cancel() should return true if sheduled for repeated execution even if not run",
- testTask.cancel());
- t.cancel();
-
- // Ensure cancelling a repeated execution task which HAS run returns
- // true
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 50, 50);
- while (testTask.wasRun() == 0) {
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- }
- }
- assertTrue(
- "TimerTask.cancel() should return true if sheduled for repeated execution and run",
- testTask.cancel());
- t.cancel();
-
- // Ensure calling cancel a second returns false
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 5000); // Should never run
- assertTrue(
- "TimerTask.cancel() should return true if task has never run",
- testTask.cancel());
- assertFalse(
- "TimerTask.cancel() should return false if called a second time",
- testTask.cancel());
- t.cancel();
-
- // Ensure cancelling a task won't cause deadlock
- t = new Timer();
- testTask = new TimerTestTask();
- testTask.sleepInRun(true);
- synchronized (start) {
- t.schedule(testTask, 0);
- try {
- start.wait();
- Thread.sleep(50);
- } catch (InterruptedException e) {
- }
- }
- assertFalse("TimerTask should have been cancelled", testTask
- .cancel());
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
- }
-
- /**
- * @tests java.util.TimerTask#scheduledExecutionTime()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "scheduledExecutionTime",
- args = {}
- )
- public void test_scheduledExecutionTime() {
- Timer t = null;
- try {
- // Ensure scheduledExecutionTime is roughly right
- t = new Timer();
- TimerTestTask testTask = new TimerTestTask();
- t.schedule(testTask, 100);
- long time = System.currentTimeMillis() + 100;
- synchronized (sync) {
- try {
- sync.wait(500);
- } catch (InterruptedException e) {
- }
- }
- long scheduledExecutionTime = testTask.scheduledExecutionTime();
- assertTrue(scheduledExecutionTime <= time);
- t.cancel();
-
- // Ensure scheduledExecutionTime is the last scheduled time
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 100, 500);
- long estNow = System.currentTimeMillis() + 100;
- // Will wake in 100, and every 500 run again
- // We want to try to get it after it's run at least once but not
- // twice
- synchronized (sync) {
- try {
- sync.wait(500);
- } catch (InterruptedException e) {
- }
- }
- scheduledExecutionTime = testTask.scheduledExecutionTime();
- assertTrue(scheduledExecutionTime <= estNow);
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
-
- }
-
- /**
- * @tests java.util.TimerTask#run()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "run",
- args = {}
- )
- public void test_run() {
- Timer t = null;
- try {
- // Ensure a new task is never run
- TimerTestTask testTask = new TimerTestTask();
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- }
- assertEquals("TimerTask.run() method should not have been called",
- 0, testTask.wasRun());
-
- // Ensure a task is run
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 200);
- while(testTask.wasRun() < 1) {
- try {
- Thread.sleep(400);
- } catch (InterruptedException e) {
- }
- }
- assertFalse(testTask.cancel());
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
-
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/TimerTest.java b/luni/src/test/java/tests/api/java/util/TimerTest.java
deleted file mode 100644
index b47270e..0000000
--- a/luni/src/test/java/tests/api/java/util/TimerTest.java
+++ /dev/null
@@ -1,1273 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.Date;
-import java.util.Timer;
-import java.util.TimerTask;
-
-@TestTargetClass(Timer.class)
-public class TimerTest extends junit.framework.TestCase {
-
- int timerCounter = 0;
-
- Object sync = new Object();
-
- /**
- * Warning: These tests have the possibility to leave a VM hanging if the
- * Timer is not cancelled.
- */
- class TimerTestTask extends TimerTask {
- int wasRun = 0;
-
- // Should we sleep for 200 ms each run()?
- boolean sleepInRun = false;
-
- // Should we increment the timerCounter?
- boolean incrementCount = false;
-
- // Should we terminate the timer at a specific timerCounter?
- int terminateCount = -1;
-
- // The timer we belong to
- Timer timer = null;
-
- public TimerTestTask() {
- }
-
- public TimerTestTask(Timer t) {
- timer = t;
- }
-
- public void run() {
- synchronized (this) {
- wasRun++;
- }
- if (incrementCount)
- timerCounter++;
- if (terminateCount == timerCounter && timer != null)
- timer.cancel();
- if (sleepInRun) {
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- }
- }
- synchronized (sync) {
- sync.notify();
- }
- }
-
- public synchronized int wasRun() {
- return wasRun;
- }
-
- public void sleepInRun(boolean sleepInRun) {
- this.sleepInRun = sleepInRun;
- }
-
- public void incrementCount(boolean incrementCount) {
- this.incrementCount = incrementCount;
- }
-
- public void terminateCount(int terminateCount) {
- this.terminateCount = terminateCount;
- }
- }
-
- /**
- * @tests java.util.Timer#Timer(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Timer",
- args = {boolean.class}
- )
- public void test_ConstructorZ() {
- Timer t = null;
- try {
- // Ensure a task is run
- t = new Timer(true);
- TimerTestTask testTask = new TimerTestTask();
- t.schedule(testTask, 200);
- synchronized (sync) {
- try {
- sync.wait(1000);
- } catch (InterruptedException e) {
- }
- }
- assertEquals("TimerTask.run() method not called after 200ms",
- 1, testTask.wasRun());
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
-
- }
-
- /**
- * @tests java.util.Timer#Timer()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Timer",
- args = {}
- )
- public void test_Constructor() {
- Timer t = null;
- try {
- // Ensure a task is run
- t = new Timer();
- TimerTestTask testTask = new TimerTestTask();
- t.schedule(testTask, 200);
- synchronized (sync) {
- try {
- sync.wait(1000);
- } catch (InterruptedException e) {
- }
- }
- assertEquals("TimerTask.run() method not called after 200ms",
- 1, testTask.wasRun());
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
-
- }
-
- /**
- * @tests java.util.Timer#Timer(String, boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Timer",
- args = {java.lang.String.class, boolean.class}
- )
- public void test_ConstructorSZ() {
- Timer t = null;
- try {
- // Ensure a task is run
- t = new Timer("test_ConstructorSZThread", true);
- TimerTestTask testTask = new TimerTestTask();
- t.schedule(testTask, 200);
- synchronized (sync) {
- try {
- sync.wait(1000);
- } catch (InterruptedException e) {}
- }
- assertEquals("TimerTask.run() method not called after 200ms", 1,
- testTask.wasRun());
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
-
- try {
- new Timer(null, true);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- try {
- new Timer(null, false);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Timer#Timer(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Timer",
- args = {java.lang.String.class}
- )
- public void test_ConstructorS() {
- Timer t = null;
- try {
- // Ensure a task is run
- t = new Timer("test_ConstructorSThread");
- TimerTestTask testTask = new TimerTestTask();
- t.schedule(testTask, 200);
- synchronized (sync) {
- try {
- sync.wait(1000);
- } catch (InterruptedException e) {}
- }
- assertEquals("TimerTask.run() method not called after 200ms", 1,
- testTask.wasRun());
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
-
- try {
- new Timer(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Timer#cancel()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "cancel",
- args = {}
- )
- public void test_cancel() {
- Timer t = null;
- try {
- // Ensure a task throws an IllegalStateException after cancelled
- t = new Timer();
- TimerTestTask testTask = new TimerTestTask();
- t.cancel();
- boolean exception = false;
- try {
- t.schedule(testTask, 100, 200);
- } catch (IllegalStateException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a task after Timer.cancel() should throw exception",
- exception);
-
- // Ensure a task is run but not after cancel
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 100, 500);
- synchronized (sync) {
- try {
- sync.wait(1000);
- } catch (InterruptedException e) {
- }
- }
- assertEquals("TimerTask.run() method not called after 200ms",
- 1, testTask.wasRun());
- t.cancel();
- synchronized (sync) {
- try {
- sync.wait(500);
- } catch (InterruptedException e) {
- }
- }
- assertEquals("TimerTask.run() method should not have been called after cancel",
- 1, testTask.wasRun());
-
- // Ensure you can call cancel more than once
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 100, 500);
- synchronized (sync) {
- try {
- sync.wait(500);
- } catch (InterruptedException e) {
- }
- }
- assertEquals("TimerTask.run() method not called after 200ms",
- 1, testTask.wasRun());
- t.cancel();
- t.cancel();
- t.cancel();
- synchronized (sync) {
- try {
- sync.wait(500);
- } catch (InterruptedException e) {
- }
- }
- assertEquals("TimerTask.run() method should not have been called after cancel",
- 1, testTask.wasRun());
-
- // Ensure that a call to cancel from within a timer ensures no more
- // run
- t = new Timer();
- testTask = new TimerTestTask(t);
- testTask.incrementCount(true);
- testTask.terminateCount(5); // Terminate after 5 runs
- t.schedule(testTask, 100, 100);
- synchronized (sync) {
- try {
- sync.wait(200);
- sync.wait(200);
- sync.wait(200);
- sync.wait(200);
- sync.wait(200);
- sync.wait(200);
- } catch (InterruptedException e) {
- }
- }
- assertTrue("TimerTask.run() method should be called 5 times not "
- + testTask.wasRun(), testTask.wasRun() == 5);
- t.cancel();
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- }
- } finally {
- if (t != null)
- t.cancel();
- }
-
- }
-
- /**
- * @tests java.util.Timer#purge()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "purge",
- args = {}
- )
- public void test_purge() throws Exception {
- Timer t = null;
- try {
- t = new Timer();
- assertEquals(0, t.purge());
-
- TimerTestTask[] tasks = new TimerTestTask[100];
- int[] delayTime = { 50, 80, 20, 70, 40, 10, 90, 30, 60 };
-
- int j = 0;
- for (int i = 0; i < 100; i++) {
- tasks[i] = new TimerTestTask();
- t.schedule(tasks[i], delayTime[j++], 200);
- if (j == 9) {
- j = 0;
- }
- }
-
- for (int i = 0; i < 50; i++) {
- tasks[i].cancel();
- }
-
- assertTrue(t.purge() <= 50);
- assertEquals(0, t.purge());
- } finally {
- if (t != null) {
- t.cancel();
- }
- }
- }
-
- /**
- * @tests java.util.Timer#schedule(java.util.TimerTask, java.util.Date)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "schedule",
- args = {java.util.TimerTask.class, java.util.Date.class}
- )
- public void test_scheduleLjava_util_TimerTaskLjava_util_Date() {
- Timer t = null;
- try {
- // Ensure a Timer throws an IllegalStateException after cancelled
- t = new Timer();
- TimerTestTask testTask = new TimerTestTask();
- Date d = new Date(System.currentTimeMillis() + 100);
- t.cancel();
- boolean exception = false;
- try {
- t.schedule(testTask, d);
- } catch (IllegalStateException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a task after Timer.cancel() should throw exception",
- exception);
-
- // Ensure a Timer throws an IllegalStateException if task already
- // cancelled
- t = new Timer();
- testTask = new TimerTestTask();
- d = new Date(System.currentTimeMillis() + 100);
- testTask.cancel();
- exception = false;
- try {
- t.schedule(testTask, d);
- } catch (IllegalStateException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a task after cancelling it should throw exception",
- exception);
- t.cancel();
-
- // Ensure a Timer throws an IllegalArgumentException if delay is
- // negative
- t = new Timer();
- testTask = new TimerTestTask();
- d = new Date(-100);
- exception = false;
- try {
- t.schedule(testTask, d);
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a task with negative date should throw IllegalArgumentException",
- exception);
- t.cancel();
-
- // Ensure a Timer throws a NullPointerException if the task is null
- t = new Timer();
- exception = false;
- d = new Date(System.currentTimeMillis() + 100);
- try {
- t.schedule(null, d);
- } catch (NullPointerException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a null task should throw NullPointerException",
- exception);
- t.cancel();
-
- // Ensure a Timer throws a NullPointerException if the date is null
- t = new Timer();
- testTask = new TimerTestTask();
- exception = false;
- try {
- t.schedule(testTask, null);
- } catch (NullPointerException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a null date should throw NullPointerException",
- exception);
- t.cancel();
-
- // Ensure proper sequence of exceptions
- t = new Timer();
- d = new Date(-100);
- exception = false;
- try {
- t.schedule(null, d);
- } catch (NullPointerException e) {
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a null task with negative date should throw IllegalArgumentException first",
- exception);
- t.cancel();
-
- // Ensure a task is run
- t = new Timer();
- testTask = new TimerTestTask();
- d = new Date(System.currentTimeMillis() + 200);
- t.schedule(testTask, d);
- try {
- Thread.sleep(400);
- } catch (InterruptedException e) {
- }
- assertEquals("TimerTask.run() method not called after 200ms",
- 1, testTask.wasRun());
- t.cancel();
-
- // Ensure multiple tasks are run
- t = new Timer();
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- d = new Date(System.currentTimeMillis() + 100);
- t.schedule(testTask, d);
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- d = new Date(System.currentTimeMillis() + 150);
- t.schedule(testTask, d);
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- d = new Date(System.currentTimeMillis() + 70);
- t.schedule(testTask, d);
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- d = new Date(System.currentTimeMillis() + 10);
- t.schedule(testTask, d);
- try {
- Thread.sleep(400);
- } catch (InterruptedException e) {
- }
- assertTrue(
- "Multiple tasks should have incremented counter 4 times not "
- + timerCounter, timerCounter == 4);
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
- }
-
- /**
- * @tests java.util.Timer#schedule(java.util.TimerTask, long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "schedule",
- args = {java.util.TimerTask.class, long.class}
- )
- public void test_scheduleLjava_util_TimerTaskJ() {
- Timer t = null;
- try {
- // Ensure a Timer throws an IllegalStateException after cancelled
- t = new Timer();
- TimerTestTask testTask = new TimerTestTask();
- t.cancel();
- boolean exception = false;
- try {
- t.schedule(testTask, 100);
- } catch (IllegalStateException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a task after Timer.cancel() should throw exception",
- exception);
-
- // Ensure a Timer throws an IllegalStateException if task already
- // cancelled
- t = new Timer();
- testTask = new TimerTestTask();
- testTask.cancel();
- exception = false;
- try {
- t.schedule(testTask, 100);
- } catch (IllegalStateException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a task after cancelling it should throw exception",
- exception);
- t.cancel();
-
- // Ensure a Timer throws an IllegalArgumentException if delay is
- // negative
- t = new Timer();
- testTask = new TimerTestTask();
- exception = false;
- try {
- t.schedule(testTask, -100);
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a task with negative delay should throw IllegalArgumentException",
- exception);
- t.cancel();
-
- // Ensure a Timer throws a NullPointerException if the task is null
- t = new Timer();
- exception = false;
- try {
- t.schedule(null, 10);
- } catch (NullPointerException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a null task should throw NullPointerException",
- exception);
- t.cancel();
-
- // Ensure proper sequence of exceptions
- t = new Timer();
- exception = false;
- try {
- t.schedule(null, -10);
- } catch (NullPointerException e) {
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a null task with negative delays should throw IllegalArgumentException first",
- exception);
- t.cancel();
-
- // Ensure a task is run
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 200);
- try {
- Thread.sleep(400);
- } catch (InterruptedException e) {
- }
- assertEquals("TimerTask.run() method not called after 200ms",
- 1, testTask.wasRun());
- t.cancel();
-
- // Ensure multiple tasks are run
- t = new Timer();
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- t.schedule(testTask, 100);
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- t.schedule(testTask, 150);
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- t.schedule(testTask, 70);
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- t.schedule(testTask, 10);
- try {
- Thread.sleep(400);
- } catch (InterruptedException e) {
- }
- assertTrue(
- "Multiple tasks should have incremented counter 4 times not "
- + timerCounter, timerCounter == 4);
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
- }
-
- /**
- * @tests java.util.Timer#schedule(java.util.TimerTask, long, long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "schedule",
- args = {java.util.TimerTask.class, long.class, long.class}
- )
- public void test_scheduleLjava_util_TimerTaskJJ() {
- Timer t = null;
- try {
- // Ensure a Timer throws an IllegalStateException after cancelled
- t = new Timer();
- TimerTestTask testTask = new TimerTestTask();
- t.cancel();
- boolean exception = false;
- try {
- t.schedule(testTask, 100, 100);
- } catch (IllegalStateException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a task after Timer.cancel() should throw exception",
- exception);
-
- // Ensure a Timer throws an IllegalStateException if task already
- // cancelled
- t = new Timer();
- testTask = new TimerTestTask();
- testTask.cancel();
- exception = false;
- try {
- t.schedule(testTask, 100, 100);
- } catch (IllegalStateException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a task after cancelling it should throw exception",
- exception);
- t.cancel();
-
- // Ensure a Timer throws an IllegalArgumentException if delay is
- // negative
- t = new Timer();
- testTask = new TimerTestTask();
- exception = false;
- try {
- t.schedule(testTask, -100, 100);
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a task with negative delay should throw IllegalArgumentException",
- exception);
- t.cancel();
-
- // Ensure a Timer throws an IllegalArgumentException if period is
- // negative
- t = new Timer();
- testTask = new TimerTestTask();
- exception = false;
- try {
- t.schedule(testTask, 100, -100);
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a task with negative period should throw IllegalArgumentException",
- exception);
- t.cancel();
-
- // Ensure a Timer throws an IllegalArgumentException if period is
- // zero
- t = new Timer();
- testTask = new TimerTestTask();
- exception = false;
- try {
- t.schedule(testTask, 100, 0);
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a task with 0 period should throw IllegalArgumentException",
- exception);
- t.cancel();
-
- // Ensure a Timer throws a NullPointerException if the task is null
- t = new Timer();
- exception = false;
- try {
- t.schedule(null, 10, 10);
- } catch (NullPointerException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a null task should throw NullPointerException",
- exception);
- t.cancel();
-
- // Ensure proper sequence of exceptions
- t = new Timer();
- exception = false;
- try {
- t.schedule(null, -10, -10);
- } catch (NullPointerException e) {
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a null task with negative delays should throw IllegalArgumentException first",
- exception);
- t.cancel();
-
- // Ensure a task is run at least twice
- t = new Timer();
- testTask = new TimerTestTask();
- t.schedule(testTask, 100, 100);
- try {
- Thread.sleep(400);
- } catch (InterruptedException e) {
- }
- assertTrue(
- "TimerTask.run() method should have been called at least twice ("
- + testTask.wasRun() + ")", testTask.wasRun() >= 2);
- t.cancel();
-
- // Ensure multiple tasks are run
- t = new Timer();
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- t.schedule(testTask, 100, 100); // at least 9 times
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- t.schedule(testTask, 200, 100); // at least 7 times
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- t.schedule(testTask, 300, 200); // at least 4 times
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- t.schedule(testTask, 100, 200); // at least 4 times
- try {
- Thread.sleep(1200); // Allowed more room for error
- } catch (InterruptedException e) {
- }
- assertTrue(
- "Multiple tasks should have incremented counter 24 times not "
- + timerCounter, timerCounter >= 24);
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
- }
-
- /**
- * @tests java.util.Timer#schedule(java.util.TimerTask, java.util.Date,
- * long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "schedule",
- args = {java.util.TimerTask.class, java.util.Date.class, long.class}
- )
- public void test_scheduleLjava_util_TimerTaskLjava_util_DateJ() {
- Timer t = null;
- try {
- // Ensure a Timer throws an IllegalStateException after cancelled
- t = new Timer();
- TimerTestTask testTask = new TimerTestTask();
- Date d = new Date(System.currentTimeMillis() + 100);
- t.cancel();
- boolean exception = false;
- try {
- t.schedule(testTask, d, 100);
- } catch (IllegalStateException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a task after Timer.cancel() should throw exception",
- exception);
-
- // Ensure a Timer throws an IllegalStateException if task already
- // cancelled
- t = new Timer();
- d = new Date(System.currentTimeMillis() + 100);
- testTask = new TimerTestTask();
- testTask.cancel();
- exception = false;
- try {
- t.schedule(testTask, d, 100);
- } catch (IllegalStateException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a task after cancelling it should throw exception",
- exception);
- t.cancel();
-
- // Ensure a Timer throws an IllegalArgumentException if delay is
- // negative
- t = new Timer();
- d = new Date(-100);
- testTask = new TimerTestTask();
- exception = false;
- try {
- t.schedule(testTask, d, 100);
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a task with negative delay should throw IllegalArgumentException",
- exception);
- t.cancel();
-
- // Ensure a Timer throws an IllegalArgumentException if period is
- // negative
- t = new Timer();
- d = new Date(System.currentTimeMillis() + 100);
- testTask = new TimerTestTask();
- exception = false;
- try {
- t.schedule(testTask, d, -100);
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a task with negative period should throw IllegalArgumentException",
- exception);
- t.cancel();
-
- // Ensure a Timer throws a NullPointerException if the task is null
- t = new Timer();
- d = new Date(System.currentTimeMillis() + 100);
- exception = false;
- try {
- t.schedule(null, d, 10);
- } catch (NullPointerException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a null task should throw NullPointerException",
- exception);
- t.cancel();
-
- // Ensure a Timer throws a NullPointerException if the date is null
- t = new Timer();
- testTask = new TimerTestTask();
- exception = false;
- try {
- t.schedule(testTask, null, 10);
- } catch (NullPointerException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a null task should throw NullPointerException",
- exception);
- t.cancel();
-
- // Ensure proper sequence of exceptions
- t = new Timer();
- d = new Date(-100);
- exception = false;
- try {
- t.schedule(null, d, 10);
- } catch (NullPointerException e) {
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a null task with negative dates should throw IllegalArgumentException first",
- exception);
- t.cancel();
-
- // Ensure a task is run at least twice
- t = new Timer();
- d = new Date(System.currentTimeMillis() + 100);
- testTask = new TimerTestTask();
- t.schedule(testTask, d, 100);
- try {
- Thread.sleep(800);
- } catch (InterruptedException e) {
- }
- assertTrue(
- "TimerTask.run() method should have been called at least twice ("
- + testTask.wasRun() + ")", testTask.wasRun() >= 2);
- t.cancel();
-
- // Ensure multiple tasks are run
- t = new Timer();
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- d = new Date(System.currentTimeMillis() + 100);
- t.schedule(testTask, d, 100); // at least 9 times
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- d = new Date(System.currentTimeMillis() + 200);
- t.schedule(testTask, d, 100); // at least 7 times
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- d = new Date(System.currentTimeMillis() + 300);
- t.schedule(testTask, d, 200); // at least 4 times
- testTask = new TimerTestTask();
- testTask.incrementCount(true);
- d = new Date(System.currentTimeMillis() + 100);
- t.schedule(testTask, d, 200); // at least 4 times
- try {
- Thread.sleep(3000);
- } catch (InterruptedException e) {
- }
- assertTrue(
- "Multiple tasks should have incremented counter 24 times not "
- + timerCounter, timerCounter >= 24);
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
- }
-
- /**
- * @tests java.util.Timer#scheduleAtFixedRate(java.util.TimerTask, long,
- * long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "scheduleAtFixedRate",
- args = {java.util.TimerTask.class, long.class, long.class}
- )
- public void test_scheduleAtFixedRateLjava_util_TimerTaskJJ() {
- Timer t = null;
- try {
- // Ensure a Timer throws an IllegalStateException after cancelled
- t = new Timer();
- TimerTestTask testTask = new TimerTestTask();
- t.cancel();
- boolean exception = false;
- try {
- t.scheduleAtFixedRate(testTask, 100, 100);
- } catch (IllegalStateException e) {
- exception = true;
- }
- assertTrue(
- "scheduleAtFixedRate after Timer.cancel() should throw exception",
- exception);
-
- // Ensure a Timer throws an IllegalArgumentException if delay is
- // negative
- t = new Timer();
- testTask = new TimerTestTask();
- exception = false;
- try {
- t.scheduleAtFixedRate(testTask, -100, 100);
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue(
- "scheduleAtFixedRate with negative delay should throw IllegalArgumentException",
- exception);
- t.cancel();
-
- // Ensure a Timer throws an IllegalArgumentException if period is
- // negative
- t = new Timer();
- testTask = new TimerTestTask();
- exception = false;
- try {
- t.scheduleAtFixedRate(testTask, 100, -100);
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue(
- "scheduleAtFixedRate with negative period should throw IllegalArgumentException",
- exception);
- t.cancel();
-
- // Ensure a task is run at least twice
- t = new Timer();
- testTask = new TimerTestTask();
- t.scheduleAtFixedRate(testTask, 100, 100);
- try {
- Thread.sleep(400);
- } catch (InterruptedException e) {
- }
- assertTrue(
- "TimerTask.run() method should have been called at least twice ("
- + testTask.wasRun() + ")", testTask.wasRun() >= 2);
- t.cancel();
-
- class SlowThenFastTask extends TimerTask {
- int wasRun = 0;
-
- long startedAt;
-
- long lastDelta;
-
- public void run() {
- if (wasRun == 0)
- startedAt = System.currentTimeMillis();
- lastDelta = System.currentTimeMillis()
- - (startedAt + (100 * wasRun));
- wasRun++;
- if (wasRun == 2) {
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- }
- }
- }
-
- public long lastDelta() {
- return lastDelta;
- }
-
- public int wasRun() {
- return wasRun;
- }
- }
-
- // Ensure multiple tasks are run
- t = new Timer();
- SlowThenFastTask slowThenFastTask = new SlowThenFastTask();
-
- // at least 9 times even when asleep
- t.scheduleAtFixedRate(slowThenFastTask, 100, 100);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- }
- long lastDelta = slowThenFastTask.lastDelta();
- assertTrue("Fixed Rate Schedule should catch up, but is off by "
- + lastDelta + " ms", slowThenFastTask.lastDelta < 300);
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
- }
-
- /**
- * @tests java.util.Timer#scheduleAtFixedRate(java.util.TimerTask,
- * java.util.Date, long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "scheduleAtFixedRate",
- args = {java.util.TimerTask.class, java.util.Date.class, long.class}
- )
- public void test_scheduleAtFixedRateLjava_util_TimerTaskLjava_util_DateJ() {
- Timer t = null;
- try {
- // Ensure a Timer throws an IllegalStateException after cancelled
- t = new Timer();
- TimerTestTask testTask = new TimerTestTask();
- t.cancel();
- boolean exception = false;
- Date d = new Date(System.currentTimeMillis() + 100);
- try {
- t.scheduleAtFixedRate(testTask, d, 100);
- } catch (IllegalStateException e) {
- exception = true;
- }
- assertTrue(
- "scheduleAtFixedRate after Timer.cancel() should throw exception",
- exception);
-
- // Ensure a Timer throws an IllegalArgumentException if delay is
- // negative
- t = new Timer();
- testTask = new TimerTestTask();
- exception = false;
- d = new Date(-100);
- try {
- t.scheduleAtFixedRate(testTask, d, 100);
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue(
- "scheduleAtFixedRate with negative Date should throw IllegalArgumentException",
- exception);
- t.cancel();
-
- // Ensure a Timer throws an IllegalArgumentException if period is
- // negative
- t = new Timer();
- testTask = new TimerTestTask();
- exception = false;
- try {
- t.scheduleAtFixedRate(testTask, d, -100);
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue(
- "scheduleAtFixedRate with negative period should throw IllegalArgumentException",
- exception);
- t.cancel();
-
- // Ensure a Timer throws an NullPointerException if date is Null
- t = new Timer();
- testTask = new TimerTestTask();
- exception = false;
- try {
- t.scheduleAtFixedRate(testTask, null, 100);
- } catch (NullPointerException e) {
- exception = true;
- }
- assertTrue(
- "scheduleAtFixedRate with null date should throw NullPointerException",
- exception);
- t.cancel();
-
- // Ensure proper sequence of exceptions
- t = new Timer();
- exception = false;
- d = new Date(-100);
- try {
- t.scheduleAtFixedRate(null, d, 10);
- } catch (NullPointerException e) {
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a null task with negative date should throw IllegalArgumentException first",
- exception);
- t.cancel();
-
- // Ensure proper sequence of exceptions
- t = new Timer();
- exception = false;
- try {
- t.scheduleAtFixedRate(null, null, -10);
- } catch (NullPointerException e) {
- } catch (IllegalArgumentException e) {
- exception = true;
- }
- assertTrue(
- "Scheduling a null task & null date & negative period should throw IllegalArgumentException first",
- exception);
- t.cancel();
-
- // Ensure a task is run at least twice
- t = new Timer();
- testTask = new TimerTestTask();
- d = new Date(System.currentTimeMillis() + 100);
- t.scheduleAtFixedRate(testTask, d, 100);
- try {
- Thread.sleep(400);
- } catch (InterruptedException e) {
- }
- assertTrue(
- "TimerTask.run() method should have been called at least twice ("
- + testTask.wasRun() + ")", testTask.wasRun() >= 2);
- t.cancel();
-
- class SlowThenFastTask extends TimerTask {
- int wasRun = 0;
-
- long startedAt;
-
- long lastDelta;
-
- public void run() {
- if (wasRun == 0)
- startedAt = System.currentTimeMillis();
- lastDelta = System.currentTimeMillis()
- - (startedAt + (100 * wasRun));
- wasRun++;
- if (wasRun == 2) {
- try {
- Thread.sleep(200);
- } catch (InterruptedException e) {
- }
- }
- }
-
- public long lastDelta() {
- return lastDelta;
- }
-
- public int wasRun() {
- return wasRun;
- }
- }
-
- // Ensure multiple tasks are run
- t = new Timer();
- SlowThenFastTask slowThenFastTask = new SlowThenFastTask();
- d = new Date(System.currentTimeMillis() + 100);
-
- // at least 9 times even when asleep
- t.scheduleAtFixedRate(slowThenFastTask, d, 100);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- }
- long lastDelta = slowThenFastTask.lastDelta();
- assertTrue("Fixed Rate Schedule should catch up, but is off by "
- + lastDelta + " ms", lastDelta < 300);
- t.cancel();
- } finally {
- if (t != null)
- t.cancel();
- }
- }
-
- protected void setUp() {
- timerCounter = 0;
- }
-
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/TooManyListenersExceptionTest.java b/luni/src/test/java/tests/api/java/util/TooManyListenersExceptionTest.java
deleted file mode 100644
index 0116893..0000000
--- a/luni/src/test/java/tests/api/java/util/TooManyListenersExceptionTest.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.TooManyListenersException;
-
-@TestTargetClass(TooManyListenersException.class)
-public class TooManyListenersExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.util.TooManyListenersException#TooManyListenersException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TooManyListenersException",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.TooManyListenersException()
- try {
- throw new TooManyListenersException();
- } catch (TooManyListenersException e) {
- assertNull(
- "Message thrown with exception constructed with no message",
- e.getMessage());
- }
- }
-
- /**
- * @tests java.util.TooManyListenersException#TooManyListenersException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TooManyListenersException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.util.TooManyListenersException(java.lang.String)
- try {
- throw new TooManyListenersException("Gah");
- } catch (TooManyListenersException e) {
- assertEquals("Incorrect message thrown with exception", "Gah", e
- .getMessage());
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/TreeMapTest.java b/luni/src/test/java/tests/api/java/util/TreeMapTest.java
deleted file mode 100644
index 7ea4c9e..0000000
--- a/luni/src/test/java/tests/api/java/util/TreeMapTest.java
+++ /dev/null
@@ -1,890 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.AndroidOnly;
-
-import java.io.Serializable;
-import java.text.CollationKey;
-import java.text.Collator;
-import java.util.AbstractMap;
-import java.util.Collection;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.Set;
-import java.util.SortedMap;
-import java.util.TreeMap;
-
-import org.apache.harmony.testframework.serialization.SerializationTest;
-
-import tests.support.Support_MapTest2;
-import tests.support.Support_UnmodifiableCollectionTest;
-
-@TestTargetClass(TreeMap.class)
-public class TreeMapTest extends junit.framework.TestCase {
-
- public static class ReversedComparator implements Comparator {
- public int compare(Object o1, Object o2) {
- return -(((Comparable) o1).compareTo(o2));
- }
-
- public boolean equals(Object o1, Object o2) {
- return (((Comparable) o1).compareTo(o2)) == 0;
- }
- }
-
- // Regression for Harmony-1026
- public static class MockComparator<T extends Comparable<T>> implements
- Comparator<T>, Serializable {
-
- public int compare(T o1, T o2) {
- if (o1 == o2) {
- return 0;
- }
- if (null == o1 || null == o2) {
- return -1;
- }
- T c1 = o1;
- T c2 = o2;
- return c1.compareTo(c2);
- }
- }
-
- // Regression for Harmony-1161
- class MockComparatorNullTolerable implements Comparator<String> {
-
- public int compare(String o1, String o2) {
- if (o1 == o2) {
- return 0;
- }
- if (null == o1) {
- return -1;
- }
- return o1.compareTo(o2);
- }
- }
-
- TreeMap tm;
-
- Object objArray[] = new Object[1000];
-
- /**
- * @tests java.util.TreeMap#TreeMap()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TreeMap",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.TreeMap()
- new Support_MapTest2(new TreeMap()).runTest();
-
- assertTrue("New treeMap non-empty", new TreeMap().isEmpty());
- }
-
- /**
- * @tests java.util.TreeMap#TreeMap(java.util.Comparator)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TreeMap",
- args = {java.util.Comparator.class}
- )
- public void test_ConstructorLjava_util_Comparator() {
- // Test for method java.util.TreeMap(java.util.Comparator)
- Comparator comp = new ReversedComparator();
- TreeMap reversedTreeMap = new TreeMap(comp);
- assertTrue("TreeMap answered incorrect comparator", reversedTreeMap
- .comparator() == comp);
- reversedTreeMap.put(new Integer(1).toString(), new Integer(1));
- reversedTreeMap.put(new Integer(2).toString(), new Integer(2));
- assertTrue("TreeMap does not use comparator (firstKey was incorrect)",
- reversedTreeMap.firstKey().equals(new Integer(2).toString()));
- assertTrue("TreeMap does not use comparator (lastKey was incorrect)",
- reversedTreeMap.lastKey().equals(new Integer(1).toString()));
-
- }
-
- /**
- * @tests java.util.TreeMap#TreeMap(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TreeMap",
- args = {java.util.Map.class}
- )
- public void test_ConstructorLjava_util_Map() {
- // Test for method java.util.TreeMap(java.util.Map)
- TreeMap myTreeMap = new TreeMap(new HashMap(tm));
- assertTrue("Map is incorrect size", myTreeMap.size() == objArray.length);
- for (Object element : objArray) {
- assertTrue("Map has incorrect mappings", myTreeMap.get(
- element.toString()).equals(element));
- }
-
- HashMap hm = new HashMap();
- hm.put(new Integer(1), "one");
- hm.put("one", new Integer(1));
-
- try {
- new TreeMap(hm);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- try {
- new TreeMap((Map)null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.TreeMap#TreeMap(java.util.SortedMap)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TreeMap",
- args = {java.util.SortedMap.class}
- )
- public void test_ConstructorLjava_util_SortedMap() {
- // Test for method java.util.TreeMap(java.util.SortedMap)
- Comparator comp = new ReversedComparator();
- TreeMap reversedTreeMap = new TreeMap(comp);
- reversedTreeMap.put(new Integer(1).toString(), new Integer(1));
- reversedTreeMap.put(new Integer(2).toString(), new Integer(2));
- TreeMap anotherTreeMap = new TreeMap(reversedTreeMap);
- assertTrue("New tree map does not answer correct comparator",
- anotherTreeMap.comparator() == comp);
- assertTrue("TreeMap does not use comparator (firstKey was incorrect)",
- anotherTreeMap.firstKey().equals(new Integer(2).toString()));
- assertTrue("TreeMap does not use comparator (lastKey was incorrect)",
- anotherTreeMap.lastKey().equals(new Integer(1).toString()));
-
- try {
- new TreeMap((SortedMap)null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.TreeMap#clear()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- // Test for method void java.util.TreeMap.clear()
- tm.clear();
- assertEquals("Cleared map returned non-zero size", 0, tm.size());
- }
-
- /**
- * @tests java.util.TreeMap#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- // Test for method java.lang.Object java.util.TreeMap.clone()
- TreeMap clonedMap = (TreeMap) tm.clone();
- assertTrue("Cloned map does not equal the original map", clonedMap
- .equals(tm));
- assertTrue("Cloned map is the same reference as the original map",
- clonedMap != tm);
- for (Object element : objArray) {
- assertTrue("Cloned map contains incorrect elements", clonedMap
- .get(element.toString()) == tm.get(element.toString()));
- }
-
- TreeMap map = new TreeMap();
- map.put("key", "value");
- // get the keySet() and values() on the original Map
- Set keys = map.keySet();
- Collection values = map.values();
- assertEquals("values() does not work", "value", values.iterator()
- .next());
- assertEquals("keySet() does not work", "key", keys.iterator().next());
- AbstractMap map2 = (AbstractMap) map.clone();
- map2.put("key", "value2");
- Collection values2 = map2.values();
- assertTrue("values() is identical", values2 != values);
- // values() and keySet() on the cloned() map should be different
- assertEquals("values() was not cloned", "value2", values2.iterator()
- .next());
- map2.clear();
- map2.put("key2", "value3");
- Set key2 = map2.keySet();
- assertTrue("keySet() is identical", key2 != keys);
- assertEquals("keySet() was not cloned", "key2", key2.iterator().next());
- }
-
- /**
- * @tests java.util.TreeMap#comparator()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "comparator",
- args = {}
- )
- public void test_comparator() {
- // Test for method java.util.Comparator java.util.TreeMap.comparator()\
- Comparator comp = new ReversedComparator();
- TreeMap reversedTreeMap = new TreeMap(comp);
- assertTrue("TreeMap answered incorrect comparator", reversedTreeMap
- .comparator() == comp);
- reversedTreeMap.put(new Integer(1).toString(), new Integer(1));
- reversedTreeMap.put(new Integer(2).toString(), new Integer(2));
- assertTrue("TreeMap does not use comparator (firstKey was incorrect)",
- reversedTreeMap.firstKey().equals(new Integer(2).toString()));
- assertTrue("TreeMap does not use comparator (lastKey was incorrect)",
- reversedTreeMap.lastKey().equals(new Integer(1).toString()));
- }
-
- /**
- * @tests java.util.TreeMap#containsKey(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "containsKey",
- args = {java.lang.Object.class}
- )
- public void test_containsKeyLjava_lang_Object() {
- // Test for method boolean
- // java.util.TreeMap.containsKey(java.lang.Object)
- assertTrue("Returned false for valid key", tm.containsKey("95"));
- assertTrue("Returned true for invalid key", !tm.containsKey("XXXXX"));
-
- try {
- tm.containsKey(new Double(3.14));
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- try {
- tm.containsKey(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.TreeMap#containsValue(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "containsValue",
- args = {java.lang.Object.class}
- )
- public void test_containsValueLjava_lang_Object() {
- // Test for method boolean
- // java.util.TreeMap.containsValue(java.lang.Object)
- assertTrue("Returned false for valid value", tm
- .containsValue(objArray[986]));
- assertTrue("Returned true for invalid value", !tm
- .containsValue(new Object()));
- }
-
- /**
- * @tests java.util.TreeMap#entrySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "entrySet",
- args = {}
- )
- public void test_entrySet() {
- // Test for method java.util.Set java.util.TreeMap.entrySet()
- Set anEntrySet = tm.entrySet();
- Iterator entrySetIterator = anEntrySet.iterator();
- assertTrue("EntrySet is incorrect size",
- anEntrySet.size() == objArray.length);
- Map.Entry entry;
- while (entrySetIterator.hasNext()) {
- entry = (Map.Entry) entrySetIterator.next();
- assertTrue("EntrySet does not contain correct mappings", tm
- .get(entry.getKey()) == entry.getValue());
- }
- }
-
- /**
- * @tests java.util.TreeMap#firstKey()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "firstKey",
- args = {}
- )
- public void test_firstKey() {
- // Test for method java.lang.Object java.util.TreeMap.firstKey()
- assertEquals("Returned incorrect first key", "0", tm.firstKey());
- tm = new TreeMap();
- try {
- tm.firstKey();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.TreeMap#get(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {java.lang.Object.class}
- )
- public void test_getLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.TreeMap.get(java.lang.Object)
- Object o = new Object();
- tm.put("Hello", o);
- assertTrue("Failed to get mapping", tm.get("Hello") == o);
-
- try {
- tm.get(new Double(3.14));
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- try {
- tm.get(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.TreeMap#headMap(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "headMap",
- args = {java.lang.Object.class}
- )
- public void test_headMapLjava_lang_Object() {
- // Test for method java.util.SortedMap
- // java.util.TreeMap.headMap(java.lang.Object)
- Map head = tm.headMap("100");
- assertEquals("Returned map of incorrect size", 3, head.size());
- assertTrue("Returned incorrect elements", head.containsKey("0")
- && head.containsValue(new Integer("1"))
- && head.containsKey("10"));
- SortedMap sort = tm.headMap("100");
- try {
- sort.headMap("50");
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- tm.headMap(this);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- try {
- tm.headMap(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- // Regression for Harmony-1026
- TreeMap<Integer, Double> map = new TreeMap<Integer, Double>(
- new MockComparator());
- map.put(1, 2.1);
- map.put(2, 3.1);
- map.put(3, 4.5);
- map.put(7, 21.3);
- map.put(null, null);
-
- SortedMap<Integer, Double> smap = map.headMap(null);
- assertEquals(0, smap.size());
-
- Set<Integer> keySet = smap.keySet();
- assertEquals(0, keySet.size());
-
- Set<Map.Entry<Integer, Double>> entrySet = smap.entrySet();
- assertEquals(0, entrySet.size());
-
- Collection<Double> valueCollection = smap.values();
- assertEquals(0, valueCollection.size());
-
- // Regression for Harmony-1066
- assertTrue(head instanceof Serializable);
-
- // Regression for ill-behaved collator
- Collator c = new Collator() {
- @Override
- public int compare(String o1, String o2) {
- if (o1 == null) {
- return 0;
- }
- return o1.compareTo(o2);
- }
-
- @Override
- public CollationKey getCollationKey(String string) {
- return null;
- }
-
- @Override
- public int hashCode() {
- return 0;
- }
- };
-
- TreeMap<String, String> treemap = new TreeMap<String, String>(c);
- assertEquals(0, treemap.headMap(null).size());
- }
-
- /**
- * @tests java.util.TreeMap#keySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "keySet",
- args = {}
- )
- public void test_keySet() {
- // Test for method java.util.Set java.util.TreeMap.keySet()
- Set ks = tm.keySet();
- assertTrue("Returned set of incorrect size",
- ks.size() == objArray.length);
- for (int i = 0; i < tm.size(); i++) {
- assertTrue("Returned set is missing keys", ks.contains(new Integer(
- i).toString()));
- }
- }
-
- /**
- * @tests java.util.TreeMap#lastKey()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lastKey",
- args = {}
- )
- public void test_lastKey() {
- // Test for method java.lang.Object java.util.TreeMap.lastKey()
- assertTrue("Returned incorrect last key", tm.lastKey().equals(
- objArray[objArray.length - 1].toString()));
- tm = new TreeMap();
- try {
- tm.lastKey();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.TreeMap#put(java.lang.Object, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "put",
- args = {java.lang.Object.class, java.lang.Object.class}
- )
- public void test_putLjava_lang_ObjectLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.TreeMap.put(java.lang.Object, java.lang.Object)
- Object o = new Object();
- tm.put("Hello", o);
- assertTrue("Failed to put mapping", tm.get("Hello") == o);
-
- try {
- tm.put(null, "null");
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- // regression for Harmony-780
- tm = new TreeMap();
- assertNull(tm.put(new Object(), new Object()));
- try {
- tm.put(new Integer(1), new Object());
- fail("should throw ClassCastException");
- } catch (ClassCastException e) {
- // expected
- }
-
- tm = new TreeMap();
- assertNull(tm.put(new Integer(1), new Object()));
-
- // regression for Harmony-2474
- tm = new TreeMap();
- tm.remove(o);
- }
-
- /**
- * @tests java.util.TreeMap#putAll(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "putAll",
- args = {java.util.Map.class}
- )
- public void test_putAllLjava_util_Map() {
- // Test for method void java.util.TreeMap.putAll(java.util.Map)
- TreeMap x = new TreeMap();
- x.putAll(tm);
- assertTrue("Map incorrect size after put", x.size() == tm.size());
- for (Object element : objArray) {
- assertTrue("Failed to put all elements", x.get(element.toString())
- .equals(element));
- }
- x = new TreeMap();
- x.put(new Integer(1), "one");
- x.put(new Integer(2), "two");
-
- try {
- tm.putAll(x);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- try {
- tm.putAll(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.TreeMap#remove(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_removeLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.TreeMap.remove(java.lang.Object)
- tm.remove("990");
- assertTrue("Failed to remove mapping", !tm.containsKey("990"));
-
- try {
- tm.remove(new Double(3.14));
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- try {
- tm.remove(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.TreeMap#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- public void test_size() {
- // Test for method int java.util.TreeMap.size()
- assertEquals("Returned incorrect size", 1000, tm.size());
- }
-
- /**
- * @tests java.util.TreeMap#subMap(java.lang.Object, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "subMap",
- args = {java.lang.Object.class, java.lang.Object.class}
- )
- public void test_subMapLjava_lang_ObjectLjava_lang_Object() {
- // Test for method java.util.SortedMap
- // java.util.TreeMap.subMap(java.lang.Object, java.lang.Object)
- SortedMap subMap = tm.subMap(objArray[100].toString(), objArray[109]
- .toString());
- assertEquals("subMap is of incorrect size", 9, subMap.size());
- for (int counter = 100; counter < 109; counter++) {
- assertTrue("SubMap contains incorrect elements", subMap.get(
- objArray[counter].toString()).equals(objArray[counter]));
- }
-
- try {
- tm.subMap(objArray[9].toString(), objArray[1].toString());
- fail("end key less than start key should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // Expected
- }
-
- // Regression for Harmony-1161
- TreeMap<String, String> treeMapWithNull = new TreeMap<String, String>(
- new MockComparatorNullTolerable());
- treeMapWithNull.put("key1", "value1"); //$NON-NLS-1$ //$NON-NLS-2$
- treeMapWithNull.put(null, "value2"); //$NON-NLS-1$
- SortedMap<String, String> subMapWithNull = treeMapWithNull.subMap(null,
- "key1"); //$NON-NLS-1$
- assertEquals("Size of subMap should be 1:", 1, subMapWithNull.size()); //$NON-NLS-1$
-
- // Regression test for typo in lastKey method
- SortedMap<String, String> map = new TreeMap<String, String>();
- map.put("1", "one"); //$NON-NLS-1$ //$NON-NLS-2$
- map.put("2", "two"); //$NON-NLS-1$ //$NON-NLS-2$
- map.put("3", "three"); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals("3", map.lastKey());
- SortedMap<String, String> sub = map.subMap("1", "3"); //$NON-NLS-1$ //$NON-NLS-2$
- assertEquals("2", sub.lastKey()); //$NON-NLS-1$
-
- try {
- tm.subMap(this, this);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- try {
- tm.subMap(objArray[9].toString(), null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- try {
- tm.subMap(null, objArray[9].toString());
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.TreeMap#tailMap(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "tailMap",
- args = {java.lang.Object.class}
- )
- public void test_tailMapLjava_lang_Object() {
- // Test for method java.util.SortedMap
- // java.util.TreeMap.tailMap(java.lang.Object)
- Map tail = tm.tailMap(objArray[900].toString());
- assertTrue("Returned map of incorrect size : " + tail.size(), tail
- .size() == (objArray.length - 900) + 9);
- for (int i = 900; i < objArray.length; i++) {
- assertTrue("Map contains incorrect entries", tail
- .containsValue(objArray[i]));
- }
-
- SortedMap sort = tm.tailMap("99");
-
- try {
- sort.tailMap("101");
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- tm.tailMap(this);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- try {
- tm.tailMap(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- // Regression for Harmony-1066
- assertTrue(tail instanceof Serializable);
- }
-
- /**
- * @tests java.util.TreeMap#values()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
- public void test_values() {
- // Test for method java.util.Collection java.util.TreeMap.values()
- Collection vals = tm.values();
- vals.iterator();
- assertTrue("Returned collection of incorrect size",
- vals.size() == objArray.length);
- for (Object element : objArray) {
- assertTrue("Collection contains incorrect elements", vals
- .contains(element));
- }
-
- TreeMap myTreeMap = new TreeMap();
- for (int i = 0; i < 100; i++) {
- myTreeMap.put(objArray[i], objArray[i]);
- }
- Collection values = myTreeMap.values();
- new Support_UnmodifiableCollectionTest(
- "Test Returned Collection From TreeMap.values()", values)
- .runTest();
- values.remove(new Integer(0));
- assertTrue(
- "Removing from the values collection should remove from the original map",
- !myTreeMap.containsValue(new Integer(0)));
- }
-
- /**
- * @tests java.util.TreeMap#SerializationTest()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization.",
- method = "!SerializationSelf",
- args = {}
- )
- @AndroidOnly("fail on RI. See comment below")
- // Regression for Harmony-1066
- public void test_SubMap_Serializable() throws Exception {
- TreeMap<Integer, Double> map = new TreeMap<Integer, Double>();
- map.put(1, 2.1);
- map.put(2, 3.1);
- map.put(3, 4.5);
- map.put(7, 21.3);
- SortedMap<Integer, Double> headMap = map.headMap(3);
- assertTrue(headMap instanceof Serializable);
- assertFalse(headMap instanceof TreeMap);
- assertTrue(headMap instanceof SortedMap);
-
- assertFalse(headMap.entrySet() instanceof Serializable);
- assertFalse(headMap.keySet() instanceof Serializable);
- assertFalse(headMap.values() instanceof Serializable);
-
- // This assertion will fail on RI. This is a bug of RI.
- SerializationTest.verifySelf(headMap);
- }
-
- /**
- * Tests equals() method.
- * Tests that no ClassCastException will be thrown in all cases.
- * Regression test for HARMONY-1639.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- @KnownFailure("equals(Onject o) method throws java.lang.ClassCastException " +
- "for TreeMap objects with different key objects.")
- public void test_equals() throws Exception {
- // comparing TreeMaps with different object types
- Map m1 = new TreeMap();
- Map m2 = new TreeMap();
- m1.put("key1", "val1");
- m1.put("key2", "val2");
- m2.put(new Integer(1), "val1");
- m2.put(new Integer(2), "val2");
- assertFalse("Maps should not be equal 1", m1.equals(m2));
- assertFalse("Maps should not be equal 2", m2.equals(m1));
-
- // comparing TreeMap with HashMap
- m1 = new TreeMap();
- m2 = new HashMap();
- m1.put("key", "val");
- m2.put(new Object(), "val");
- assertFalse("Maps should not be equal 3", m1.equals(m2));
- assertFalse("Maps should not be equal 4", m2.equals(m1));
-
- // comparing TreeMaps with not-comparable objects inside
- m1 = new TreeMap();
- m2 = new TreeMap();
- m1.put(new Object(), "val1");
- m2.put(new Object(), "val1");
- assertFalse("Maps should not be equal 5", m1.equals(m2));
- assertFalse("Maps should not be equal 6", m2.equals(m1));
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- @Override
- protected void setUp() {
- tm = new TreeMap();
- for (int i = 0; i < objArray.length; i++) {
- Object x = objArray[i] = new Integer(i);
- tm.put(x.toString(), x);
- }
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/util/TreeSetTest.java b/luni/src/test/java/tests/api/java/util/TreeSetTest.java
deleted file mode 100644
index d5fe48d..0000000
--- a/luni/src/test/java/tests/api/java/util/TreeSetTest.java
+++ /dev/null
@@ -1,611 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.NoSuchElementException;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-@TestTargetClass(TreeSet.class)
-public class TreeSetTest extends junit.framework.TestCase {
-
- public static class ReversedIntegerComparator implements Comparator {
- public int compare(Object o1, Object o2) {
- return -(((Integer) o1).compareTo((Integer) o2));
- }
-
- public boolean equals(Object o1, Object o2) {
- return ((Integer) o1).compareTo((Integer) o2) == 0;
- }
- }
-
- TreeSet ts;
-
- Object objArray[] = new Object[1000];
-
- /**
- * @tests java.util.TreeSet#TreeSet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TreeSet",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.TreeSet()
- assertTrue("Did not construct correct TreeSet", new TreeSet().isEmpty());
- }
-
- /**
- * @tests java.util.TreeSet#TreeSet(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TreeSet",
- args = {java.util.Collection.class}
- )
- public void test_ConstructorLjava_util_Collection() {
- // Test for method java.util.TreeSet(java.util.Collection)
- TreeSet myTreeSet = new TreeSet(Arrays.asList(objArray));
- assertTrue("TreeSet incorrect size",
- myTreeSet.size() == objArray.length);
- for (int counter = 0; counter < objArray.length; counter++)
- assertTrue("TreeSet does not contain correct elements", myTreeSet
- .contains(objArray[counter]));
-
- HashMap hm = new HashMap();
- hm.put("First", new Integer(1));
- hm.put(new Integer(2), "two");
-
- try {
- new TreeSet(hm.values());
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- try {
- new TreeSet((Collection)null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.TreeSet#TreeSet(java.util.Comparator)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TreeSet",
- args = {java.util.Comparator.class}
- )
- public void test_ConstructorLjava_util_Comparator() {
- // Test for method java.util.TreeSet(java.util.Comparator)
- TreeSet myTreeSet = new TreeSet(new ReversedIntegerComparator());
- assertTrue("Did not construct correct TreeSet", myTreeSet.isEmpty());
- myTreeSet.add(new Integer(1));
- myTreeSet.add(new Integer(2));
- assertTrue(
- "Answered incorrect first element--did not use custom comparator ",
- myTreeSet.first().equals(new Integer(2)));
- assertTrue(
- "Answered incorrect last element--did not use custom comparator ",
- myTreeSet.last().equals(new Integer(1)));
- }
-
- /**
- * @tests java.util.TreeSet#TreeSet(java.util.SortedSet)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "TreeSet",
- args = {java.util.SortedSet.class}
- )
- public void test_ConstructorLjava_util_SortedSet() {
- // Test for method java.util.TreeSet(java.util.SortedSet)
- ReversedIntegerComparator comp = new ReversedIntegerComparator();
- TreeSet myTreeSet = new TreeSet(comp);
- for (int i = 0; i < objArray.length; i++)
- myTreeSet.add(objArray[i]);
- TreeSet anotherTreeSet = new TreeSet(myTreeSet);
- assertTrue("TreeSet is not correct size",
- anotherTreeSet.size() == objArray.length);
- for (int counter = 0; counter < objArray.length; counter++)
- assertTrue("TreeSet does not contain correct elements",
- anotherTreeSet.contains(objArray[counter]));
- assertTrue("TreeSet does not answer correct comparator", anotherTreeSet
- .comparator() == comp);
- assertTrue("TreeSet does not use comparator",
- anotherTreeSet.first() == objArray[objArray.length - 1]);
-
- try {
- new TreeSet((SortedSet)null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.TreeSet#add(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "add",
- args = {java.lang.Object.class}
- )
- public void test_addLjava_lang_Object() {
- // Test for method boolean java.util.TreeSet.add(java.lang.Object)
- ts.add(new Integer(-8));
- assertTrue("Failed to add Object", ts.contains(new Integer(-8)));
- ts.add(objArray[0]);
- assertTrue("Added existing element", ts.size() == objArray.length + 1);
-
- HashMap hm = new HashMap();
- hm.put("First", new Integer(1));
- hm.put(new Integer(2), "two");
-
- try {
- ts.add("Wrong element");
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.TreeSet#addAll(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addAll",
- args = {java.util.Collection.class}
- )
- public void test_addAllLjava_util_Collection() {
- // Test for method boolean
- // java.util.TreeSet.addAll(java.util.Collection)
- TreeSet s = new TreeSet();
- s.addAll(ts);
- assertTrue("Incorrect size after add", s.size() == ts.size());
- Iterator i = ts.iterator();
- while (i.hasNext())
- assertTrue("Returned incorrect set", s.contains(i.next()));
-
- HashMap hm = new HashMap();
- hm.put("First", new Integer(1));
- hm.put(new Integer(2), "two");
-
- try {
- s.addAll(hm.values());
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- try {
- s.addAll(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.TreeSet#clear()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- // Test for method void java.util.TreeSet.clear()
- ts.clear();
- assertEquals("Returned non-zero size after clear", 0, ts.size());
- assertTrue("Found element in cleared set", !ts.contains(objArray[0]));
- }
-
- /**
- * @tests java.util.TreeSet#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- // Test for method java.lang.Object java.util.TreeSet.clone()
- TreeSet s = (TreeSet) ts.clone();
- Iterator i = ts.iterator();
- while (i.hasNext())
- assertTrue("Clone failed to copy all elements", s
- .contains(i.next()));
- }
-
- /**
- * @tests java.util.TreeSet#comparator()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "comparator",
- args = {}
- )
- public void test_comparator() {
- // Test for method java.util.Comparator java.util.TreeSet.comparator()
- ReversedIntegerComparator comp = new ReversedIntegerComparator();
- TreeSet myTreeSet = new TreeSet(comp);
- assertTrue("Answered incorrect comparator",
- myTreeSet.comparator() == comp);
- }
-
- /**
- * @tests java.util.TreeSet#contains(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "contains",
- args = {java.lang.Object.class}
- )
- public void test_containsLjava_lang_Object() {
- // Test for method boolean java.util.TreeSet.contains(java.lang.Object)
- assertTrue("Returned false for valid Object", ts
- .contains(objArray[objArray.length / 2]));
- assertTrue("Returned true for invalid Object", !ts
- .contains(new Integer(-9)));
- try {
- ts.contains(new Object());
- } catch (ClassCastException e) {
- // Correct
- return;
- }
- fail("Failed to throw exception when passed invalid element");
-
- }
-
- /**
- * @tests java.util.TreeSet#first()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "first",
- args = {}
- )
- public void test_first() {
- // Test for method java.lang.Object java.util.TreeSet.first()
- assertTrue("Returned incorrect first element",
- ts.first() == objArray[0]);
-
- ts = new TreeSet();
- try {
- ts.first();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.TreeSet#headSet(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "headSet",
- args = {java.lang.Object.class}
- )
- public void test_headSetLjava_lang_Object() {
- // Test for method java.util.SortedSet
- // java.util.TreeSet.headSet(java.lang.Object)
- Set s = ts.headSet(new Integer(100));
- assertEquals("Returned set of incorrect size", 100, s.size());
- for (int i = 0; i < 100; i++)
- assertTrue("Returned incorrect set", s.contains(objArray[i]));
-
- SortedSet sort = ts.headSet(new Integer(100));
- try {
- sort.headSet(new Integer(101));
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- ts.headSet(this);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- try {
- ts.headSet(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.TreeSet#isEmpty()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isEmpty",
- args = {}
- )
- public void test_isEmpty() {
- // Test for method boolean java.util.TreeSet.isEmpty()
- assertTrue("Empty set returned false", new TreeSet().isEmpty());
- assertTrue("Non-Empty returned true", !ts.isEmpty());
- }
-
- /**
- * @tests java.util.TreeSet#iterator()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "iterator",
- args = {}
- )
- public void test_iterator() {
- // Test for method java.util.Iterator java.util.TreeSet.iterator()
- TreeSet s = new TreeSet();
- s.addAll(ts);
- Iterator i = ts.iterator();
- Set as = new HashSet(Arrays.asList(objArray));
- while (i.hasNext())
- as.remove(i.next());
- assertEquals("Returned incorrect iterator", 0, as.size());
-
- }
-
- /**
- * @tests java.util.TreeSet#last()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "last",
- args = {}
- )
- public void test_last() {
- // Test for method java.lang.Object java.util.TreeSet.last()
- assertTrue("Returned incorrect last element",
- ts.last() == objArray[objArray.length - 1]);
-
- ts = new TreeSet();
- try {
- ts.last();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.TreeSet#remove(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_removeLjava_lang_Object() {
- // Test for method boolean java.util.TreeSet.remove(java.lang.Object)
- ts.remove(objArray[0]);
- assertTrue("Failed to remove object", !ts.contains(objArray[0]));
- assertTrue("Failed to change size after remove",
- ts.size() == objArray.length - 1);
- try {
- ts.remove(new Object());
- } catch (ClassCastException e) {
- // Correct
- return;
- }
- fail("Failed to throw exception when past uncomparable value");
- }
-
- /**
- * @tests java.util.TreeSet#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- public void test_size() {
- // Test for method int java.util.TreeSet.size()
- assertTrue("Returned incorrect size", ts.size() == objArray.length);
- }
-
- /**
- * @tests java.util.TreeSet#subSet(java.lang.Object, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "subSet",
- args = {java.lang.Object.class, java.lang.Object.class}
- )
- public void test_subSetLjava_lang_ObjectLjava_lang_Object() {
- // Test for method java.util.SortedSet
- // java.util.TreeSet.subSet(java.lang.Object, java.lang.Object)
- final int startPos = objArray.length / 4;
- final int endPos = 3 * objArray.length / 4;
- SortedSet aSubSet = ts.subSet(objArray[startPos], objArray[endPos]);
- assertTrue("Subset has wrong number of elements",
- aSubSet.size() == (endPos - startPos));
- for (int counter = startPos; counter < endPos; counter++)
- assertTrue("Subset does not contain all the elements it should",
- aSubSet.contains(objArray[counter]));
-
- try {
- ts.subSet(objArray[3], objArray[0]);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- ts.subSet(null, objArray[3]);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- try {
- ts.subSet(objArray[3], null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
-
- try {
- ts.subSet(objArray[3], this);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.TreeSet#tailSet(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "tailSet",
- args = {java.lang.Object.class}
- )
- public void test_tailSetLjava_lang_Object() {
- // Test for method java.util.SortedSet
- // java.util.TreeSet.tailSet(java.lang.Object)
- Set s = ts.tailSet(new Integer(900));
- assertEquals("Returned set of incorrect size", 100, s.size());
- for (int i = 900; i < objArray.length; i++)
- assertTrue("Returned incorrect set", s.contains(objArray[i]));
-
- SortedSet sort = ts.tailSet(new Integer(101));
-
- try {
- sort.tailSet(new Integer(100));
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- ts.tailSet(this);
- fail("ClassCastException expected");
- } catch (ClassCastException e) {
- //expected
- }
-
- try {
- ts.tailSet(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * Tests equals() method.
- * Tests that no ClassCastException will be thrown in all cases.
- * Regression test for HARMONY-1639.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equals() throws Exception {
- // comparing TreeSets with different object types
- Set s1 = new TreeSet();
- Set s2 = new TreeSet();
- s1.add("key1");
- s1.add("key2");
- s2.add(new Integer(1));
- s2.add(new Integer(2));
- assertFalse("Sets should not be equal 1", s1.equals(s2));
- assertFalse("Sets should not be equal 2", s2.equals(s1));
-
- // comparing TreeSet with HashSet
- s1 = new TreeSet();
- s2 = new HashSet();
- s1.add("key");
- s2.add(new Object());
- assertFalse("Sets should not be equal 3", s1.equals(s2));
- assertFalse("Sets should not be equal 4", s2.equals(s1));
-
- // comparing TreeSets with not-comparable objects inside
- s1 = new TreeSet();
- s2 = new TreeSet();
- s1.add(new Object());
- s2.add(new Object());
- assertFalse("Sets should not be equal 5", s1.equals(s2));
- assertFalse("Sets should not be equal 6", s2.equals(s1));
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- ts = new TreeSet();
- for (int i = 0; i < objArray.length; i++) {
- Object x = objArray[i] = new Integer(i);
- ts.add(x);
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/VectorTest.java b/luni/src/test/java/tests/api/java/util/VectorTest.java
deleted file mode 100644
index f8acc20..0000000
--- a/luni/src/test/java/tests/api/java/util/VectorTest.java
+++ /dev/null
@@ -1,1498 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Enumeration;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.NoSuchElementException;
-import java.util.Vector;
-
-import tests.support.Support_ListTest;
-
-@TestTargetClass(Vector.class)
-public class VectorTest extends junit.framework.TestCase {
-
- private Vector tVector = new Vector();
-
- Object[] objArray;
-
- private String vString = "[Test 0, Test 1, Test 2, Test 3, Test 4, Test 5, Test 6, Test 7, Test 8, Test 9, Test 10, Test 11, Test 12, Test 13, Test 14, Test 15, Test 16, Test 17, Test 18, Test 19, Test 20, Test 21, Test 22, Test 23, Test 24, Test 25, Test 26, Test 27, Test 28, Test 29, Test 30, Test 31, Test 32, Test 33, Test 34, Test 35, Test 36, Test 37, Test 38, Test 39, Test 40, Test 41, Test 42, Test 43, Test 44, Test 45, Test 46, Test 47, Test 48, Test 49, Test 50, Test 51, Test 52, Test 53, Test 54, Test 55, Test 56, Test 57, Test 58, Test 59, Test 60, Test 61, Test 62, Test 63, Test 64, Test 65, Test 66, Test 67, Test 68, Test 69, Test 70, Test 71, Test 72, Test 73, Test 74, Test 75, Test 76, Test 77, Test 78, Test 79, Test 80, Test 81, Test 82, Test 83, Test 84, Test 85, Test 86, Test 87, Test 88, Test 89, Test 90, Test 91, Test 92, Test 93, Test 94, Test 95, Test 96, Test 97, Test 98, Test 99]";
-
- /**
- * @tests java.util.Vector#Vector()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Vector",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.util.Vector()
-
- Vector tv = new Vector(100);
- for (int i = 0; i < 100; i++)
- tv.addElement(new Integer(i));
- new Support_ListTest("", tv).runTest();
-
- tv = new Vector(200);
- for (int i = -50; i < 150; i++)
- tv.addElement(new Integer(i));
- new Support_ListTest("", tv.subList(50, 150)).runTest();
-
- Vector v = new Vector();
- assertEquals("Vector creation failed", 0, v.size());
- assertEquals("Wrong capacity", 10, v.capacity());
- }
-
- /**
- * @tests java.util.Vector#Vector(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Vector",
- args = {int.class}
- )
- public void test_ConstructorI() {
- // Test for method java.util.Vector(int)
-
- Vector v = new Vector(100);
- assertEquals("Vector creation failed", 0, v.size());
- assertEquals("Wrong capacity", 100, v.capacity());
-
- try {
- new Vector(-1);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#Vector(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Vector",
- args = {int.class, int.class}
- )
- public void test_ConstructorII() {
- // Test for method java.util.Vector(int, int)
-
- Vector v = new Vector(2, 10);
- v.addElement(new Object());
- v.addElement(new Object());
- v.addElement(new Object());
-
- assertEquals("Failed to inc capacity by proper amount",
- 12, v.capacity());
-
- Vector grow = new Vector(3, -1);
- grow.addElement("one");
- grow.addElement("two");
- grow.addElement("three");
- grow.addElement("four");
- assertEquals("Wrong size", 4, grow.size());
- assertEquals("Wrong capacity", 6, grow.capacity());
-
- try {
- new Vector(-1, 1);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#Vector(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Vector",
- args = {java.util.Collection.class}
- )
- public void test_ConstructorLjava_util_Collection() {
- // Test for method java.util.Vector(java.util.Collection)
- Collection l = new LinkedList();
- for (int i = 0; i < 100; i++)
- l.add("Test " + i);
- Vector myVector = new Vector(l);
- assertTrue("Vector is not correct size",
- myVector.size() == objArray.length);
- for (int counter = 0; counter < objArray.length; counter++)
- assertTrue("Vector does not contain correct elements", myVector
- .contains(((List) l).get(counter)));
-
- try {
- new Vector(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#add(int, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "add",
- args = {int.class, java.lang.Object.class}
- )
- public void test_addILjava_lang_Object() {
- // Test for method void java.util.Vector.add(int, java.lang.Object)
- Object o = new Object();
- Object prev = tVector.get(45);
- tVector.add(45, o);
- assertTrue("Failed to add Object", tVector.get(45) == o);
- assertTrue("Failed to fix-up existing indices", tVector.get(46) == prev);
- assertEquals("Wrong size after add", 101, tVector.size());
-
- prev = tVector.get(50);
- tVector.add(50, null);
- assertNull("Failed to add null", tVector.get(50));
- assertTrue("Failed to fix-up existing indices after adding null",
- tVector.get(51) == prev);
- assertEquals("Wrong size after add", 102, tVector.size());
-
- try {
- tVector.add(-5, null);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.add(tVector.size() + 1, null);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#add(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "add",
- args = {java.lang.Object.class}
- )
- public void test_addLjava_lang_Object() {
- // Test for method boolean java.util.Vector.add(java.lang.Object)
- Object o = new Object();
- tVector.add(o);
- assertTrue("Failed to add Object", tVector.lastElement() == o);
- assertEquals("Wrong size after add", 101, tVector.size());
-
- tVector.add(null);
- assertNull("Failed to add null", tVector.lastElement());
- assertEquals("Wrong size after add", 102, tVector.size());
- }
-
- /**
- * @tests java.util.Vector#addAll(int, java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addAll",
- args = {int.class, java.util.Collection.class}
- )
- public void test_addAllILjava_util_Collection() {
- // Test for method boolean java.util.Vector.addAll(int,
- // java.util.Collection)
- Collection l = new LinkedList();
- for (int i = 0; i < 100; i++)
- l.add("Test " + i);
- Vector v = new Vector();
- tVector.addAll(50, l);
- for (int i = 50; i < 100; i++)
- assertTrue("Failed to add all elements",
- tVector.get(i) == ((List) l).get(i - 50));
- v = new Vector();
- v.add("one");
- int r = 0;
- try {
- v.addAll(3, Arrays.asList(new String[] { "two", "three" }));
- } catch (ArrayIndexOutOfBoundsException e) {
- r = 1;
- } catch (IndexOutOfBoundsException e) {
- r = 2;
- }
- assertTrue("Invalid add: " + r, r == 1);
- l = new LinkedList();
- l.add(null);
- l.add("gah");
- l.add(null);
- tVector.addAll(50, l);
- assertNull("Wrong element at position 50--wanted null",
- tVector.get(50));
- assertEquals("Wrong element at position 51--wanted 'gah'", "gah", tVector
- .get(51));
- assertNull("Wrong element at position 52--wanted null",
- tVector.get(52));
-
- try {
- tVector.addAll(-5, Arrays.asList(new String[] { "two", "three" }));
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.addAll(tVector.size() + 1, Arrays.asList(new String[] { "two", "three" }));
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.addAll(tVector.size() / 2, null);
- fail("NullPointerException expected");
- } catch(NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#addAll(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addAll",
- args = {java.util.Collection.class}
- )
- public void test_addAllLjava_util_Collection() {
- // Test for method boolean java.util.Vector.addAll(java.util.Collection)
- Vector v = new Vector();
- Collection l = new LinkedList();
- for (int i = 0; i < 100; i++)
- l.add("Test " + i);
- v.addAll(l);
- assertTrue("Failed to add all elements", tVector.equals(v));
-
- v.addAll(l);
- int vSize = tVector.size();
- for (int counter = vSize - 1; counter >= 0; counter--)
- assertTrue("Failed to add elements correctly", v.get(counter) == v
- .get(counter + vSize));
-
- l = new LinkedList();
- l.add(null);
- l.add("gah");
- l.add(null);
- tVector.addAll(l);
- assertNull("Wrong element at 3rd last position--wanted null", tVector
- .get(vSize));
- assertEquals("Wrong element at 2nd last position--wanted 'gah'", "gah", tVector
- .get(vSize + 1));
- assertNull("Wrong element at last position--wanted null", tVector
- .get(vSize + 2));
-
- try {
- tVector.addAll(tVector.size() / 2, null);
- fail("NullPointerException expected");
- } catch(NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#addElement(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addElement",
- args = {java.lang.Object.class}
- )
- public void test_addElementLjava_lang_Object() {
- // Test for method void java.util.Vector.addElement(java.lang.Object)
- Vector v = vectorClone(tVector);
- v.addElement("Added Element");
- assertTrue("Failed to add element", v.contains("Added Element"));
- assertEquals("Added Element to wrong slot", "Added Element", ((String) v.elementAt(100))
- );
- v.addElement(null);
- assertTrue("Failed to add null", v.contains(null));
- assertNull("Added null to wrong slot", v.elementAt(101));
- }
-
- /**
- * @tests java.util.Vector#addElement(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "addElement",
- args = {java.lang.Object.class}
- )
- public void test_addElementLjava_lang_Object_subtest0() {
- // Test for method void java.util.Vector.addElement(java.lang.Object)
- Vector v = vectorClone(tVector);
- v.addElement("Added Element");
- assertTrue("Failed to add element", v.contains("Added Element"));
- assertEquals("Added Element to wrong slot", "Added Element", ((String) v.elementAt(100))
- );
- v.addElement(null);
- assertTrue("Failed to add null", v.contains(null));
- assertNull("Added null to wrong slot", v.elementAt(101));
- }
-
- /**
- * @tests java.util.Vector#capacity()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "capacity",
- args = {}
- )
- public void test_capacity() {
- // Test for method int java.util.Vector.capacity()
-
- Vector v = new Vector(9);
- assertEquals("Incorrect capacity returned", 9, v.capacity());
- }
-
- /**
- * @tests java.util.Vector#clear()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- )
- public void test_clear() {
- // Test for method void java.util.Vector.clear()
- Vector orgVector = vectorClone(tVector);
- tVector.clear();
- assertEquals("a) Cleared Vector has non-zero size", 0, tVector.size());
- Enumeration e = orgVector.elements();
- while (e.hasMoreElements())
- assertTrue("a) Cleared vector contained elements", !tVector
- .contains(e.nextElement()));
-
- tVector.add(null);
- tVector.clear();
- assertEquals("b) Cleared Vector has non-zero size", 0, tVector.size());
- e = orgVector.elements();
- while (e.hasMoreElements())
- assertTrue("b) Cleared vector contained elements", !tVector
- .contains(e.nextElement()));
- }
-
- /**
- * @tests java.util.Vector#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- // Test for method java.lang.Object java.util.Vector.clone()
- tVector.add(25, null);
- tVector.add(75, null);
- Vector v = (Vector) tVector.clone();
- Enumeration orgNum = tVector.elements();
- Enumeration cnum = v.elements();
-
- while (orgNum.hasMoreElements()) {
- assertTrue("Not enough elements copied", cnum.hasMoreElements());
- assertTrue("Vector cloned improperly, elements do not match",
- orgNum.nextElement() == cnum.nextElement());
- }
- assertTrue("Not enough elements copied", !cnum.hasMoreElements());
-
- }
-
- /**
- * @tests java.util.Vector#contains(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "contains",
- args = {java.lang.Object.class}
- )
- public void test_containsLjava_lang_Object() {
- // Test for method boolean java.util.Vector.contains(java.lang.Object)
- assertTrue("Did not find element", tVector.contains("Test 42"));
- assertTrue("Found bogus element", !tVector.contains("Hello"));
- assertTrue(
- "Returned true looking for null in vector without null element",
- !tVector.contains(null));
- tVector.insertElementAt(null, 20);
- assertTrue(
- "Returned false looking for null in vector with null element",
- tVector.contains(null));
- }
-
- /**
- * @tests java.util.Vector#containsAll(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "containsAll",
- args = {java.util.Collection.class}
- )
- public void test_containsAllLjava_util_Collection() {
- // Test for method boolean
- // java.util.Vector.containsAll(java.util.Collection)
- Collection s = new HashSet();
- for (int i = 0; i < 100; i++)
- s.add("Test " + i);
-
- assertTrue("Returned false for valid collection", tVector
- .containsAll(s));
- s.add(null);
- assertTrue("Returned true for invlaid collection containing null",
- !tVector.containsAll(s));
- tVector.add(25, null);
- assertTrue("Returned false for valid collection containing null",
- tVector.containsAll(s));
- s = new HashSet();
- s.add(new Object());
- assertTrue("Returned true for invalid collection", !tVector
- .containsAll(s));
-
- try {
- tVector.containsAll(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#copyInto(java.lang.Object[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "copyInto",
- args = {java.lang.Object[].class}
- )
- public void test_copyInto$Ljava_lang_Object() {
- // Test for method void java.util.Vector.copyInto(java.lang.Object [])
-
- Object[] a = new Object[100];
- tVector.setElementAt(null, 20);
- tVector.copyInto(a);
-
- for (int i = 0; i < 100; i++)
- assertTrue("copyInto failed", a[i] == tVector.elementAt(i));
-
- try {
- tVector.copyInto(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#elementAt(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "elementAt",
- args = {int.class}
- )
- public void test_elementAtI() {
- // Test for method java.lang.Object java.util.Vector.elementAt(int)
- assertEquals("Incorrect element returned", "Test 18", ((String) tVector
- .elementAt(18)));
- tVector.setElementAt(null, 20);
- assertNull("Incorrect element returned--wanted null", tVector
- .elementAt(20));
-
- try {
- tVector.elementAt(-5);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.elementAt(tVector.size() + 1);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#elements()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "elements",
- args = {}
- )
- public void test_elements() {
- // Test for method java.util.Enumeration java.util.Vector.elements()
- tVector.insertElementAt(null, 20);
- Enumeration e = tVector.elements();
- int i = 0;
- while (e.hasMoreElements()) {
- assertTrue("Enumeration returned incorrect element at pos: " + i, e
- .nextElement() == tVector.elementAt(i));
- i++;
- }
- assertTrue("Invalid enumeration", i == tVector.size());
- }
-
- /**
- * @tests java.util.Vector#elements()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "elements",
- args = {}
- )
- public void test_elements_subtest0() {
- final int iterations = 10000;
- final Vector v = new Vector();
- Thread t1 = new Thread() {
- public void run() {
- for (int i = 0; i < iterations; i++) {
- synchronized (v) {
- v.addElement(String.valueOf(i));
- v.removeElementAt(0);
- }
- }
- }
- };
- t1.start();
- for (int i = 0; i < iterations; i++) {
- Enumeration en = v.elements();
- try {
- while (true) {
- Object result = en.nextElement();
- if (result == null) {
- fail("Null result: " + i);
- }
- }
- } catch (NoSuchElementException e) {
- }
- }
- }
-
- /**
- * @tests java.util.Vector#ensureCapacity(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ensureCapacity",
- args = {int.class}
- )
- public void test_ensureCapacityI() {
- // Test for method void java.util.Vector.ensureCapacity(int)
-
- Vector v = new Vector(9);
- v.ensureCapacity(20);
- assertEquals("ensureCapacity failed to set correct capacity", 20, v
- .capacity());
- v = new Vector(100);
- assertEquals("ensureCapacity reduced capacity", 100, v.capacity());
- }
-
- /**
- * @tests java.util.Vector#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean java.util.Vector.equals(java.lang.Object)
- Vector v = new Vector();
- for (int i = 0; i < 100; i++)
- v.addElement("Test " + i);
- assertTrue("a) Equal vectors returned false", tVector.equals(v));
- v.addElement(null);
- assertTrue("b) UnEqual vectors returned true", !tVector.equals(v));
- tVector.addElement(null);
- assertTrue("c) Equal vectors returned false", tVector.equals(v));
- tVector.removeElementAt(22);
- assertTrue("d) UnEqual vectors returned true", !tVector.equals(v));
- }
-
- /**
- * @tests java.util.Vector#firstElement()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "firstElement",
- args = {}
- )
- public void test_firstElement() {
- // Test for method java.lang.Object java.util.Vector.firstElement()
- assertEquals("Returned incorrect firstElement", "Test 0", tVector.firstElement()
- );
- tVector.insertElementAt(null, 0);
- assertNull("Returned incorrect firstElement--wanted null", tVector
- .firstElement());
-
- tVector = new Vector(10);
-
- try {
- tVector.firstElement();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#get(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {int.class}
- )
- public void test_getI() {
- // Test for method java.lang.Object java.util.Vector.get(int)
- assertEquals("Get returned incorrect object",
- "Test 80", tVector.get(80));
- tVector.add(25, null);
- assertNull("Returned incorrect element--wanted null",
- tVector.get(25));
-
- try {
- tVector.get(-5);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.get(tVector.size() + 1);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- // Test for method int java.util.Vector.hashCode()
- int hashCode = 1; // one
- tVector.insertElementAt(null, 20);
- for (int i = 0; i < tVector.size(); i++) {
- Object obj = tVector.elementAt(i);
- hashCode = 31 * hashCode + (obj == null ? 0 : obj.hashCode());
- }
- assertTrue("Incorrect hashCode returned. Wanted: " + hashCode
- + " got: " + tVector.hashCode(), tVector.hashCode() == hashCode);
- }
-
- /**
- * @tests java.util.Vector#indexOf(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "indexOf",
- args = {java.lang.Object.class}
- )
- public void test_indexOfLjava_lang_Object() {
- // Test for method int java.util.Vector.indexOf(java.lang.Object)
- assertEquals("Incorrect index returned", 10, tVector.indexOf("Test 10"));
- assertEquals("Index returned for invalid Object", -1, tVector
- .indexOf("XXXXXXXXXXX"));
- tVector.setElementAt(null, 20);
- tVector.setElementAt(null, 40);
- assertTrue("Incorrect indexOf returned for null: "
- + tVector.indexOf(null), tVector.indexOf(null) == 20);
- }
-
- /**
- * @tests java.util.Vector#indexOf(java.lang.Object, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "indexOf",
- args = {java.lang.Object.class, int.class}
- )
- public void test_indexOfLjava_lang_ObjectI() {
- // Test for method int java.util.Vector.indexOf(java.lang.Object, int)
- assertTrue("Failed to find correct index", (tVector.indexOf("Test 98",
- 50) == 98));
- assertTrue("Found index of bogus element", (tVector.indexOf(
- "Test 1001", 50) == -1));
- tVector.setElementAt(null, 20);
- tVector.setElementAt(null, 40);
- tVector.setElementAt(null, 60);
- assertTrue("a) Incorrect indexOf returned for null: "
- + tVector.indexOf(null, 25), tVector.indexOf(null, 25) == 40);
- assertTrue("b) Incorrect indexOf returned for null: "
- + tVector.indexOf(null, 20), tVector.indexOf(null, 20) == 20);
-
- try {
- tVector.indexOf(null, -1);
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#insertElementAt(java.lang.Object, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "insertElementAt",
- args = {java.lang.Object.class, int.class}
- )
- public void test_insertElementAtLjava_lang_ObjectI() {
- // Test for method void
- // java.util.Vector.insertElementAt(java.lang.Object, int)
- Vector v = vectorClone(tVector);
- String prevElement = (String) v.elementAt(99);
- v.insertElementAt("Inserted Element", 99);
- assertEquals("Element not inserted", "Inserted Element", ((String) v.elementAt(99))
- );
- assertTrue("Elements shifted incorrectly", ((String) v.elementAt(100))
- .equals(prevElement));
- v.insertElementAt(null, 20);
- assertNull("null not inserted", v.elementAt(20));
-
- try {
- tVector.insertElementAt(null, -5);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.insertElementAt(null, tVector.size() + 1);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#isEmpty()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isEmpty",
- args = {}
- )
- public void test_isEmpty() {
- // Test for method boolean java.util.Vector.isEmpty()Vector
- Vector v = new java.util.Vector();
- assertTrue("Empty vector returned false", v.isEmpty());
- v.addElement(new Object());
- assertTrue("non-Empty vector returned true", !v.isEmpty());
- }
-
- /**
- * @tests java.util.Vector#isEmpty()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isEmpty",
- args = {}
- )
- public void test_isEmpty_subtest0() {
- final Vector v = new Vector();
- v.addElement("initial");
- Thread t1 = new Thread() {
- public void run() {
- while (!v.isEmpty())
- ;
- v.addElement("final");
- }
- };
- t1.start();
- for (int i = 0; i < 10000; i++) {
- synchronized (v) {
- v.removeElementAt(0);
- v.addElement(String.valueOf(i));
- }
- int size;
- if ((size = v.size()) != 1) {
- String result = "Size is not 1: " + size + " " + v;
- // terminate the thread
- v.removeAllElements();
- fail(result);
- }
- }
- // terminate the thread
- v.removeElementAt(0);
- }
-
- /**
- * @tests java.util.Vector#lastElement()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lastElement",
- args = {}
- )
- public void test_lastElement() {
- // Test for method java.lang.Object java.util.Vector.lastElement()
- assertEquals("Incorrect last element returned", "Test 99", tVector.lastElement()
- );
- tVector.addElement(null);
- assertNull("Incorrect last element returned--wanted null", tVector
- .lastElement());
-
- tVector = new Vector(10);
-
- try {
- tVector.lastElement();
- fail("NoSuchElementException expected");
- } catch (NoSuchElementException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#lastIndexOf(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lastIndexOf",
- args = {java.lang.Object.class}
- )
- public void test_lastIndexOfLjava_lang_Object() {
- // Test for method int java.util.Vector.lastIndexOf(java.lang.Object)
- Vector v = new Vector(9);
- for (int i = 0; i < 9; i++)
- v.addElement("Test");
- v.addElement("z");
- assertEquals("Failed to return correct index", 8, v.lastIndexOf("Test"));
- tVector.setElementAt(null, 20);
- tVector.setElementAt(null, 40);
- assertTrue("Incorrect lastIndexOf returned for null: "
- + tVector.lastIndexOf(null), tVector.lastIndexOf(null) == 40);
- }
-
- /**
- * @tests java.util.Vector#lastIndexOf(java.lang.Object, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "lastIndexOf",
- args = {java.lang.Object.class, int.class}
- )
- public void test_lastIndexOfLjava_lang_ObjectI() {
- // Test for method int java.util.Vector.lastIndexOf(java.lang.Object,
- // int)
- assertEquals("Failed to find object",
- 0, tVector.lastIndexOf("Test 0", 0));
- assertTrue("Found Object outside of index", (tVector.lastIndexOf(
- "Test 0", 10) > -1));
- tVector.setElementAt(null, 20);
- tVector.setElementAt(null, 40);
- tVector.setElementAt(null, 60);
- assertTrue("Incorrect lastIndexOf returned for null: "
- + tVector.lastIndexOf(null, 15),
- tVector.lastIndexOf(null, 15) == -1);
- assertTrue("Incorrect lastIndexOf returned for null: "
- + tVector.lastIndexOf(null, 45),
- tVector.lastIndexOf(null, 45) == 40);
-
- try {
- tVector.lastIndexOf(null, tVector.size());
- fail("IndexOutOfBoundsException expected");
- } catch (IndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#remove(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {int.class}
- )
- public void test_removeI() {
- // Test for method java.lang.Object java.util.Vector.remove(int)
- tVector.remove(36);
- assertTrue("Contained element after remove", !tVector
- .contains("Test 36"));
- assertEquals("Failed to decrement size after remove",
- 99, tVector.size());
- tVector.add(20, null);
- tVector.remove(19);
- assertNull("Didn't move null element over", tVector.get(19));
- tVector.remove(19);
- assertNotNull("Didn't remove null element", tVector.get(19));
- assertEquals("Failed to decrement size after removing null", 98, tVector
- .size());
-
- try {
- tVector.remove(-5);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.remove(tVector.size() + 1);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#remove(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_removeLjava_lang_Object() {
- // Test for method boolean java.util.Vector.remove(java.lang.Object)
- tVector.remove("Test 0");
- assertTrue("Contained element after remove", !tVector
- .contains("Test 0"));
- assertEquals("Failed to decrement size after remove",
- 99, tVector.size());
- tVector.add(null);
- tVector.remove(null);
- assertTrue("Contained null after remove", !tVector.contains(null));
- assertEquals("Failed to decrement size after removing null", 99, tVector
- .size());
- }
-
- /**
- * @tests java.util.Vector#removeAll(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "removeAll",
- args = {java.util.Collection.class}
- )
- public void test_removeAllLjava_util_Collection() {
- // Test for method boolean
- // java.util.Vector.removeAll(java.util.Collection)
- Vector v = new Vector();
- Collection l = new LinkedList();
- for (int i = 0; i < 5; i++)
- l.add("Test " + i);
- v.addElement(l);
-
- Collection s = new HashSet();
- Object o;
- s.add(o = v.firstElement());
- v.removeAll(s);
- assertTrue("Failed to remove items in collection", !v.contains(o));
- v.removeAll(l);
- assertTrue("Failed to remove all elements", v.isEmpty());
-
- v.add(null);
- v.add(null);
- v.add("Boom");
- v.removeAll(s);
- assertEquals("Should not have removed any elements", 3, v.size());
- l = new LinkedList();
- l.add(null);
- v.removeAll(l);
- assertEquals("Should only have one element", 1, v.size());
- assertEquals("Element should be 'Boom'", "Boom", v.firstElement());
-
- try {
- v.removeAll(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#removeAllElements()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "removeAllElements",
- args = {}
- )
- public void test_removeAllElements() {
- // Test for method void java.util.Vector.removeAllElements()
- Vector v = vectorClone(tVector);
- v.removeAllElements();
- assertEquals("Failed to remove all elements", 0, v.size());
- }
-
- /**
- * @tests java.util.Vector#removeElement(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Doesn't check negative case.",
- method = "removeElement",
- args = {java.lang.Object.class}
- )
- public void test_removeElementLjava_lang_Object() {
- // Test for method boolean
- // java.util.Vector.removeElement(java.lang.Object)
- Vector v = vectorClone(tVector);
- v.removeElement("Test 98");
- assertEquals("Element not removed", "Test 99", ((String) v.elementAt(98))
- );
- assertTrue("Vector is wrong size after removal: " + v.size(),
- v.size() == 99);
- tVector.addElement(null);
- v.removeElement(null);
- assertTrue("Vector is wrong size after removing null: " + v.size(), v
- .size() == 99);
- }
-
- /**
- * @tests java.util.Vector#removeElementAt(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "removeElementAt",
- args = {int.class}
- )
- public void test_removeElementAtI() {
- // Test for method void java.util.Vector.removeElementAt(int)
- Vector v = vectorClone(tVector);
- v.removeElementAt(50);
- assertEquals("Failed to remove element", -1, v.indexOf("Test 50", 0));
- tVector.insertElementAt(null, 60);
- tVector.removeElementAt(60);
- assertNotNull("Element at 60 should not be null after removal", tVector
- .elementAt(60));
-
- try {
- tVector.elementAt(-5);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.elementAt(tVector.size() + 1);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#retainAll(java.util.Collection)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "retainAll",
- args = {java.util.Collection.class}
- )
- public void test_retainAllLjava_util_Collection() {
- // Test for method boolean
- // java.util.Vector.retainAll(java.util.Collection)
- Object o = tVector.firstElement();
- tVector.add(null);
- Collection s = new HashSet();
- s.add(o);
- s.add(null);
- tVector.retainAll(s);
- assertTrue("Retained items other than specified", tVector.size() == 2
- && tVector.contains(o) && tVector.contains(null));
-
- Iterator i = s.iterator();
-
- while (i.hasNext()) {
- assertTrue(tVector.contains(i.next()));
- }
-
- try {
- tVector.retainAll(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#set(int, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "set",
- args = {int.class, java.lang.Object.class}
- )
- public void test_setILjava_lang_Object() {
- // Test for method java.lang.Object java.util.Vector.set(int,
- // java.lang.Object)
- Object o = new Object();
- tVector.set(23, o);
- assertTrue("Failed to set Object", tVector.get(23) == o);
-
- try {
- tVector.set(-5, "Wrong position");
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.set(tVector.size() + 1, "Wrong position");
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#setElementAt(java.lang.Object, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setElementAt",
- args = {java.lang.Object.class, int.class}
- )
- public void test_setElementAtLjava_lang_ObjectI() {
- // Test for method void java.util.Vector.setElementAt(java.lang.Object,
- // int)
- Vector v = vectorClone(tVector);
- v.setElementAt("Inserted Element", 99);
- assertEquals("Element not set", "Inserted Element", ((String) v.elementAt(99))
- );
-
- try {
- tVector.setElementAt("Wrong position", -5);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.setElementAt("Wrong position", tVector.size() + 1);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#setSize(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setSize",
- args = {int.class}
- )
- public void test_setSizeI() {
- // Test for method void java.util.Vector.setSize(int)
- Vector v = vectorClone(tVector);
- v.setSize(10);
- assertEquals("Failed to set size", 10, v.size());
-
- try {
- tVector.setSize(-5);
- fail("ArrayIndexOutOfBoundsException expected");
- } catch(ArrayIndexOutOfBoundsException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- public void test_size() {
- // Test for method int java.util.Vector.size()
- assertEquals("Returned incorrect size", 100, tVector.size());
-
- final Vector v = new Vector();
- v.addElement("initial");
- Thread t1 = new Thread() {
- public void run() {
- while (v.size() > 0)
- ;
- v.addElement("final");
- }
- };
- t1.start();
- for (int i = 0; i < 10000; i++) {
- synchronized (v) {
- v.removeElementAt(0);
- v.addElement(String.valueOf(i));
- }
- int size;
- if ((size = v.size()) != 1) {
- String result = "Size is not 1: " + size + " " + v;
- // terminate the thread
- v.removeAllElements();
- fail(result);
- }
- }
- // terminate the thread
- v.removeElementAt(0);
- }
-
- /**
- * @tests java.util.Vector#subList(int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "subList",
- args = {int.class, int.class}
- )
- public void test_subListII() {
- // Test for method java.util.List java.util.Vector.subList(int, int)
- List sl = tVector.subList(10, 25);
- assertEquals("Returned sublist of incorrect size", 15, sl.size());
- for (int i = 10; i < 25; i++)
- assertTrue("Returned incorrect sublist", sl
- .contains(tVector.get(i)));
-
- assertEquals("Not synchronized random access", "java.util.Collections$SynchronizedRandomAccessList", sl.getClass().getName()
- );
-
- try {
- tVector.subList(-10, 25);
- fail("IndexOutOfBoundsException expected");
- } catch(IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.subList(10, tVector.size() + 1);
- fail("IndexOutOfBoundsException expected");
- } catch(IndexOutOfBoundsException e) {
- //expected
- }
-
- try {
- tVector.subList(25, 10);
- fail("IllegalArgumentException expected");
- } catch(IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#toArray()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toArray",
- args = {}
- )
- public void test_toArray() {
- // Test for method java.lang.Object [] java.util.Vector.toArray()
- assertTrue("Returned incorrect array", Arrays.equals(objArray, tVector
- .toArray()));
- }
-
- /**
- * @tests java.util.Vector#toArray(java.lang.Object[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toArray",
- args = {java.lang.Object[].class}
- )
- public void test_toArray$Ljava_lang_Object() {
- // Test for method java.lang.Object []
- // java.util.Vector.toArray(java.lang.Object [])
- Object[] o = new Object[1000];
- Object f = new Object();
- for (int i = 0; i < o.length; i++)
- o[i] = f;
- tVector.toArray(o);
- assertNull("Failed to set slot to null", o[100]);
- for (int i = 0; i < tVector.size(); i++)
- assertTrue("Returned incorrect array", tVector.elementAt(i) == o[i]);
-
- try {
- tVector.toArray(null);
- fail("NullPointerException expected");
- } catch(NullPointerException e) {
- //expected
- }
- tVector = new Vector<Integer>();
- tVector.add(new Integer(1));
- tVector.add(new Integer(2));
- tVector.add(new Integer(3));
- try {
- tVector.toArray(new String[tVector.size()]);
- fail("ArrayStoreException expected");
- } catch(ArrayStoreException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.Vector#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.util.Vector.toString()
- assertTrue("Incorrect String returned", tVector.toString().equals(
- vString));
-
- Vector v = new Vector();
- v.addElement("one");
- v.addElement(v);
- v.addElement("3");
- // test last element
- v.addElement(v);
- String result = v.toString();
- assertTrue("should contain self ref", result.indexOf("(this") > -1);
- }
-
- /**
- * @tests java.util.Vector#trimToSize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "trimToSize",
- args = {}
- )
- public void test_trimToSize() {
- // Test for method void java.util.Vector.trimToSize()
- Vector v = new Vector(10);
- v.addElement(new Object());
- v.trimToSize();
- assertEquals("Failed to trim capacity", 1, v.capacity());
- }
-
- class Mock_Vector extends Vector {
- @Override
- protected void removeRange(int from, int to) {
- super.removeRange(from, to);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "removeRange",
- args = {int.class, int.class}
- )
- public void test_removeRangeII() {
- Mock_Vector mv = new Mock_Vector();
- mv.add("First");
- mv.add("Second");
- mv.add("One more");
- mv.add("Last");
- mv.removeRange(1, 3);
- assertTrue(mv.contains("First"));
- assertFalse(mv.contains("Second"));
- assertFalse(mv.contains("One more"));
- assertTrue(mv.contains("Last"));
- }
-
- protected Vector vectorClone(Vector s) {
- return (Vector) s.clone();
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- for (int i = 0; i < 100; i++) {
- tVector.addElement("Test " + i);
- }
- objArray = new Object[100];
- for (int i = 0; i < 100; i++) {
- objArray[i] = "Test " + i;
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/WeakHashMapTest.java b/luni/src/test/java/tests/api/java/util/WeakHashMapTest.java
deleted file mode 100644
index 82366c4..0000000
--- a/luni/src/test/java/tests/api/java/util/WeakHashMapTest.java
+++ /dev/null
@@ -1,525 +0,0 @@
-/*
- * 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 tests.api.java.util;
-
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-
-import java.util.AbstractMap;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.WeakHashMap;
-
-import tests.support.Support_MapTest2;
-
-@TestTargetClass(WeakHashMap.class)
-public class WeakHashMapTest extends junit.framework.TestCase {
- class MockMap extends AbstractMap {
- public Set entrySet() {
- return null;
- }
- public int size(){
- return 0;
- }
- }
-
- Object[] keyArray = new Object[100];
-
- Object[] valueArray = new Object[100];
-
- WeakHashMap whm;
-
- /**
- * @tests java.util.WeakHashMap#WeakHashMap()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "WeakHashMap",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {java.lang.Object.class}
- )
- })
- public void test_Constructor() {
- // Test for method java.util.WeakHashMap()
- new Support_MapTest2(new WeakHashMap()).runTest();
-
- whm = new WeakHashMap();
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
- for (int i = 0; i < 100; i++)
- assertTrue("Incorrect value retrieved",
- whm.get(keyArray[i]) == valueArray[i]);
-
- }
-
- /**
- * @tests java.util.WeakHashMap#WeakHashMap(int)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "WeakHashMap",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {java.lang.Object.class}
- )
- })
- public void test_ConstructorI() {
- // Test for method java.util.WeakHashMap(int)
- whm = new WeakHashMap(50);
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
- for (int i = 0; i < 100; i++)
- assertTrue("Incorrect value retrieved",
- whm.get(keyArray[i]) == valueArray[i]);
-
- WeakHashMap empty = new WeakHashMap(0);
- assertNull("Empty weakhashmap access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
-
- try {
- new WeakHashMap(-50);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.WeakHashMap#WeakHashMap(int, float)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "WeakHashMap",
- args = {int.class, float.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {java.lang.Object.class}
- )
- })
- public void test_ConstructorIF() {
- // Test for method java.util.WeakHashMap(int, float)
- whm = new WeakHashMap(50, 0.5f);
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
- for (int i = 0; i < 100; i++)
- assertTrue("Incorrect value retrieved",
- whm.get(keyArray[i]) == valueArray[i]);
-
- WeakHashMap empty = new WeakHashMap(0, 0.75f);
- assertNull("Empty hashtable access", empty.get("nothing"));
- empty.put("something", "here");
- assertTrue("cannot get element", empty.get("something") == "here");
-
- try {
- new WeakHashMap(50, -0.5f);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
-
- try {
- new WeakHashMap(-50, 0.5f);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.WeakHashMap#WeakHashMap(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "WeakHashMap",
- args = {java.util.Map.class}
- )
- public void test_ConstructorLjava_util_Map() {
- Map mockMap = new MockMap();
- WeakHashMap map = new WeakHashMap(mockMap);
- assertEquals("Size should be 0", 0, map.size());
-
- try {
- new WeakHashMap(null);
- fail("NullPointerException expected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.WeakHashMap#clear()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clear",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {java.lang.Object.class}
- )
- })
- public void test_clear() {
- // Test for method boolean java.util.WeakHashMap.clear()
- whm = new WeakHashMap();
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
- whm.clear();
- assertTrue("Cleared map should be empty", whm.isEmpty());
- for (int i = 0; i < 100; i++)
- assertNull("Cleared map should only return null", whm
- .get(keyArray[i]));
-
- }
-
- /**
- * @tests java.util.WeakHashMap#containsKey(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "containsKey",
- args = {java.lang.Object.class}
- )
- public void test_containsKeyLjava_lang_Object() {
- // Test for method boolean java.util.WeakHashMap.containsKey()
- whm = new WeakHashMap();
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
- for (int i = 0; i < 100; i++)
- assertTrue("Should contain referenced key", whm
- .containsKey(keyArray[i]));
- keyArray[25] = null;
- keyArray[50] = null;
- }
-
- /**
- * @tests java.util.WeakHashMap#containsValue(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "containsValue",
- args = {java.lang.Object.class}
- )
- public void test_containsValueLjava_lang_Object() {
- // Test for method boolean java.util.WeakHashMap.containsValue()
- whm = new WeakHashMap();
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
- for (int i = 0; i < 100; i++)
- assertTrue("Should contain referenced value", whm
- .containsValue(valueArray[i]));
- keyArray[25] = null;
- keyArray[50] = null;
- }
-
- /**
- * @tests java.util.WeakHashMap#entrySet()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "entrySet",
- args = {}
- )
- public void test_entrySet() {
- // Test for method java.util.Set java.util.WeakHashMap.entrySet()
- whm = new WeakHashMap();
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
- List keys = Arrays.asList(keyArray);
- List values = Arrays.asList(valueArray);
- Set entrySet = whm.entrySet();
- assertTrue("Incorrect number of entries returned--wanted 100, got: "
- + entrySet.size(), entrySet.size() == 100);
- Iterator it = entrySet.iterator();
- while (it.hasNext()) {
- Map.Entry entry = (Map.Entry) it.next();
- assertTrue("Invalid map entry returned--bad key", keys
- .contains(entry.getKey()));
- assertTrue("Invalid map entry returned--bad key", values
- .contains(entry.getValue()));
- }
- keys = null;
- values = null;
- keyArray[50] = null;
-
- int count = 0;
- do {
- System.gc();
- System.gc();
- Runtime.getRuntime().runFinalization();
- count++;
- } while (count <= 5 && entrySet.size() == 100);
-
- assertTrue(
- "Incorrect number of entries returned after gc--wanted 99, got: "
- + entrySet.size(), entrySet.size() == 99);
- }
-
- /**
- * @tests java.util.WeakHashMap#isEmpty()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isEmpty",
- args = {}
- )
- public void test_isEmpty() {
- // Test for method boolean java.util.WeakHashMap.isEmpty()
- whm = new WeakHashMap();
- assertTrue("New map should be empty", whm.isEmpty());
- Object myObject = new Object();
- whm.put(myObject, myObject);
- assertTrue("Map should not be empty", !whm.isEmpty());
- whm.remove(myObject);
- assertTrue("Map with elements removed should be empty", whm.isEmpty());
- }
-
- /**
- * @tests java.util.WeakHashMap#put(java.lang.Object, java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "put",
- args = {java.lang.Object.class, java.lang.Object.class}
- )
- public void test_putLjava_lang_ObjectLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.WeakHashMap.put(java.lang.Object, java.lang.Object)
- WeakHashMap map = new WeakHashMap();
- map.put(null, "value"); // add null key
- System.gc();
- System.runFinalization();
- map.remove("nothing"); // Cause objects in queue to be removed
- assertEquals("null key was removed", 1, map.size());
- }
-
- /**
- * @tests java.util.WeakHashMap#putAll(java.util.Map)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "putAll",
- args = {java.util.Map.class}
- )
- public void test_putAllLjava_util_Map() {
- Map mockMap=new MockMap();
- WeakHashMap map = new WeakHashMap();
- map.putAll(mockMap);
- assertEquals("Size should be 0", 0, map.size());
-
- try {
- map.putAll(null);
- fail("NullPointerException exected");
- } catch (NullPointerException e) {
- //expected
- }
- }
-
- /**
- * @tests java.util.WeakHashMap#remove(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "remove",
- args = {java.lang.Object.class}
- )
- public void test_removeLjava_lang_Object() {
- // Test for method java.lang.Object
- // java.util.WeakHashMap.remove(java.lang.Object)
- whm = new WeakHashMap();
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
-
- assertTrue("Remove returned incorrect value",
- whm.remove(keyArray[25]) == valueArray[25]);
- assertNull("Remove returned incorrect value",
- whm.remove(keyArray[25]));
- assertEquals("Size should be 99 after remove", 99, whm.size());
- }
-
- /**
- * @tests java.util.WeakHashMap#size()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- public void test_size() {
- whm = new WeakHashMap();
- assertEquals(0, whm.size());
- }
-
- /**
- * @tests java.util.WeakHashMap#keySet()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "keySet",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- })
- public void test_keySet() {
- // Test for method java.util.Set java.util.WeakHashMap.keySet()
- whm = new WeakHashMap();
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
-
- List keys = Arrays.asList(keyArray);
- List values = Arrays.asList(valueArray);
-
- Set keySet = whm.keySet();
- assertEquals("Incorrect number of keys returned,", 100, keySet.size());
- Iterator it = keySet.iterator();
- while (it.hasNext()) {
- Object key = it.next();
- assertTrue("Invalid map entry returned--bad key", keys
- .contains(key));
- }
- keys = null;
- values = null;
- keyArray[50] = null;
-
- int count = 0;
- do {
- System.gc();
- System.gc();
- Runtime.getRuntime().runFinalization();
- count++;
- } while (count <= 5 && keySet.size() == 100);
-
- assertEquals("Incorrect number of keys returned after gc,", 99, keySet
- .size());
- }
-
- /**
- * @tests java.util.WeakHashMap#values()
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "size",
- args = {}
- )
- })
- public void test_values() {
- // Test for method java.util.Set java.util.WeakHashMap.values()
- whm = new WeakHashMap();
- for (int i = 0; i < 100; i++)
- whm.put(keyArray[i], valueArray[i]);
-
- List keys = Arrays.asList(keyArray);
- List values = Arrays.asList(valueArray);
-
- Collection valuesCollection = whm.values();
- assertEquals("Incorrect number of keys returned,", 100,
- valuesCollection.size());
- Iterator it = valuesCollection.iterator();
- while (it.hasNext()) {
- Object value = it.next();
- assertTrue("Invalid map entry returned--bad value", values
- .contains(value));
- }
- keys = null;
- values = null;
- keyArray[50] = null;
-
- int count = 0;
- do {
- System.gc();
- System.gc();
- Runtime.getRuntime().runFinalization();
- count++;
- } while (count <= 5 && valuesCollection.size() == 100);
-
- assertEquals("Incorrect number of keys returned after gc,", 99,
- valuesCollection.size());
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- for (int i = 0; i < 100; i++) {
- keyArray[i] = new Object();
- valueArray[i] = new Object();
- }
-
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/support/A.java b/luni/src/test/java/tests/api/java/util/support/A.java
deleted file mode 100644
index c2b43b5..0000000
--- a/luni/src/test/java/tests/api/java/util/support/A.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package tests.api.java.util.support;
-
-public class A implements I {
- private static P pp = new P();
-
- public A() {
- pp.setClazz(getClass());
- }
-
- public String find(String key) {
- return pp.findProp(key);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/util/support/B.java b/luni/src/test/java/tests/api/java/util/support/B.java
deleted file mode 100644
index baafdbe..0000000
--- a/luni/src/test/java/tests/api/java/util/support/B.java
+++ /dev/null
@@ -1,4 +0,0 @@
-package tests.api.java.util.support;
-
-public class B extends A {
-}
diff --git a/luni/src/test/java/tests/api/java/util/support/I.java b/luni/src/test/java/tests/api/java/util/support/I.java
deleted file mode 100644
index a1cd73a..0000000
--- a/luni/src/test/java/tests/api/java/util/support/I.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package tests.api.java.util.support;
-
-public interface I {
- String find(String key);
-}
diff --git a/luni/src/test/java/tests/api/java/util/support/P.java b/luni/src/test/java/tests/api/java/util/support/P.java
deleted file mode 100644
index 6883936..0000000
--- a/luni/src/test/java/tests/api/java/util/support/P.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package tests.api.java.util.support;
-
-import java.util.ResourceBundle;
-
-public class P {
- private Class c;
-
- public void setClazz(Class c) {
- this.c = c;
- }
-
- public String findProp(String key) {
- return findProp(this.c, key);
- }
-
- private String findProp(Class cls, String key) {
- String ret = null;
- try {
- ResourceBundle b = ResourceBundle.getBundle(cls.getName());
- ret = (String)b.getObject(key);
- } catch (Exception e) {
- }
- if (ret == null && !cls.equals(Object.class) && !cls.isPrimitive()) {
- ret = findProp(cls.getSuperclass(), key);
- }
- return ret;
- }
-}
diff --git a/luni/src/test/java/tests/java/lang/StrictMath/Fdlibm53Test.java b/luni/src/test/java/tests/java/lang/StrictMath/Fdlibm53Test.java
deleted file mode 100644
index d57fef9..0000000
--- a/luni/src/test/java/tests/java/lang/StrictMath/Fdlibm53Test.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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 tests.java.lang.StrictMath;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(StrictMath.class)
-public class Fdlibm53Test extends TestCase {
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "pow",
- args = {double.class, double.class}
- )
- public void test_pow() {
- assertTrue(Double.longBitsToDouble(-4610068591539890326L) == StrictMath.pow(-1.0000000000000002e+00,4.5035996273704970e+15));
- assertTrue(Double.longBitsToDouble(4601023824101950163L) == StrictMath.pow(-9.9999999999999978e-01,4.035996273704970e+15));
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Stress test.",
- method = "tan",
- args = {double.class}
- )
- public void test_tan(){
- assertTrue(Double.longBitsToDouble(4850236541654588678L) == StrictMath.tan( 1.7765241907548024E+269));
- }
-}
diff --git a/luni/src/test/java/tests/java/lang/String/Tests.java b/luni/src/test/java/tests/java/lang/String/Tests.java
deleted file mode 100644
index 3fe49bc..0000000
--- a/luni/src/test/java/tests/java/lang/String/Tests.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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 tests.java.lang.String;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for the class {@link String}.
- */
-@TestTargetClass(String.class)
-public class Tests extends TestCase {
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Doesn't check NullPointerException.",
- method = "contains",
- args = {java.lang.CharSequence.class}
- )
- public void test_contains() {
- assertTrue("aabc".contains("abc"));
- assertTrue("abcd".contains("abc"));
- assertFalse("abcd".contains("cba"));
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies positive functionality.",
- method = "charAt",
- args = {int.class}
- )
- public void test_charAt() {
- assertTrue("abcd".charAt(0) == 'a');
- assertTrue("abcd".charAt(3) == 'd');
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Doesn't check specific cases.",
- method = "startsWith",
- args = {java.lang.String.class}
- )
- public void test_StartsWith() {
- assertTrue("abcd".startsWith("abc"));
- assertFalse("abcd".startsWith("aabc"));
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Doesn't check specific cases.",
- method = "endsWith",
- args = {java.lang.String.class}
- )
- public void test_EndsWith() {
- assertTrue("abcd".endsWith("bcd"));
- assertFalse("abcd".endsWith("bcde"));
- }
- @TestTargetNew(
- level = TestLevel.TODO,
- notes = "Verifies nothing.",
- method = "!Constants",
- args = {}
- )
- public void test_CASE_INSENSITIVE_ORDER() {
- String s1 = "ABCDEFG";
- String s2 = "abcdefg";
-
- assertTrue(String.CASE_INSENSITIVE_ORDER.compare(s1, s2) == 0);
- }
-}
diff --git a/luni/src/test/java/tests/luni/AllTests.java b/luni/src/test/java/tests/luni/AllTests.java
deleted file mode 100644
index ff5b05a..0000000
--- a/luni/src/test/java/tests/luni/AllTests.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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 tests.luni;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-import junit.textui.TestRunner;
-
-/**
- * Listing of all the tests that are to be run.
- */
-public class AllTests
-{
-
- public static void run() {
- TestRunner.main(new String[] { AllTests.class.getName() });
- }
-
- public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite();
-
- suite.addTestSuite(tests.api.java.lang.BooleanTest.class);
- suite.addTestSuite(tests.api.java.lang.StringTest.class);
-
- suite.addTestSuite(tests.java.lang.StrictMath.Fdlibm53Test.class);
-
- suite.addTestSuite(tests.api.org.apache.harmony.kernel.dalvik.ThreadsTest.class);
- return suite;
- }
-}
diff --git a/luni/src/test/java/tests/luni/AllTestsIo.java b/luni/src/test/java/tests/luni/AllTestsIo.java
deleted file mode 100644
index d135244..0000000
--- a/luni/src/test/java/tests/luni/AllTestsIo.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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 tests.luni;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-import junit.textui.TestRunner;
-
-/**
- * Listing of all the tests that are to be run.
- */
-public class AllTestsIo
-{
-
- public static void run() {
- TestRunner.main(new String[] { AllTestsIo.class.getName() });
- }
-
- public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.io");
-
- suite.addTest(tests.api.java.io.AllTests.suite());
-
- suite.addTest(org.apache.harmony.luni.tests.java.io.AllTests.suite());
-
- return suite;
- }
-}
diff --git a/luni/src/test/java/tests/luni/AllTestsLang.java b/luni/src/test/java/tests/luni/AllTestsLang.java
deleted file mode 100644
index 418571e..0000000
--- a/luni/src/test/java/tests/luni/AllTestsLang.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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 tests.luni;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-import junit.textui.TestRunner;
-
-/**
- * Listing of all the tests that are to be run.
- */
-public class AllTestsLang
-{
-
- public static void run() {
- TestRunner.main(new String[] { AllTestsLang.class.getName() });
- }
-
- public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.lang");
-
- suite.addTest(org.apache.harmony.luni.tests.java.lang.AllTests.suite());
-
- suite.addTest(tests.api.java.lang.AllTests.suite());
-
- suite.addTest(tests.api.java.lang.ref.AllTests.suite());
-
- suite.addTest(tests.api.java.lang.reflect.AllTests.suite());
-
- return suite;
- }
-}
diff --git a/luni/src/test/java/tests/luni/AllTestsNet.java b/luni/src/test/java/tests/luni/AllTestsNet.java
deleted file mode 100644
index c61cb5f..0000000
--- a/luni/src/test/java/tests/luni/AllTestsNet.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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 tests.luni;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-import junit.textui.TestRunner;
-
-/**
- * Listing of all the tests that are to be run.
- */
-public class AllTestsNet
-{
-
- public static void run() {
- TestRunner.main(new String[] { AllTestsNet.class.getName() });
- }
-
- public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.net");
-
- suite.addTest(org.apache.harmony.luni.tests.java.net.AllTests.suite());
-
- suite.addTest(tests.api.java.net.AllTests.suite());
-
- suite.addTest(org.apache.harmony.luni.tests.internal.net.www.protocol.http.AllTests.suite());
- suite.addTest(org.apache.harmony.luni.tests.internal.net.www.protocol.https.AllTests.suite());
-
- return suite;
- }
-}
diff --git a/luni/src/test/java/tests/luni/AllTestsUtil.java b/luni/src/test/java/tests/luni/AllTestsUtil.java
deleted file mode 100644
index a157a95..0000000
--- a/luni/src/test/java/tests/luni/AllTestsUtil.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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 tests.luni;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-import junit.textui.TestRunner;
-
-/**
- * Listing of all the tests that are to be run.
- */
-public class AllTestsUtil
-{
-
- public static void run() {
- TestRunner.main(new String[] { AllTestsUtil.class.getName() });
- }
-
- public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.util");
-
- suite.addTest(tests.api.java.util.AllTests.suite());
- suite.addTest(org.apache.harmony.luni.tests.java.util.AllTests.suite());
-
- return suite;
- }
-}