summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorElliott Hughes <enh@google.com>2010-02-18 17:20:15 -0800
committerElliott Hughes <enh@google.com>2010-02-19 10:35:06 -0800
commit7ee3a061452c5a7e5c8e661219a1f08a14171858 (patch)
treef995fb4c053e4c68a86909aa72aee284cb39133a
parent1d1f9244611a8ba3be65795d4ea6e84bcecdb89d (diff)
downloadlibcore-7ee3a061452c5a7e5c8e661219a1f08a14171858.zip
libcore-7ee3a061452c5a7e5c8e661219a1f08a14171858.tar.gz
libcore-7ee3a061452c5a7e5c8e661219a1f08a14171858.tar.bz2
Resync a load of tests with upstream, make our build faster.
I started off with a mission to remove uses of dalvik.annotation.* (stuff like @TestTargetNew and other useless junk that just makes it harder to stay in sync with upstream). I wrote a script to go through tests showing me the diff between what we have and what upstream has, thinking that in cases where upstream has also added tests, I may as well pull them in at the same time... ...but I didn't realize how close we were to having dx fill its 1.5GiB heap. After trying various alternatives, I decided to bite the bullet and break core-tests up into one .jar per module. This adds parallelism back into this, the slowest part of our build. (I can do even better, but I'll do that in a separate patch, preferably after we've merged recent changes from master.) Only a couple of dependencies were problematic: the worthless TestSuiteFactory which already contained a comment suggesting we get rid of it, and the fact that some tests -- most notably the concurrent ones -- also contained main methods that started the JUnit tty-based TestRunner. (In the long run, we want to be running the harmony tests directly from a pristine "svn co" of upstream, using DalvikRunner. But this will be a big help in the meantime, and starts the work of getting our current copy of the tests into a state where we can start to extract any meaningful changes/additions we've made.)
-rw-r--r--JavaLibrary.mk253
-rw-r--r--annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AllTests.java2
-rw-r--r--annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationFormatErrorTest.java26
-rw-r--r--annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationTypeMismatchExceptionTest.java30
-rw-r--r--annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/ElementTypeTest.java22
-rw-r--r--annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/IncompleteAnnotationExceptionTest.java37
-rw-r--r--annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/RetentionPolicyTest.java22
-rw-r--r--annotation/src/test/java/tests/annotation/AllTests.java7
-rw-r--r--archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AllTests.java7
-rw-r--r--archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/Adler32Test.java339
-rw-r--r--archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/AllTests.java7
-rw-r--r--archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CRC32Test.java372
-rw-r--r--archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CheckedInputStreamTest.java142
-rw-r--r--archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterOutputStreamTest.java86
-rw-r--r--archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterTest.java1815
-rw-r--r--archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPInputStreamTest.java281
-rw-r--r--archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPOutputStreamTest.java353
-rw-r--r--archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterInputStreamTest.java581
-rw-r--r--archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterTest.java1361
-rw-r--r--archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipEntryTest.java1035
-rw-r--r--archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipOutputStreamTest.java109
-rw-r--r--archive/src/test/java/tests/archive/AllTests.java7
-rw-r--r--concurrent/src/test/java/tests/api/java/util/concurrent/AbstractExecutorServiceTest.java3
-rw-r--r--concurrent/src/test/java/tests/api/java/util/concurrent/AbstractQueueTest.java3
-rw-r--r--concurrent/src/test/java/tests/api/java/util/concurrent/AbstractQueuedSynchronizerTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/ArrayBlockingQueueTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/AtomicBooleanTest.java3
-rw-r--r--concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerArrayTest.java4
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerFieldUpdaterTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerTest.java3
-rw-r--r--concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongArrayTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongFieldUpdaterTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/AtomicMarkableReferenceTest.java3
-rw-r--r--concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceArrayTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceFieldUpdaterTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/AtomicStampedReferenceTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/ConcurrentHashMapTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/ConcurrentLinkedQueueTest.java5
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArrayListTest.java5
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArraySetTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/CountDownLatchTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/CyclicBarrierTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/DelayQueueTest.java4
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/ExchangerTest.java4
-rw-r--r--concurrent/src/test/java/tests/api/java/util/concurrent/ExecutorCompletionServiceTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/ExecutorsTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/FutureTaskTest.java4
-rw-r--r--concurrent/src/test/java/tests/api/java/util/concurrent/JSR166TestCase.java4
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/LinkedBlockingQueueTest.java5
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/LinkedListTest.java4
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/LockSupportTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/PriorityBlockingQueueTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/PriorityQueueTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/ReentrantLockTest.java3
-rw-r--r--concurrent/src/test/java/tests/api/java/util/concurrent/ReentrantReadWriteLockTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/ScheduledExecutorTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/SemaphoreTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/SynchronousQueueTest.java5
-rw-r--r--concurrent/src/test/java/tests/api/java/util/concurrent/SystemTest.java4
-rw-r--r--concurrent/src/test/java/tests/api/java/util/concurrent/ThreadLocalTest.java4
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/ThreadPoolExecutorTest.java3
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/ThreadTest.java4
-rwxr-xr-xconcurrent/src/test/java/tests/api/java/util/concurrent/TimeUnitTest.java4
-rw-r--r--concurrent/src/test/java/tests/concurrent/AllTests.java7
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/AllTests.java7
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java5
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/AllTests.java5
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/interfaces/AllTests.java7
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/AllTests.java7
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/BadPaddingExceptionTest.java4
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/ExemptionMechanismExceptionTest.java4
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/IllegalBlockSizeExceptionTest.java4
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/NoSuchPaddingExceptionTest.java4
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/ShortBufferExceptionTest.java4
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/AllTests.java7
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DESKeySpecTest.java4
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DESedeKeySpecTest.java4
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHGenParameterSpecTest.java4
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHParameterSpecTest.java4
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHPrivateKeySpecTest.java4
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHPublicKeySpecTest.java4
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/IvParameterSpecTest.java4
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/OAEPParameterSpecTest.java4
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PBEKeySpecTest.java4
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PBEParameterSpecTest.java4
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PSourceTest.java4
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/RC2ParameterSpecTest.java4
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/RC5ParameterSpecTest.java4
-rw-r--r--crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/SecretKeySpecTest.java4
-rw-r--r--crypto/src/test/java/tests/crypto/AllTests.java8
-rw-r--r--dom/src/test/java/tests/api/org/w3c/dom/AllTests.java2
-rw-r--r--dom/src/test/java/tests/dom/AllTests.java5
-rw-r--r--icu/src/test/java/com/ibm/icu4jni/util/AllTests.java2
-rw-r--r--logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/AllTests.java3
-rw-r--r--logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/ConsoleHandlerTest.java1172
-rw-r--r--logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FilterTest.java53
-rw-r--r--logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/HandlerTest.java1271
-rw-r--r--logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LevelTestResource.java4
-rw-r--r--logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggingPermissionTest.java84
-rw-r--r--logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/StreamHandlerTest.java2274
-rw-r--r--logging/src/test/java/tests/logging/AllTests.java9
-rw-r--r--luni-kernel/src/test/java/java/lang/reflect/AllTests.java2
-rw-r--r--luni-kernel/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/AllTests.java2
-rw-r--r--luni/src/test/java/java/io/AllTests.java2
-rw-r--r--luni/src/test/java/java/lang/AllTests.java2
-rw-r--r--luni/src/test/java/java/net/AllTests.java2
-rw-r--r--luni/src/test/java/java/nio/charset/AllTests.java2
-rw-r--r--luni/src/test/java/java/text/AllTests.java2
-rw-r--r--luni/src/test/java/java/util/AllTests.java2
-rw-r--r--luni/src/test/java/javax/xml/parsers/AllTests.java2
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/platform/AllTests.java2
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/http/AllTests.java7
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/internal/net/www/protocol/https/AllTests.java7
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/AllTests.java2
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/BufferedReaderTest.java656
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/FilePermissionTest.java221
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/FileTest.java2276
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/InputStreamReaderTest.java577
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectInputStreamTest.java1296
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectStreamConstantsTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/OutputStreamWriterTest.java726
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/RandomAccessFileTest.java991
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/io/WriterTest.java143
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AbstractMethodErrorTest.java91
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AllTests.java2
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArithmeticExceptionTest.java18
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArrayIndexOutOfBoundsExceptionTest.java26
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ArrayStoreExceptionTest.java18
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AssertionErrorTest.java61
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/BooleanTest.java78
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ByteTest.java230
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CharacterImplTest.java13
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/Character_SubsetTest.java4
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/Character_UnicodeBlockTest.java38
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassCastExceptionTest.java38
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassCircularityErrorTest.java66
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassFormatErrorTest.java68
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassLoaderTest.java1089
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ClassNotFoundExceptionTest.java118
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CloneNotSupportedExceptionTest.java38
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CompilerTest.java90
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/EnumConstantNotPresentExceptionTest.java31
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/EnumTest.java124
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ErrorTest.java50
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExceptionInInitializerErrorTest.java72
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ExceptionTest.java51
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalAccessErrorTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalAccessExceptionTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalArgumentExceptionTest.java86
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalMonitorStateExceptionTest.java18
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalStateExceptionTest.java99
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalThreadStateExceptionTest.java20
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IncompatibleClassChangeErrorTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IndexOutOfBoundsExceptionTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InstantiationErrorTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InstantiationExceptionTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InternalErrorTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/InterruptedExceptionTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/LinkageErrorTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NegativeArraySizeExceptionTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoClassDefFoundErrorTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchFieldErrorTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchFieldExceptionTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchMethodErrorTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NoSuchMethodExceptionTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NullPointerExceptionTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NumberFormatExceptionTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/NumberTest.java142
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/OutOfMemoryErrorTest.java46
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/PackageTest.java297
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimePermissionTest.java58
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SecurityExceptionTest.java51
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SecurityManagerTest.java1189
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ShortTest.java213
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StackOverflowErrorTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBufferTest.java244
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringBuilderTest.java3581
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/StringIndexOutOfBoundsExceptionTest.java29
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadDeathTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TypeNotPresentExceptionTest.java18
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnknownErrorTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsatisfiedLinkErrorTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsupportedClassVersionErrorTest.java75
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/UnsupportedOperationExceptionTest.java98
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/VerifyErrorTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/lang/VirtualMachineErrorTest.java24
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/AllTests.java2
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/ContentHandlerTest.java41
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/HttpRetryExceptionTest.java18
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/URITest.java1896
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLEncoderTest.java72
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/AbstractCollectionTest.java184
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/AllTests.java2
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArrayListTest.java1018
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/ArraysTest.java2298
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/BitSetTest.java1384
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/DateTest.java524
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/DuplicateFormatFlagsExceptionTest.java42
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatFlagsConversionMismatchExceptionTest.java51
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatterClosedExceptionTest.java31
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/FormatterTest.java4319
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/HashMapTest.java776
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/IdentityHashMapTest.java737
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatCodePointExceptionTest.java40
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatConversionExceptionTest.java48
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatFlagsExceptionTest.java42
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatPrecisionExceptionTest.java40
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/IllegalFormatWidthExceptionTest.java40
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/InputMismatchExceptionTest.java34
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/InvalidPropertiesFormatExceptionTest.java73
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/LocaleTest.java427
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/MissingFormatArgumentExceptionTest.java41
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/MissingFormatWidthExceptionTest.java41
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/UUIDTest.java316
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/UnknownFormatConversionExceptionTest.java40
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/UnknownFormatFlagsExceptionTest.java41
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/VectorTest.java1318
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/java/util/WeakHashMapTest.java404
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/util/Base64Test.java20
-rw-r--r--luni/src/test/java/org/apache/harmony/luni/tests/util/NYITest.java13
-rw-r--r--luni/src/test/java/tests/AllTests.java2
-rw-r--r--luni/src/test/java/tests/TestSuiteFactory.java34
-rw-r--r--luni/src/test/java/tests/api/java/io/AllTests.java7
-rw-r--r--luni/src/test/java/tests/api/java/lang/AllTests.java7
-rw-r--r--luni/src/test/java/tests/api/java/lang/ref/AllTests.java7
-rw-r--r--luni/src/test/java/tests/api/java/lang/reflect/AllTests.java7
-rw-r--r--luni/src/test/java/tests/api/java/net/AllTests.java7
-rw-r--r--luni/src/test/java/tests/api/java/util/AllTests.java7
-rw-r--r--luni/src/test/java/tests/luni/AllTestsIo.java2
-rw-r--r--luni/src/test/java/tests/luni/AllTestsLang.java2
-rw-r--r--luni/src/test/java/tests/luni/AllTestsNet.java2
-rw-r--r--luni/src/test/java/tests/luni/AllTestsUtil.java2
-rw-r--r--math/src/test/java/org/apache/harmony/math/tests/java/math/AllTests.java7
-rw-r--r--math/src/test/java/tests/api/java/math/AllTests.java7
-rw-r--r--math/src/test/java/tests/math/AllTests.java7
-rw-r--r--nio/src/test/java/org/apache/harmony/nio/tests/java/nio/AllTests.java7
-rw-r--r--nio/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java4
-rw-r--r--nio/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AllTests.java7
-rw-r--r--nio/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AllTests.java3
-rw-r--r--nio/src/test/java/tests/nio/AllTests.java7
-rw-r--r--nio_char/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/AllTests.java8
-rw-r--r--nio_char/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/spi/AllTests.java8
-rw-r--r--nio_char/src/test/java/tests/api/java/nio/charset/AllTests.java7
-rw-r--r--nio_char/src/test/java/tests/nio_char/AllTests.java7
-rw-r--r--prefs/src/test/java/org/apache/harmony/prefs/tests/java/util/prefs/AllTests.java7
-rw-r--r--prefs/src/test/java/tests/prefs/AllTests.java7
-rw-r--r--regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/AllTests.java7
-rw-r--r--regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/MatcherTest.java4
-rw-r--r--regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java4
-rw-r--r--regex/src/test/java/tests/regex/AllTests.java7
-rwxr-xr-xrun-core-tests10
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/AccessControlExceptionTest.java8
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParameterGenerator1Test.java4
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParametersSpiTest.java4
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/AllTests.java7
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/CodeSignerTest.java9
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/CodeSourceTest.java10
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/GuardedObjectTest.java4
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/IdentityScopeTest.java4
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/KSPrivateKeyEntryTest.java4
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator1Test.java4
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator2Test.java3
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator3Test.java4
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGeneratorSpiTest.java3
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/KeyStoreSpiTest.java8
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/PermissionTest.java5
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/PermissionsTest.java5
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/PolicyTest.java4
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/PrivilegedActionExceptionTest.java10
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/ProtectionDomainTest.java8
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/SecurityPermissionTest.java5
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/SignerTest.java4
-rw-r--r--security/src/test/java/org/apache/harmony/security/tests/java/security/TimestampTest.java5
-rw-r--r--security/src/test/java/org/bouncycastle/jce/provider/AllTests.java8
-rw-r--r--security/src/test/java/tests/api/java/security/AllTests.java7
-rw-r--r--security/src/test/java/tests/api/javax/security/auth/AllTests.java7
-rw-r--r--security/src/test/java/tests/api/javax/security/cert/AllTests.java7
-rw-r--r--security/src/test/java/tests/api/javax/security/cert/CertificateTest.java4
-rw-r--r--security/src/test/java/tests/api/javax/security/cert/X509CertificateTest.java4
-rw-r--r--security/src/test/java/tests/java/security/AllPermissionTest.java4
-rw-r--r--security/src/test/java/tests/java/security/AllTests.java7
-rw-r--r--security/src/test/java/tests/java/security/BasicPermissionTest.java5
-rw-r--r--security/src/test/java/tests/java/security/IdentityTest.java4
-rw-r--r--security/src/test/java/tests/java/security/SecureClassLoaderTest.java10
-rw-r--r--security/src/test/java/tests/security/AllTests.java7
-rw-r--r--security/src/test/java/tests/security/acl/AclNotFoundExceptionTest.java5
-rw-r--r--security/src/test/java/tests/security/acl/AllTests.java7
-rw-r--r--security/src/test/java/tests/security/acl/LastOwnerExceptionTest.java16
-rw-r--r--security/src/test/java/tests/security/acl/NotOwnerExceptionTest.java16
-rw-r--r--security/src/test/java/tests/security/cert/AllTests.java7
-rw-r--r--security/src/test/java/tests/security/cert/CertPathBuilder1Test.java5
-rw-r--r--security/src/test/java/tests/security/cert/CertPathBuilder2Test.java5
-rw-r--r--security/src/test/java/tests/security/cert/CertPathValidator1Test.java4
-rw-r--r--security/src/test/java/tests/security/cert/CertStoreSpiTest.java4
-rw-r--r--security/src/test/java/tests/security/cert/CertificateFactory1Test.java4
-rw-r--r--security/src/test/java/tests/security/cert/X509CRLEntryTest.java4
-rw-r--r--security/src/test/java/tests/security/cert/X509CRLTest.java4
-rw-r--r--security/src/test/java/tests/security/interfaces/AllTests.java7
-rw-r--r--security/src/test/java/tests/security/spec/AllTests.java7
-rw-r--r--security/src/test/java/tests/targets/security/AllTests.java9
-rw-r--r--security/src/test/java/tests/targets/security/cert/AllTests.java9
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/AllTests.java7
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/AllTests.java7
-rw-r--r--sql/src/test/java/tests/SQLite/AllTests.java2
-rw-r--r--sql/src/test/java/tests/java/sql/AllTests.java7
-rw-r--r--sql/src/test/java/tests/sql/AllTests.java7
-rw-r--r--suncompat/src/test/java/sun/misc/AllTests.java7
-rw-r--r--suncompat/src/test/java/tests/suncompat/AllTests.java7
-rw-r--r--text/src/test/java/org/apache/harmony/text/tests/java/text/AllTests.java8
-rw-r--r--text/src/test/java/tests/text/AllTests.java7
-rw-r--r--x-net/src/test/java/tests/api/javax/net/AllTests.java7
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/AllTests.java7
-rw-r--r--x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java4
-rw-r--r--x-net/src/test/java/tests/xnet/AllTests.java8
-rw-r--r--xml/src/test/java/org/apache/harmony/xml/AllTests.java2
-rw-r--r--xml/src/test/java/org/apache/harmony/xml/XsltXPathConformanceTestSuite.java3
-rw-r--r--xml/src/test/java/org/kxml2/io/AllTests.java2
-rw-r--r--xml/src/test/java/tests/api/javax/xml/parsers/AllTests.java7
-rw-r--r--xml/src/test/java/tests/api/org/xml/sax/AllTests.java7
-rw-r--r--xml/src/test/java/tests/api/org/xml/sax/ext/AllTests.java7
-rw-r--r--xml/src/test/java/tests/api/org/xml/sax/helpers/AllTests.java7
-rw-r--r--xml/src/test/java/tests/org/w3c/dom/AllTests.java7
-rw-r--r--xml/src/test/java/tests/xml/AllTests.java6
325 files changed, 28041 insertions, 17210 deletions
diff --git a/JavaLibrary.mk b/JavaLibrary.mk
index b12b47d..eb2f791 100644
--- a/JavaLibrary.mk
+++ b/JavaLibrary.mk
@@ -1,3 +1,4 @@
+# -*- mode: makefile -*-
# Copyright (C) 2007 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -28,19 +29,22 @@ define all-core-java-files
$(patsubst ./%,%,$(shell cd $(LOCAL_PATH) && find */src/$(1)/java -name "*.java"))
endef
+define all-test-java-files-under
+$(patsubst ./%,%,$(shell cd $(LOCAL_PATH) && find $(1)/src/test/java -name "*.java"))
+endef
+
# Redirect ls stderr to /dev/null because the corresponding resources
# directories don't always exist.
define all-core-resource-dirs
-$(shell cd $(LOCAL_PATH) && ls -d */src/$(1)/{java,resources} 2> /dev/null)
+$(shell cd $(LOCAL_PATH) && ls -d */src/test/{java,resources} 2> /dev/null)
endef
# The core Java files and associated resources.
core_src_files := $(call all-core-java-files,main)
core_resource_dirs := $(call all-core-resource-dirs,main)
-# The test Java files and associated resources.
-test_src_files := $(call all-core-java-files,test)
-test_resource_dirs := $(call all-core-resource-dirs,test)
+# The tests' associated resources.
+test_resource_dirs := $(call all-core-resource-dirs)
#
@@ -67,24 +71,240 @@ include $(BUILD_JAVA_LIBRARY)
core-intermediates := ${intermediates}
-# Definitions to make the core-tests library.
+
+
+# Definitions to make the core-tests libraries.
+#
+# We make a library per module, because otherwise the .jar files get too
+# large, to the point that dx(1) can't cope (and the build is
+# ridiculously slow).
+#
+# TODO: DalvikRunner will make this nonsense obsolete.
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,annotation)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-annotation
+include $(BUILD_JAVA_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,archive)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-archive
+include $(BUILD_JAVA_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,concurrent)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-concurrent
+include $(BUILD_JAVA_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,crypto)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-crypto
+include $(BUILD_JAVA_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,dom)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-dom
+include $(BUILD_JAVA_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,icu)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-icu
+include $(BUILD_JAVA_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,logging)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-logging
+include $(BUILD_JAVA_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,luni-kernel)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-luni-kernel
+include $(BUILD_JAVA_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,luni)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+# This module contains the top-level "tests.AllTests" that ties everything
+# together, so it has compile-time dependencies on all the other test
+# libraries.
+# TODO: we should have a bogus module that just contains tests.AllTests for speed.
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_JAVA_LIBRARIES += core-tests-annotation core-tests-archive
+LOCAL_JAVA_LIBRARIES += core-tests-concurrent core-tests-crypto
+LOCAL_JAVA_LIBRARIES += core-tests-dom core-tests-icu core-tests-logging
+LOCAL_JAVA_LIBRARIES += core-tests-luni-kernel core-tests-math core-tests-nio
+LOCAL_JAVA_LIBRARIES += core-tests-nio_char core-tests-prefs core-tests-regex
+LOCAL_JAVA_LIBRARIES += core-tests-security core-tests-sql core-tests-suncompat
+LOCAL_JAVA_LIBRARIES += core-tests-text core-tests-x-net core-tests-xml
+LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-luni
+include $(BUILD_JAVA_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,math)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-math
+include $(BUILD_JAVA_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,nio)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-nio
+include $(BUILD_JAVA_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,nio_char)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-nio_char
+include $(BUILD_JAVA_LIBRARY)
include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,prefs)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-prefs
+include $(BUILD_JAVA_LIBRARY)
-LOCAL_SRC_FILES := $(test_src_files)
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,regex)
LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-regex
+include $(BUILD_JAVA_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,security)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-security
+include $(BUILD_JAVA_LIBRARY)
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,sql)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-sql
+include $(BUILD_JAVA_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,suncompat)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-suncompat
+include $(BUILD_JAVA_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,support)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
LOCAL_NO_STANDARD_LIBRARIES := true
LOCAL_JAVA_LIBRARIES := core caliper
LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-support
+include $(BUILD_JAVA_LIBRARY)
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,text)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-text
+include $(BUILD_JAVA_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,x-net)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_DX_FLAGS := --core-library
LOCAL_MODULE_TAGS := tests
-LOCAL_MODULE := core-tests
+LOCAL_MODULE := core-tests-x-net
+include $(BUILD_JAVA_LIBRARY)
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-test-java-files-under,xml)
+LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
+LOCAL_NO_STANDARD_LIBRARIES := true
+LOCAL_JAVA_LIBRARIES := core caliper core-tests-support
+LOCAL_DX_FLAGS := --core-library
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE := core-tests-xml
include $(BUILD_JAVA_LIBRARY)
+
# This one's tricky. One of our tests needs to have a
# resource with a "#" in its name, but Perforce doesn't
# allow us to submit such a file. So we create it here
@@ -164,21 +384,4 @@ ifeq ($(WITH_HOST_DALVIK),true)
include $(BUILD_HOST_JAVA_LIBRARY)
-
- # Definitions to make the core-tests library.
-
- include $(CLEAR_VARS)
-
- LOCAL_SRC_FILES := $(test_src_files)
- LOCAL_JAVA_RESOURCE_DIRS := $(test_resource_dirs)
-
- LOCAL_NO_STANDARD_LIBRARIES := true
- LOCAL_JAVA_LIBRARIES := core
- LOCAL_DX_FLAGS := --core-library
-
- LOCAL_MODULE_TAGS := tests
- LOCAL_MODULE := core-tests
-
- include $(BUILD_HOST_JAVA_LIBRARY)
-
-endif \ No newline at end of file
+endif
diff --git a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AllTests.java b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AllTests.java
index e306435..c2b179e 100644
--- a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AllTests.java
+++ b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AllTests.java
@@ -25,7 +25,7 @@ import junit.framework.TestSuite;
public class AllTests {
public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Test for java.lang.annotation");
+ TestSuite suite = new TestSuite("Test for java.lang.annotation");
// $JUnit-BEGIN$
suite.addTestSuite(AnnotationTest.class);
diff --git a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationFormatErrorTest.java b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationFormatErrorTest.java
index c2a32b8..b80f3a9 100644
--- a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationFormatErrorTest.java
+++ b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationFormatErrorTest.java
@@ -17,29 +17,17 @@
package org.apache.harmony.annotation.tests.java.lang.annotation;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
+import java.lang.annotation.AnnotationFormatError;
import junit.framework.TestCase;
-import java.lang.annotation.AnnotationFormatError;
-
/**
* Test case of java.lang.annotation.AnnotationFormatError
*/
-@TestTargetClass(AnnotationFormatError.class)
public class AnnotationFormatErrorTest extends TestCase {
/**
* @tests java.lang.annotation.AnnotationFormatError#AnnotationFormatError(String)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AnnotationFormatError",
- args = {java.lang.String.class}
- )
@SuppressWarnings("nls")
public void test_constructorLjava_lang_String() {
AnnotationFormatError e = new AnnotationFormatError("some message");
@@ -49,12 +37,6 @@ public class AnnotationFormatErrorTest extends TestCase {
/**
* @tests java.lang.annotation.AnnotationFormatError#AnnotationFormatError(Throwable)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AnnotationFormatError",
- args = {java.lang.Throwable.class}
- )
public void test_constructorLjava_lang_Throwable() {
IllegalArgumentException iae = new IllegalArgumentException();
AnnotationFormatError e = new AnnotationFormatError(iae);
@@ -64,12 +46,6 @@ public class AnnotationFormatErrorTest extends TestCase {
/**
* @tests java.lang.annotation.AnnotationFormatError#AnnotationFormatError(String,Throwable)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AnnotationFormatError",
- args = {java.lang.String.class, java.lang.Throwable.class}
- )
@SuppressWarnings("nls")
public void test_constructorLjava_lang_StringLjava_lang_Throwable() {
IllegalArgumentException iae = new IllegalArgumentException();
diff --git a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationTypeMismatchExceptionTest.java b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationTypeMismatchExceptionTest.java
index 5430286..37ee8c1 100644
--- a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationTypeMismatchExceptionTest.java
+++ b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/AnnotationTypeMismatchExceptionTest.java
@@ -17,20 +17,14 @@
package org.apache.harmony.annotation.tests.java.lang.annotation;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
import java.lang.annotation.AnnotationTypeMismatchException;
import java.lang.reflect.Method;
+import junit.framework.TestCase;
+
/**
* Test case of java.lang.annotation.AnnotationTypeMismatchException
*/
-@TestTargetClass(AnnotationTypeMismatchException.class)
public class AnnotationTypeMismatchExceptionTest extends TestCase {
/**
@@ -39,26 +33,6 @@ public class AnnotationTypeMismatchExceptionTest extends TestCase {
* @tests java.lang.annotation.AnnotationTypeMismatchException#AnnotationTypeMismatchException(Method,
* String)
*/
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "AnnotationTypeMismatchException",
- args = {java.lang.reflect.Method.class, java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "element",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "foundType",
- args = {}
- )
- })
@SuppressWarnings("nls")
public void test_constructorLjava_lang_reflect_MethodLjava_lang_String() throws SecurityException, ClassNotFoundException {
Method[] methods = Class.forName("java.lang.String").getMethods();
diff --git a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/ElementTypeTest.java b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/ElementTypeTest.java
index dec9bf7..d81cabd 100644
--- a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/ElementTypeTest.java
+++ b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/ElementTypeTest.java
@@ -17,32 +17,20 @@
package org.apache.harmony.annotation.tests.java.lang.annotation;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
import java.lang.annotation.ElementType;
import java.util.Arrays;
+import junit.framework.TestCase;
+
/**
* Test case of java.lang.annotation.ElementType
*/
-@TestTargetClass(ElementType.class)
public class ElementTypeTest extends TestCase {
/**
* @throws Exception
* @tests java.lang.annotation.ElementType#valueOf(String)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {java.lang.String.class}
- )
@SuppressWarnings("nls")
public void test_valueOfLjava_lang_String() throws Exception {
assertSame(ElementType.ANNOTATION_TYPE, ElementType
@@ -67,12 +55,6 @@ public class ElementTypeTest extends TestCase {
* @throws Exception
* @tests java.lang.annotation.ElementType#values()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
@SuppressWarnings("nls")
public void test_values() throws Exception {
ElementType[] values = ElementType.values();
diff --git a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/IncompleteAnnotationExceptionTest.java b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/IncompleteAnnotationExceptionTest.java
index 5c718ed..d44b90a 100644
--- a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/IncompleteAnnotationExceptionTest.java
+++ b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/IncompleteAnnotationExceptionTest.java
@@ -17,28 +17,19 @@
package org.apache.harmony.annotation.tests.java.lang.annotation;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
+import java.lang.annotation.IncompleteAnnotationException;
import junit.framework.TestCase;
-import java.lang.annotation.IncompleteAnnotationException;
-
-@TestTargetClass(IncompleteAnnotationException.class)
+/**
+ *
+ */
public class IncompleteAnnotationExceptionTest extends TestCase {
/*
* Class under test for void IncompleteAnnotationException(String)
* Regression for HARMONY-2477
*/
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Verifies NullPointerException.",
- method = "IncompleteAnnotationException",
- args = {java.lang.Class.class, java.lang.String.class}
- )
public void testNullType() {
try {
new IncompleteAnnotationException(null, "str");
@@ -53,26 +44,6 @@ public class IncompleteAnnotationExceptionTest extends TestCase {
* @tests java.lang.annotation.IncompleteAnnotationException#IncompleteAnnotationException(Class,
* String)
*/
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "IncompleteAnnotationException",
- args = {java.lang.Class.class, java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "annotationType",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "elementName",
- args = {}
- )
- })
@SuppressWarnings("nls")
public void test_constructorLjava_lang_Class_Ljava_lang_String()
throws Exception {
diff --git a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/RetentionPolicyTest.java b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/RetentionPolicyTest.java
index 1827b7d..c4f7c03 100644
--- a/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/RetentionPolicyTest.java
+++ b/annotation/src/test/java/org/apache/harmony/annotation/tests/java/lang/annotation/RetentionPolicyTest.java
@@ -17,31 +17,19 @@
package org.apache.harmony.annotation.tests.java.lang.annotation;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
+import junit.framework.TestCase;
+
/**
* Test case of java.lang.annotation.RetentionPolicy
*/
-@TestTargetClass(RetentionPolicy.class)
public class RetentionPolicyTest extends TestCase {
/**
* @throws Exception
* @tests java.lang.annotation.RetentionPolicy#valueOf(String)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {java.lang.String.class}
- )
@SuppressWarnings("nls")
public void test_valueOfLjava_lang_String() throws Exception {
assertSame(RetentionPolicy.CLASS, RetentionPolicy
@@ -62,12 +50,6 @@ public class RetentionPolicyTest extends TestCase {
* @throws Exception
* @tests java.lang.annotation.RetentionPolicy#values()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
@SuppressWarnings("nls")
public void test_values() throws Exception {
RetentionPolicy[] values = RetentionPolicy.values();
diff --git a/annotation/src/test/java/tests/annotation/AllTests.java b/annotation/src/test/java/tests/annotation/AllTests.java
index 172cc10..c95fe26 100644
--- a/annotation/src/test/java/tests/annotation/AllTests.java
+++ b/annotation/src/test/java/tests/annotation/AllTests.java
@@ -23,13 +23,8 @@ import junit.framework.TestSuite;
* Test suite that includes all tests for the NIO_Char project.
*/
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 Annotation test suites");
+ TestSuite suite = new TestSuite("All Annotation test suites");
// $JUnit-BEGIN$
suite.addTest(org.apache.harmony.annotation.tests.java.lang.annotation.AllTests.suite());
// $JUnit-END$
diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AllTests.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AllTests.java
index 13fe019..7b39de6 100644
--- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AllTests.java
+++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/jar/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
* Test suite for java.util.jar package.
*/
public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
-
public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite(
+ TestSuite suite = new TestSuite(
"Suite org.apache.harmony.archive.tests.java.util.jar");
suite.addTestSuite(AttributesNameTest.class);
suite.addTestSuite(AttributesTest.class);
diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/Adler32Test.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/Adler32Test.java
index 532a3a6..7290ac2 100644
--- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/Adler32Test.java
+++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/Adler32Test.java
@@ -14,211 +14,156 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.harmony.archive.tests.java.util.zip;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
import java.util.zip.Adler32;
-@TestTargetClass(Adler32.class)
public class Adler32Test extends junit.framework.TestCase {
- /**
- * @tests java.util.zip.Adler32#Adler32()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Adler32",
- args = {}
- )
- public void test_Constructor() {
- // test method of java.util.zip.Adler32()
- Adler32 adl = new Adler32();
- assertEquals("Constructor of adl32 failed", 1, adl.getValue());
- }
-
- /**
- * @tests java.util.zip.Adler32#getValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getValue",
- args = {}
- )
- public void test_getValue() {
- // test methods of java.util.zip.getValue()
- Adler32 adl = new Adler32();
- assertEquals(
- "GetValue should return a zero as a result of construction an object of Adler32",
- 1, adl.getValue());
-
- adl.reset();
- adl.update(1);
- // System.out.print("value of adl"+adl.getValue());
- // The value of the adl should be 131074
- assertEquals(
- "update(int) failed to update the checksum to the correct value ",
- 131074, adl.getValue());
- adl.reset();
- assertEquals("reset failed to reset the checksum value to zero", 1, adl
- .getValue());
-
- adl.reset();
- adl.update(Integer.MIN_VALUE);
- // System.out.print("value of adl " + adl.getValue());
- // The value of the adl should be 65537
- assertEquals(
- "update(min) failed to update the checksum to the correct value ",
- 65537L, adl.getValue());
- }
-
- /**
- * @tests java.util.zip.Adler32#reset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reset",
- args = {}
- )
- public void test_reset() {
- // test methods of java.util.zip.reset()
- Adler32 adl = new Adler32();
- adl.update(1);
- // System.out.print("value of adl"+adl.getValue());
- // The value of the adl should be 131074
- assertEquals(
- "update(int) failed to update the checksum to the correct value ",
- 131074, adl.getValue());
- adl.reset();
- assertEquals("reset failed to reset the checksum value to zero", 1, adl
- .getValue());
- }
-
- /**
- * @tests java.util.zip.Adler32#update(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "update",
- args = {int.class}
- )
- public void test_updateI() {
- // test methods of java.util.zip.update(int)
- Adler32 adl = new Adler32();
- adl.update(1);
- // The value of the adl should be 131074
- assertEquals(
- "update(int) failed to update the checksum to the correct value ",
- 131074, adl.getValue());
-
- adl.reset();
- adl.update(Integer.MAX_VALUE);
- // System.out.print("value of adl " + adl.getValue());
- // The value of the adl should be 16777472
- assertEquals(
- "update(max) failed to update the checksum to the correct value ",
- 16777472L, adl.getValue());
-
- adl.reset();
- adl.update(Integer.MIN_VALUE);
- // System.out.print("value of adl " + adl.getValue());
- // The value of the adl should be 65537
- assertEquals(
- "update(min) failed to update the checksum to the correct value ",
- 65537L, adl.getValue());
-
- }
-
- /**
- * @tests java.util.zip.Adler32#update(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "update",
- args = {byte[].class}
- )
- public void test_update$B() {
- // test method of java.util.zip.update(byte[])
- byte byteArray[] = {1, 2};
- Adler32 adl = new Adler32();
- adl.update(byteArray);
- // System.out.print("value of adl"+adl.getValue());
- // The value of the adl should be 393220
- assertEquals(
- "update(byte[]) failed to update the checksum to the correct value ",
- 393220, adl.getValue());
-
- adl.reset();
- byte byteEmpty[] = new byte[10000];
- adl.update(byteEmpty);
- // System.out.print("value of adl"+adl.getValue());
- // The value of the adl should be 655360001
- assertEquals(
- "update(byte[]) failed to update the checksum to the correct value ",
- 655360001L, adl.getValue());
-
- }
-
- /**
- * @tests java.util.zip.Adler32#update(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "update",
- args = {byte[].class, int.class, int.class}
- )
- public void test_update$BII() {
- // test methods of java.util.zip.update(byte[],int,int)
- byte[] byteArray = {1, 2, 3};
- Adler32 adl = new Adler32();
- int off = 2;// accessing the 2nd element of byteArray
- int len = 1;
- int lenError = 3;
- int offError = 4;
- adl.update(byteArray, off, len);
- // System.out.print("value of adl"+adl.getValue());
- // The value of the adl should be 262148
- assertEquals(
- "update(byte[],int,int) failed to update the checksum to the correct value ",
- 262148, adl.getValue());
- int r = 0;
-
- try {
- adl.update(byteArray, off, lenError);
- } catch (ArrayIndexOutOfBoundsException e) {
- r = 1;
- }
- assertEquals(
- "update(byte[],int,int) failed b/c lenError>byte[].length-off",
- 1, r);
-
- try {
- adl.update(byteArray, offError, len);
- } catch (ArrayIndexOutOfBoundsException e) {
- r = 2;
- }
- assertEquals(
- "update(byte[],int,int) failed b/c offError>byte[].length", 2,
- r);
-
- }
-
- @Override
+ /**
+ * @tests java.util.zip.Adler32#Adler32()
+ */
+ public void test_Constructor() {
+ // test method of java.util.zip.Adler32()
+ Adler32 adl = new Adler32();
+ assertEquals("Constructor of adl32 failed", 1, adl.getValue());
+ }
+
+ /**
+ * @tests java.util.zip.Adler32#getValue()
+ */
+ public void test_getValue() {
+ // test methods of java.util.zip.getValue()
+ Adler32 adl = new Adler32();
+ assertEquals("GetValue should return a zero as a result of construction an object of Adler32",
+ 1, adl.getValue());
+
+ adl.reset();
+ adl.update(1);
+ // System.out.print("value of adl"+adl.getValue());
+ // The value of the adl should be 131074
+ assertEquals("update(int) failed to update the checksum to the correct value ",
+ 131074, adl.getValue());
+ adl.reset();
+ assertEquals("reset failed to reset the checksum value to zero", 1, adl
+ .getValue());
+
+ adl.reset();
+ adl.update(Integer.MIN_VALUE);
+ // System.out.print("value of adl " + adl.getValue());
+ // The value of the adl should be 65537
+ assertEquals("update(min) failed to update the checksum to the correct value ",
+ 65537L, adl.getValue());
+ }
+
+ /**
+ * @tests java.util.zip.Adler32#reset()
+ */
+ public void test_reset() {
+ // test methods of java.util.zip.reset()
+ Adler32 adl = new Adler32();
+ adl.update(1);
+ // System.out.print("value of adl"+adl.getValue());
+ // The value of the adl should be 131074
+ assertEquals("update(int) failed to update the checksum to the correct value ",
+ 131074, adl.getValue());
+ adl.reset();
+ assertEquals("reset failed to reset the checksum value to zero", 1, adl
+ .getValue());
+ }
+
+ /**
+ * @tests java.util.zip.Adler32#update(int)
+ */
+ public void test_updateI() {
+ // test methods of java.util.zip.update(int)
+ Adler32 adl = new Adler32();
+ adl.update(1);
+ // The value of the adl should be 131074
+ assertEquals("update(int) failed to update the checksum to the correct value ",
+ 131074, adl.getValue());
+
+ adl.reset();
+ adl.update(Integer.MAX_VALUE);
+ // System.out.print("value of adl " + adl.getValue());
+ // The value of the adl should be 16777472
+ assertEquals("update(max) failed to update the checksum to the correct value ",
+ 16777472L, adl.getValue());
+
+ adl.reset();
+ adl.update(Integer.MIN_VALUE);
+ // System.out.print("value of adl " + adl.getValue());
+ // The value of the adl should be 65537
+ assertEquals("update(min) failed to update the checksum to the correct value ",
+ 65537L, adl.getValue());
+
+ }
+
+ /**
+ * @tests java.util.zip.Adler32#update(byte[])
+ */
+ public void test_update$B() {
+ // test method of java.util.zip.update(byte[])
+ byte byteArray[] = { 1, 2 };
+ Adler32 adl = new Adler32();
+ adl.update(byteArray);
+ // System.out.print("value of adl"+adl.getValue());
+ // The value of the adl should be 393220
+ assertEquals("update(byte[]) failed to update the checksum to the correct value ",
+ 393220, adl.getValue());
+
+ adl.reset();
+ byte byteEmpty[] = new byte[10000];
+ adl.update(byteEmpty);
+ // System.out.print("value of adl"+adl.getValue());
+ // The value of the adl should be 655360001
+ assertEquals("update(byte[]) failed to update the checksum to the correct value ",
+ 655360001L, adl.getValue());
+
+ }
+
+ /**
+ * @tests java.util.zip.Adler32#update(byte[], int, int)
+ */
+ public void test_update$BII() {
+ // test methods of java.util.zip.update(byte[],int,int)
+ byte[] byteArray = { 1, 2, 3 };
+ Adler32 adl = new Adler32();
+ int off = 2;// accessing the 2nd element of byteArray
+ int len = 1;
+ int lenError = 3;
+ int offError = 4;
+ adl.update(byteArray, off, len);
+ // System.out.print("value of adl"+adl.getValue());
+ // The value of the adl should be 262148
+ assertEquals("update(byte[],int,int) failed to update the checksum to the correct value ",
+ 262148, adl.getValue());
+ int r = 0;
+
+ try {
+ adl.update(byteArray, off, lenError);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ r = 1;
+ }
+ assertEquals("update(byte[],int,int) failed b/c lenError>byte[].length-off",
+ 1, r);
+
+ try {
+ adl.update(byteArray, offError, len);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ r = 2;
+ }
+ assertEquals("update(byte[],int,int) failed b/c offError>byte[].length",
+ 2, r);
+
+ }
+
+ @Override
protected void setUp() {
- }
+ }
- @Override
+ @Override
protected void tearDown() {
- }
+ }
}
diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/AllTests.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/AllTests.java
index acde889..562b396 100644
--- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/AllTests.java
+++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
* Test suite for java.util.zip package.
*/
public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
-
public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite(
+ TestSuite suite = new TestSuite(
"Suite org.apache.harmony.archive.tests.java.util.zip");
// $JUnit-BEGIN$
suite.addTestSuite(Adler32Test.class);
diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CRC32Test.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CRC32Test.java
index 805cab3..7eb0566 100644
--- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CRC32Test.java
+++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CRC32Test.java
@@ -14,229 +14,173 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.harmony.archive.tests.java.util.zip;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
import java.util.zip.CRC32;
-@TestTargetClass(CRC32.class)
public class CRC32Test extends junit.framework.TestCase {
- /**
- * @tests java.util.zip.CRC32#CRC32()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "CRC32",
- args = {}
- )
- public void test_Constructor() {
- // test methods of java.util.zip.CRC32()
- CRC32 crc = new CRC32();
- assertEquals("Constructor of CRC32 failed", 0, crc.getValue());
- }
-
- /**
- * @tests java.util.zip.CRC32#getValue()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getValue",
- args = {}
- )
- public void test_getValue() {
- // test methods of java.util.zip.crc32.getValue()
- CRC32 crc = new CRC32();
- assertEquals(
- "getValue() should return a zero as a result of constructing a CRC32 instance",
- 0, crc.getValue());
-
- crc.reset();
- crc.update(Integer.MAX_VALUE);
- // System.out.print("value of crc " + crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 4278190080
- assertEquals(
- "update(max) failed to update the checksum to the correct value ",
- 4278190080L, crc.getValue());
-
- crc.reset();
- byte byteEmpty[] = new byte[10000];
- crc.update(byteEmpty);
- // System.out.print("value of crc"+crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 1295764014
- assertEquals(
- "update(byte[]) failed to update the checksum to the correct value ",
- 1295764014L, crc.getValue());
-
- crc.reset();
- crc.update(1);
- // System.out.print("value of crc"+crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 2768625435
- // assertEquals("update(int) failed to update the checksum to the
- // correct
- // value ",2768625435L, crc.getValue());
- crc.reset();
- assertEquals("reset failed to reset the checksum value to zero", 0, crc
- .getValue());
- }
-
- /**
- * @tests java.util.zip.CRC32#reset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reset",
- args = {}
- )
- public void test_reset() {
- // test methods of java.util.zip.crc32.reset()
- CRC32 crc = new CRC32();
- crc.update(1);
- // System.out.print("value of crc"+crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 2768625435
- assertEquals(
- "update(int) failed to update the checksum to the correct value ",
- 2768625435L, crc.getValue());
- crc.reset();
- assertEquals("reset failed to reset the checksum value to zero", 0, crc
- .getValue());
-
- }
-
- /**
- * @tests java.util.zip.CRC32#update(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "update",
- args = {int.class}
- )
- public void test_updateI() {
- // test methods of java.util.zip.crc32.update(int)
- CRC32 crc = new CRC32();
- crc.update(1);
- // System.out.print("value of crc"+crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 2768625435
- assertEquals(
- "update(1) failed to update the checksum to the correct value ",
- 2768625435L, crc.getValue());
-
- crc.reset();
- crc.update(Integer.MAX_VALUE);
- // System.out.print("value of crc " + crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 4278190080
- assertEquals(
- "update(max) failed to update the checksum to the correct value ",
- 4278190080L, crc.getValue());
-
- crc.reset();
- crc.update(Integer.MIN_VALUE);
- // System.out.print("value of crc " + crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 3523407757
- assertEquals(
- "update(min) failed to update the checksum to the correct value ",
- 3523407757L, crc.getValue());
- }
-
- /**
- * @tests java.util.zip.CRC32#update(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "update",
- args = {byte[].class}
- )
- public void test_update$B() {
- // test methods of java.util.zip.crc32.update(byte[])
- byte byteArray[] = {1, 2};
- CRC32 crc = new CRC32();
- crc.update(byteArray);
- // System.out.print("value of crc"+crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 3066839698
- assertEquals(
- "update(byte[]) failed to update the checksum to the correct value ",
- 3066839698L, crc.getValue());
-
- crc.reset();
- byte byteEmpty[] = new byte[10000];
- crc.update(byteEmpty);
- // System.out.print("value of crc"+crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 1295764014
- assertEquals(
- "update(byte[]) failed to update the checksum to the correct value ",
- 1295764014L, crc.getValue());
- }
-
- /**
- * @tests java.util.zip.CRC32#update(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "update",
- args = {byte[].class, int.class, int.class}
- )
- public void test_update$BII() {
- // test methods of java.util.zip.update(byte[],int,int)
- byte[] byteArray = {1, 2, 3};
- CRC32 crc = new CRC32();
- int off = 2;// accessing the 2nd element of byteArray
- int len = 1;
- int lenError = 3;
- int offError = 4;
- crc.update(byteArray, off, len);
- // System.out.print("value of crc"+crc.getValue());
- // Ran JDK and discovered that the value of the CRC should be
- // 1259060791
- assertEquals(
- "update(byte[],int,int) failed to update the checksum to the correct value ",
- 1259060791L, crc.getValue());
- int r = 0;
- try {
- crc.update(byteArray, off, lenError);
- } catch (ArrayIndexOutOfBoundsException e) {
- r = 1;
- }
- assertEquals(
- "update(byte[],int,int) failed b/c lenError>byte[].length-off",
- 1, r);
-
- try {
- crc.update(byteArray, offError, len);
- } catch (ArrayIndexOutOfBoundsException e) {
- r = 2;
- }
- assertEquals(
- "update(byte[],int,int) failed b/c offError>byte[].length", 2,
- r);
- }
-
- @Override
+ /**
+ * @tests java.util.zip.CRC32#CRC32()
+ */
+ public void test_Constructor() {
+ // test methods of java.util.zip.CRC32()
+ CRC32 crc = new CRC32();
+ assertEquals("Constructor of CRC32 failed", 0, crc.getValue());
+ }
+
+ /**
+ * @tests java.util.zip.CRC32#getValue()
+ */
+ public void test_getValue() {
+ // test methods of java.util.zip.crc32.getValue()
+ CRC32 crc = new CRC32();
+ assertEquals("getValue() should return a zero as a result of constructing a CRC32 instance",
+ 0, crc.getValue());
+
+ crc.reset();
+ crc.update(Integer.MAX_VALUE);
+ // System.out.print("value of crc " + crc.getValue());
+ // Ran JDK and discovered that the value of the CRC should be
+ // 4278190080
+ assertEquals("update(max) failed to update the checksum to the correct value ",
+ 4278190080L, crc.getValue());
+
+ crc.reset();
+ byte byteEmpty[] = new byte[10000];
+ crc.update(byteEmpty);
+ // System.out.print("value of crc"+crc.getValue());
+ // Ran JDK and discovered that the value of the CRC should be
+ // 1295764014
+ assertEquals("update(byte[]) failed to update the checksum to the correct value ",
+ 1295764014L, crc.getValue());
+
+ crc.reset();
+ crc.update(1);
+ // System.out.print("value of crc"+crc.getValue());
+ // Ran JDK and discovered that the value of the CRC should be
+ // 2768625435
+ // assertEquals("update(int) failed to update the checksum to the correct
+ // value ",2768625435L, crc.getValue());
+ crc.reset();
+ assertEquals("reset failed to reset the checksum value to zero", 0, crc
+ .getValue());
+ }
+
+ /**
+ * @tests java.util.zip.CRC32#reset()
+ */
+ public void test_reset() {
+ // test methods of java.util.zip.crc32.reset()
+ CRC32 crc = new CRC32();
+ crc.update(1);
+ // System.out.print("value of crc"+crc.getValue());
+ // Ran JDK and discovered that the value of the CRC should be
+ // 2768625435
+ assertEquals("update(int) failed to update the checksum to the correct value ",
+ 2768625435L, crc.getValue());
+ crc.reset();
+ assertEquals("reset failed to reset the checksum value to zero", 0, crc
+ .getValue());
+
+ }
+
+ /**
+ * @tests java.util.zip.CRC32#update(int)
+ */
+ public void test_updateI() {
+ // test methods of java.util.zip.crc32.update(int)
+ CRC32 crc = new CRC32();
+ crc.update(1);
+ // System.out.print("value of crc"+crc.getValue());
+ // Ran JDK and discovered that the value of the CRC should be
+ // 2768625435
+ assertEquals("update(1) failed to update the checksum to the correct value ",
+ 2768625435L, crc.getValue());
+
+ crc.reset();
+ crc.update(Integer.MAX_VALUE);
+ // System.out.print("value of crc " + crc.getValue());
+ // Ran JDK and discovered that the value of the CRC should be
+ // 4278190080
+ assertEquals("update(max) failed to update the checksum to the correct value ",
+ 4278190080L, crc.getValue());
+
+ crc.reset();
+ crc.update(Integer.MIN_VALUE);
+ // System.out.print("value of crc " + crc.getValue());
+ // Ran JDK and discovered that the value of the CRC should be
+ // 3523407757
+ assertEquals("update(min) failed to update the checksum to the correct value ",
+ 3523407757L, crc.getValue());
+ }
+
+ /**
+ * @tests java.util.zip.CRC32#update(byte[])
+ */
+ public void test_update$B() {
+ // test methods of java.util.zip.crc32.update(byte[])
+ byte byteArray[] = { 1, 2 };
+ CRC32 crc = new CRC32();
+ crc.update(byteArray);
+ // System.out.print("value of crc"+crc.getValue());
+ // Ran JDK and discovered that the value of the CRC should be
+ // 3066839698
+ assertEquals("update(byte[]) failed to update the checksum to the correct value ",
+ 3066839698L, crc.getValue());
+
+ crc.reset();
+ byte byteEmpty[] = new byte[10000];
+ crc.update(byteEmpty);
+ // System.out.print("value of crc"+crc.getValue());
+ // Ran JDK and discovered that the value of the CRC should be
+ // 1295764014
+ assertEquals("update(byte[]) failed to update the checksum to the correct value ",
+ 1295764014L, crc.getValue());
+ }
+
+ /**
+ * @tests java.util.zip.CRC32#update(byte[], int, int)
+ */
+ public void test_update$BII() {
+ // test methods of java.util.zip.update(byte[],int,int)
+ byte[] byteArray = { 1, 2, 3 };
+ CRC32 crc = new CRC32();
+ int off = 2;// accessing the 2nd element of byteArray
+ int len = 1;
+ int lenError = 3;
+ int offError = 4;
+ crc.update(byteArray, off, len);
+ // System.out.print("value of crc"+crc.getValue());
+ // Ran JDK and discovered that the value of the CRC should be
+ // 1259060791
+ assertEquals("update(byte[],int,int) failed to update the checksum to the correct value ",
+ 1259060791L, crc.getValue());
+ int r = 0;
+ try {
+ crc.update(byteArray, off, lenError);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ r = 1;
+ }
+ assertEquals("update(byte[],int,int) failed b/c lenError>byte[].length-off",
+ 1, r);
+
+ try {
+ crc.update(byteArray, offError, len);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ r = 2;
+ }
+ assertEquals("update(byte[],int,int) failed b/c offError>byte[].length",
+ 2, r);
+ }
+
+ @Override
protected void setUp() {
- }
+ }
- @Override
+ @Override
protected void tearDown() {
- }
+ }
}
diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CheckedInputStreamTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CheckedInputStreamTest.java
index 4450bdf..393923d 100644
--- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CheckedInputStreamTest.java
+++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/CheckedInputStreamTest.java
@@ -14,139 +14,99 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.harmony.archive.tests.java.util.zip;
-import dalvik.annotation.TestTargetClass;
-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.IOException;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
+
import junit.framework.TestCase;
import tests.support.resource.Support_Resources;
-
-@TestTargetClass(CheckedInputStream.class)
public class CheckedInputStreamTest extends TestCase {
+
+ @Override
+ protected void tearDown() {
+ try {
+ File deletedFile = new File("empty.txt");
+ deletedFile.delete();
+ } catch (SecurityException e) {
+ fail("Cannot delete file for security reasons");
+ }
- /**
- * @tests java.util.zip.CheckedInputStream#CheckedInputStream(java.io.InputStream,
- * java.util.zip.Checksum)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "CheckedInputStream",
- args = {java.io.InputStream.class, java.util.zip.Checksum.class}
- )
- public void test_ConstructorLjava_io_InputStreamLjava_util_zip_Checksum()
- throws Exception {
- InputStream checkInput = Support_Resources
- .getStream("hyts_checkInput.txt");
- CheckedInputStream checkIn = new CheckedInputStream(checkInput,
- new CRC32());
- assertEquals("constructor of checkedInputStream has failed", 0, checkIn
- .getChecksum().getValue());
+ }
+
+ /**
+ * @tests java.util.zip.CheckedInputStream#CheckedInputStream(java.io.InputStream,
+ * java.util.zip.Checksum)
+ */
+ public void test_ConstructorLjava_io_InputStreamLjava_util_zip_Checksum() throws Exception {
+ InputStream checkInput = Support_Resources.getStream("hyts_checkInput.txt");
+ CheckedInputStream checkIn = new CheckedInputStream(checkInput, new CRC32());
+ assertEquals("constructor of checkedInputStream has failed", 0, checkIn.getChecksum()
+ .getValue());
checkInput.close();
}
- /**
- * @tests java.util.zip.CheckedInputStream#getChecksum()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getChecksum",
- args = {}
- )
- public void test_getChecksum() throws Exception {
+ /**
+ * @tests java.util.zip.CheckedInputStream#getChecksum()
+ */
+ public void test_getChecksum() throws Exception {
byte outBuf[] = new byte[100];
// testing getChecksum for an empty file
- File empty = File.createTempFile("empty", ".txt");
- empty.deleteOnExit();
- FileOutputStream outEmp = new FileOutputStream(empty);
+ FileOutputStream outEmp = new FileOutputStream("empty.txt");
outEmp.close();
- InputStream inEmp = new FileInputStream(empty);
- CheckedInputStream checkEmpty = new CheckedInputStream(inEmp,
- new CRC32());
+ InputStream inEmp = new FileInputStream("empty.txt");
+ CheckedInputStream checkEmpty = new CheckedInputStream(inEmp, new CRC32());
while (checkEmpty.read() >= 0) {
}
- assertEquals("the checkSum value of an empty file is not zero", 0,
- checkEmpty.getChecksum().getValue());
+ assertEquals("the checkSum value of an empty file is not zero", 0, checkEmpty
+ .getChecksum().getValue());
inEmp.close();
// testing getChecksum for the file checkInput
- InputStream checkInput = Support_Resources
- .getStream("hyts_checkInput.txt");
- CheckedInputStream checkIn = new CheckedInputStream(checkInput,
- new CRC32());
+ InputStream checkInput = Support_Resources.getStream("hyts_checkInput.txt");
+ CheckedInputStream checkIn = new CheckedInputStream(checkInput, new CRC32());
while (checkIn.read() >= 0) {
}
// ran JDK and found that the checkSum value of this is 2036203193
// System.out.print(" " + checkIn.getChecksum().getValue());
- assertEquals("the checksum value is incorrect", 2036203193, checkIn
- .getChecksum().getValue());
+ assertEquals("the checksum value is incorrect", 2036203193, checkIn.getChecksum()
+ .getValue());
checkInput.close();
// testing getChecksum for file checkInput
checkInput = Support_Resources.getStream("hyts_checkInput.txt");
- CheckedInputStream checkIn2 = new CheckedInputStream(checkInput,
- new CRC32());
+ CheckedInputStream checkIn2 = new CheckedInputStream(checkInput, new CRC32());
checkIn2.read(outBuf, 0, 10);
// ran JDK and found that the checkSum value of this is 2235765342
// System.out.print(" " + checkIn2.getChecksum().getValue());
- assertEquals("the checksum value is incorrect", 2235765342L, checkIn2
- .getChecksum().getValue());
+ assertEquals("the checksum value is incorrect", 2235765342L, checkIn2.getChecksum()
+ .getValue());
checkInput.close();
}
- /**
- * @tests java.util.zip.CheckedInputStream#skip(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "skip",
- args = {long.class}
- )
- public void test_skipJ() throws Exception {
+ /**
+ * @tests java.util.zip.CheckedInputStream#skip(long)
+ */
+ public void test_skipJ() throws Exception {
// testing that the return by skip is valid
- InputStream checkInput = Support_Resources
- .getStream("hyts_checkInput.txt");
- CheckedInputStream checkIn = new CheckedInputStream(checkInput,
- new CRC32());
+ InputStream checkInput = Support_Resources.getStream("hyts_checkInput.txt");
+ CheckedInputStream checkIn = new CheckedInputStream(checkInput, new CRC32());
long skipValue = 5;
- assertEquals(
- "the value returned by skip(n) is not the same as its parameter",
+ assertEquals("the value returned by skip(n) is not the same as its parameter",
skipValue, checkIn.skip(skipValue));
checkIn.skip(skipValue);
// ran JDK and found the checkSum value is 2235765342
// System.out.print(checkIn.getChecksum().getValue());
- assertEquals("checkSum value is not correct", 2235765342L, checkIn
- .getChecksum().getValue());
+ assertEquals("checkSum value is not correct", 2235765342L, checkIn.getChecksum()
+ .getValue());
checkInput.close();
- try {
- checkInput.skip(33);
- fail("IOException expected");
- } catch (IOException ee) {
- // expected
- }
}
- /**
- * @tests java.util.zip.CheckedInputStream#read()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "read",
- args = {}
- )
public void test_read() throws Exception {
// testing that the return by skip is valid
InputStream checkInput = Support_Resources
@@ -161,16 +121,9 @@ public class CheckedInputStreamTest extends TestCase {
} catch (IOException ee) {
// expected
}
- long skipValue = 5;
checkInput.close();
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "read",
- args = {byte[].class, int.class, int.class}
- )
public void test_read$byteII() throws Exception {
// testing that the return by skip is valid
InputStream checkInput = Support_Resources
@@ -186,7 +139,6 @@ public class CheckedInputStreamTest extends TestCase {
} catch (IOException ee) {
// expected
}
- long skipValue = 5;
checkInput.close();
}
}
diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterOutputStreamTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterOutputStreamTest.java
index 738f610..be28774 100644
--- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterOutputStreamTest.java
+++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterOutputStreamTest.java
@@ -17,11 +17,6 @@
package org.apache.harmony.archive.tests.java.util.zip;
-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;
@@ -34,7 +29,6 @@ import java.util.zip.InflaterInputStream;
import junit.framework.TestCase;
-@TestTargetClass(DeflaterOutputStream.class)
public class DeflaterOutputStreamTest extends TestCase {
private class MyDeflaterOutputStream extends DeflaterOutputStream {
@@ -64,10 +58,6 @@ public class DeflaterOutputStreamTest extends TestCase {
boolean getDaflateFlag() {
return deflateFlag;
}
-
- void cleanDaflateFlag() {
- deflateFlag = false;
- }
}
private byte outPutBuf[] = new byte[500];
@@ -75,7 +65,7 @@ public class DeflaterOutputStreamTest extends TestCase {
@Override
protected void setUp() {
// setting up a deflater to be used
- byte byteArray[] = {1, 3, 4, 7, 8};
+ byte byteArray[] = { 1, 3, 4, 7, 8 };
int x = 0;
Deflater deflate = new Deflater(1);
deflate.setInput(byteArray);
@@ -93,16 +83,9 @@ public class DeflaterOutputStreamTest extends TestCase {
* @tests java.util.zip.DeflaterOutputStream#DeflaterOutputStream(java.io.OutputStream,
* java.util.zip.Deflater)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "DeflaterOutputStream",
- args = {java.io.OutputStream.class, java.util.zip.Deflater.class}
- )
- public void test_ConstructorLjava_io_OutputStreamLjava_util_zip_Deflater()
- throws Exception {
- byte byteArray[] = {1, 3, 4, 7, 8};
- File f1 = File.createTempFile("hyts_Constru_OD", ".tst");
+ public void test_ConstructorLjava_io_OutputStreamLjava_util_zip_Deflater() throws Exception {
+ byte byteArray[] = { 1, 3, 4, 7, 8 };
+ File f1 = new File("hyts_Constru(OD).tst");
FileOutputStream fos = new FileOutputStream(f1);
Deflater defl = null;
MyDeflaterOutputStream dos;
@@ -127,14 +110,8 @@ public class DeflaterOutputStreamTest extends TestCase {
/**
* @tests java.util.zip.DeflaterOutputStream#DeflaterOutputStream(java.io.OutputStream)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "DeflaterOutputStream",
- args = {java.io.OutputStream.class}
- )
public void test_ConstructorLjava_io_OutputStream() throws Exception {
- File f1 = File.createTempFile("hyts_Constru_O", ".tst");
+ File f1 = new File("hyts_Constru(O).tst");
FileOutputStream fos = new FileOutputStream(f1);
MyDeflaterOutputStream dos = new MyDeflaterOutputStream(fos);
@@ -151,19 +128,13 @@ public class DeflaterOutputStreamTest extends TestCase {
* @tests java.util.zip.DeflaterOutputStream#DeflaterOutputStream(java.io.OutputStream,
* java.util.zip.Deflater, int)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "DeflaterOutputStream",
- args = {java.io.OutputStream.class, java.util.zip.Deflater.class, int.class}
- )
public void test_ConstructorLjava_io_OutputStreamLjava_util_zip_DeflaterI()
throws Exception {
int buf = 5;
int negBuf = -5;
int zeroBuf = 0;
- byte byteArray[] = {1, 3, 4, 7, 8, 3, 6};
- File f1 = File.createTempFile("hyts_Constru_ODI", ".tst");
+ byte byteArray[] = { 1, 3, 4, 7, 8, 3, 6 };
+ File f1 = new File("hyts_Constru(ODI).tst");
FileOutputStream fos = new FileOutputStream(f1);
Deflater defl = null;
MyDeflaterOutputStream dos;
@@ -203,12 +174,6 @@ public class DeflaterOutputStreamTest extends TestCase {
/**
* @tests java.util.zip.DeflaterOutputStream#close()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "IOException can not be checked.",
- method = "close",
- args = {}
- )
public void test_close() throws Exception {
File f1 = File.createTempFile("close", ".tst");
@@ -268,20 +233,14 @@ public class DeflaterOutputStreamTest extends TestCase {
/**
* @tests java.util.zip.DeflaterOutputStream#finish()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "finish",
- args = {}
- )
public void test_finish() throws Exception {
// Need test to see if method finish() actually finishes
// Only testing possible errors, not if it actually works
- File f1 = File.createTempFile("finish", ".tst");
+ File f1 = new File("finish.tst");
FileOutputStream fos1 = new FileOutputStream(f1);
DeflaterOutputStream dos = new DeflaterOutputStream(fos1);
- byte byteArray[] = {1, 3, 4, 6};
+ byte byteArray[] = { 1, 3, 4, 6 };
dos.write(byteArray);
dos.finish();
@@ -325,14 +284,8 @@ public class DeflaterOutputStreamTest extends TestCase {
/**
* @tests java.util.zip.DeflaterOutputStream#write(int)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {int.class}
- )
public void test_writeI() throws Exception {
- File f1 = File.createTempFile("writeI1", ".tst");
+ File f1 = new File("writeI1.tst");
FileOutputStream fos = new FileOutputStream(f1);
DeflaterOutputStream dos = new DeflaterOutputStream(fos);
for (int i = 0; i < 3; i++) {
@@ -367,17 +320,11 @@ public class DeflaterOutputStreamTest extends TestCase {
/**
* @tests java.util.zip.DeflaterOutputStream#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 {
- byte byteArray[] = {1, 3, 4, 7, 8, 3, 6};
+ byte byteArray[] = { 1, 3, 4, 7, 8, 3, 6 };
// Test to see if the correct bytes are saved.
- File f1 = File.createTempFile("writeBII", ".tst");
+ File f1 = new File("writeBII.tst");
FileOutputStream fos1 = new FileOutputStream(f1);
DeflaterOutputStream dos1 = new DeflaterOutputStream(fos1);
dos1.write(byteArray, 2, 3);
@@ -393,7 +340,7 @@ public class DeflaterOutputStreamTest extends TestCase {
f1.delete();
// Test for trying to write more bytes than available from the array
- File f2 = File.createTempFile("writeBII", ".tst");
+ File f2 = new File("writeBII2.tst");
FileOutputStream fos2 = new FileOutputStream(f2);
DeflaterOutputStream dos2 = new DeflaterOutputStream(fos2);
try {
@@ -441,13 +388,6 @@ public class DeflaterOutputStreamTest extends TestCase {
f2.delete();
}
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "deflate",
- args = {}
- )
public void test_deflate() throws Exception {
File f1 = File.createTempFile("writeI1", ".tst");
FileOutputStream fos = new FileOutputStream(f1);
diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterTest.java
index ae77450..93fe710 100644
--- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterTest.java
+++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/DeflaterTest.java
@@ -17,15 +17,9 @@
package org.apache.harmony.archive.tests.java.util.zip;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.zip.Adler32;
-
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
@@ -33,447 +27,376 @@ import java.util.zip.Inflater;
import junit.framework.TestCase;
import tests.support.resource.Support_Resources;
-@TestTargetClass(Deflater.class)
public class DeflaterTest extends TestCase {
- class MyDeflater extends Deflater {
- MyDeflater() {
- super();
- }
-
- MyDeflater(int lvl) {
- super(lvl);
- }
-
- MyDeflater(int lvl, boolean noHeader) {
- super(lvl, noHeader);
- }
-
- void myFinalize() {
- finalize();
- }
-
- int getDefCompression() {
- return DEFAULT_COMPRESSION;
- }
-
- int getDefStrategy() {
- return DEFAULT_STRATEGY;
- }
-
- int getHuffman() {
- return HUFFMAN_ONLY;
- }
-
- int getFiltered() {
- return FILTERED;
- }
- }
-
- /**
- * @tests java.util.zip.Deflater#deflate(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "deflate",
- args = {byte[].class}
- )
- public void test_deflate$B() {
- byte outPutBuf[] = new byte[50];
- byte byteArray[] = {1, 3, 4, 7, 8};
- byte outPutInf[] = new byte[50];
- int x = 0;
-
- Deflater defl = new Deflater();
- defl.setInput(byteArray);
- defl.finish();
- while (!defl.finished()) {
+ class MyDeflater extends Deflater {
+ MyDeflater() {
+ super();
+ }
+
+ MyDeflater(int lvl) {
+ super(lvl);
+ }
+
+ MyDeflater(int lvl, boolean noHeader) {
+ super(lvl, noHeader);
+ }
+
+ void myFinalize() {
+ finalize();
+ }
+
+ int getDefCompression() {
+ return DEFAULT_COMPRESSION;
+ }
+
+ int getDefStrategy() {
+ return DEFAULT_STRATEGY;
+ }
+
+ int getHuffman() {
+ return HUFFMAN_ONLY;
+ }
+
+ int getFiltered() {
+ return FILTERED;
+ }
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#deflate(byte[])
+ */
+ public void test_deflate$B() {
+ byte outPutBuf[] = new byte[50];
+ byte byteArray[] = { 1, 3, 4, 7, 8 };
+ byte outPutInf[] = new byte[50];
+ int x = 0;
+
+ Deflater defl = new Deflater();
+ defl.setInput(byteArray);
+ defl.finish();
+ while (!defl.finished()) {
x += defl.deflate(outPutBuf);
}
- assertEquals("Deflater at end of stream, should return 0", 0, defl
- .deflate(outPutBuf));
+ assertEquals("Deflater at end of stream, should return 0", 0, defl
+ .deflate(outPutBuf));
int totalOut = defl.getTotalOut();
int totalIn = defl.getTotalIn();
assertEquals(x, totalOut);
assertEquals(byteArray.length, totalIn);
- defl.end();
+ defl.end();
- Inflater infl = new Inflater();
- try {
- infl.setInput(outPutBuf);
- while (!infl.finished()) {
+ Inflater infl = new Inflater();
+ try {
+ infl.setInput(outPutBuf);
+ while (!infl.finished()) {
infl.inflate(outPutInf);
}
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- }
+ } catch (DataFormatException e) {
+ fail("Invalid input to be decompressed");
+ }
assertEquals(totalIn, infl.getTotalOut());
assertEquals(totalOut, infl.getTotalIn());
- for (int i = 0; i < byteArray.length; i++) {
+ for (int i = 0; i < byteArray.length; i++) {
assertEquals(byteArray[i], outPutInf[i]);
}
- assertEquals(
- "Final decompressed data contained more bytes than original",
- 0, outPutInf[byteArray.length]);
- infl.end();
- }
-
- /**
- * @tests java.util.zip.Deflater#deflate(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "deflate",
- args = {byte[].class, int.class, int.class}
- )
- public void test_deflate$BII() {
- byte outPutBuf[] = new byte[50];
- byte byteArray[] = {5, 2, 3, 7, 8};
- byte outPutInf[] = new byte[50];
- int offSet = 1;
- int length = outPutBuf.length - 1;
- int x = 0;
-
- Deflater defl = new Deflater();
- defl.setInput(byteArray);
- defl.finish();
- while (!defl.finished()) {
+ assertEquals("Final decompressed data contained more bytes than original",
+ 0, outPutInf[byteArray.length]);
+ infl.end();
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#deflate(byte[], int, int)
+ */
+ public void test_deflate$BII() {
+ byte outPutBuf[] = new byte[50];
+ byte byteArray[] = { 5, 2, 3, 7, 8 };
+ byte outPutInf[] = new byte[50];
+ int offSet = 1;
+ int length = outPutBuf.length - 1;
+ int x = 0;
+
+ Deflater defl = new Deflater();
+ defl.setInput(byteArray);
+ defl.finish();
+ while (!defl.finished()) {
x += defl.deflate(outPutBuf, offSet, length);
}
- assertEquals("Deflater at end of stream, should return 0", 0, defl
- .deflate(outPutBuf, offSet, length));
- int totalOut = defl.getTotalOut();
- int totalIn = defl.getTotalIn();
+ assertEquals("Deflater at end of stream, should return 0", 0, defl.deflate(
+ outPutBuf, offSet, length));
+ int totalOut = defl.getTotalOut();
+ int totalIn = defl.getTotalIn();
assertEquals(x, totalOut);
assertEquals(byteArray.length, totalIn);
- defl.end();
+ defl.end();
- Inflater infl = new Inflater();
- try {
- infl.setInput(outPutBuf, offSet, length);
- while (!infl.finished()) {
+ Inflater infl = new Inflater();
+ try {
+ infl.setInput(outPutBuf, offSet, length);
+ while (!infl.finished()) {
infl.inflate(outPutInf);
}
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- }
+ } catch (DataFormatException e) {
+ fail("Invalid input to be decompressed");
+ }
assertEquals(totalIn, infl.getTotalOut());
assertEquals(totalOut, infl.getTotalIn());
- for (int i = 0; i < byteArray.length; i++) {
+ for (int i = 0; i < byteArray.length; i++) {
assertEquals(byteArray[i], outPutInf[i]);
}
- assertEquals(
- "Final decompressed data contained more bytes than original",
- 0, outPutInf[byteArray.length]);
- infl.end();
-
- // Set of tests testing the boundaries of the offSet/length
- defl = new Deflater();
- outPutBuf = new byte[100];
- defl.setInput(byteArray);
- for (int i = 0; i < 2; i++) {
- if (i == 0) {
- offSet = outPutBuf.length + 1;
- length = outPutBuf.length;
- } else {
- offSet = 0;
- length = outPutBuf.length + 1;
- }
- try {
- defl.deflate(outPutBuf, offSet, length);
- fail("Test " + i
- + ": ArrayIndexOutOfBoundsException not thrown");
- } catch (ArrayIndexOutOfBoundsException e) {
- }
- }
- defl.end();
- }
-
- /**
- * @tests java.util.zip.Deflater#end()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "end",
- args = {}
- )
- public void test_end() {
- byte byteArray[] = {5, 2, 3, 7, 8};
- byte outPutBuf[] = new byte[100];
-
- Deflater defl = new Deflater();
- defl.setInput(byteArray);
- defl.finish();
- while (!defl.finished()) {
+ assertEquals("Final decompressed data contained more bytes than original",
+ 0, outPutInf[byteArray.length]);
+ infl.end();
+
+ // Set of tests testing the boundaries of the offSet/length
+ defl = new Deflater();
+ outPutBuf = new byte[100];
+ defl.setInput(byteArray);
+ for (int i = 0; i < 2; i++) {
+ if (i == 0) {
+ offSet = outPutBuf.length + 1;
+ length = outPutBuf.length;
+ } else {
+ offSet = 0;
+ length = outPutBuf.length + 1;
+ }
+ try {
+ defl.deflate(outPutBuf, offSet, length);
+ fail("Test " + i
+ + ": ArrayIndexOutOfBoundsException not thrown");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ }
+ }
+ defl.end();
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#end()
+ */
+ public void test_end() {
+ byte byteArray[] = { 5, 2, 3, 7, 8 };
+ byte outPutBuf[] = new byte[100];
+
+ Deflater defl = new Deflater();
+ defl.setInput(byteArray);
+ defl.finish();
+ while (!defl.finished()) {
defl.deflate(outPutBuf);
}
- defl.end();
- helper_end_test(defl, "end");
- }
-
- /**
- * @tests java.util.zip.Deflater#finalize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "finalize",
- args = {}
- )
- public void test_finalize() {
- MyDeflater mdefl = new MyDeflater();
- mdefl.myFinalize();
- System.gc();
- helper_end_test(mdefl, "finalize");
- }
-
- /**
- * @tests java.util.zip.Deflater#finish()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "finish",
- args = {}
- )
- public void test_finish() throws Exception {
- // This test already here, its the same as test_deflate()
- byte byteArray[] = {5, 2, 3, 7, 8};
- byte outPutBuf[] = new byte[100];
- byte outPutInf[] = new byte[100];
- int x = 0;
- Deflater defl = new Deflater();
- defl.setInput(byteArray);
- defl.finish();
-
- // needsInput should never return true after finish() is called
- if (System.getProperty("java.vendor").startsWith("IBM")) {
- assertFalse(
- "needsInput() should return false after finish() is called",
- defl.needsInput());
- }
-
- while (!defl.finished()) {
+ defl.end();
+ helper_end_test(defl, "end");
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#finalize()
+ */
+ public void test_finalize() {
+ MyDeflater mdefl = new MyDeflater();
+ mdefl.myFinalize();
+ System.gc();
+ helper_end_test(mdefl, "finalize");
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#finish()
+ */
+ public void test_finish() throws Exception {
+ // This test already here, its the same as test_deflate()
+ byte byteArray[] = { 5, 2, 3, 7, 8 };
+ byte outPutBuf[] = new byte[100];
+ byte outPutInf[] = new byte[100];
+ int x = 0;
+ Deflater defl = new Deflater();
+ defl.setInput(byteArray);
+ defl.finish();
+
+ // needsInput should never return true after finish() is called
+ if (System.getProperty("java.vendor").startsWith("IBM")) {
+ assertFalse("needsInput() should return false after finish() is called", defl
+ .needsInput());
+ }
+
+ while (!defl.finished()) {
x += defl.deflate(outPutBuf);
}
- int totalOut = defl.getTotalOut();
- int totalIn = defl.getTotalIn();
+ int totalOut = defl.getTotalOut();
+ int totalIn = defl.getTotalIn();
assertEquals(x, totalOut);
assertEquals(byteArray.length, totalIn);
- defl.end();
+ defl.end();
- Inflater infl = new Inflater();
- infl.setInput(outPutBuf);
- while (!infl.finished()) {
- infl.inflate(outPutInf);
- }
+ Inflater infl = new Inflater();
+ infl.setInput(outPutBuf);
+ while (!infl.finished()) {
+ infl.inflate(outPutInf);
+ }
assertEquals(totalIn, infl.getTotalOut());
assertEquals(totalOut, infl.getTotalIn());
- for (int i = 0; i < byteArray.length; i++) {
+ for (int i = 0; i < byteArray.length; i++) {
assertEquals(byteArray[i], outPutInf[i]);
}
- assertEquals(
- "Final decompressed data contained more bytes than original",
- 0, outPutInf[byteArray.length]);
- infl.end();
- }
-
- /**
- * @tests java.util.zip.Deflater#finished()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "finished",
- args = {}
- )
- public void test_finished() {
- byte byteArray[] = {5, 2, 3, 7, 8};
- byte outPutBuf[] = new byte[100];
- Deflater defl = new Deflater();
- assertTrue("Test 1: Deflater should not be finished.", !defl.finished());
- defl.setInput(byteArray);
- assertTrue("Test 2: Deflater should not be finished.", !defl.finished());
- defl.finish();
- assertTrue("Test 3: Deflater should not be finished.", !defl.finished());
- while (!defl.finished()) {
+ assertEquals("Final decompressed data contained more bytes than original",
+ 0, outPutInf[byteArray.length]);
+ infl.end();
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#finished()
+ */
+ public void test_finished() {
+ byte byteArray[] = { 5, 2, 3, 7, 8 };
+ byte outPutBuf[] = new byte[100];
+ Deflater defl = new Deflater();
+ assertTrue("Test 1: Deflater should not be finished.", !defl.finished());
+ defl.setInput(byteArray);
+ assertTrue("Test 2: Deflater should not be finished.", !defl.finished());
+ defl.finish();
+ assertTrue("Test 3: Deflater should not be finished.", !defl.finished());
+ while (!defl.finished()) {
defl.deflate(outPutBuf);
}
- assertTrue("Test 4: Deflater should be finished.", defl.finished());
- defl.end();
- assertTrue("Test 5: Deflater should be finished.", defl.finished());
- }
-
- /**
- * @tests java.util.zip.Deflater#getAdler()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAdler",
- args = {}
- )
- public void test_getAdler() {
- byte byteArray[] = {'a', 'b', 'c', 1, 2, 3};
- byte outPutBuf[] = new byte[100];
- Deflater defl = new Deflater();
-
- // getting the checkSum value using the Adler
- defl.setInput(byteArray);
- defl.finish();
- while (!defl.finished()) {
+ assertTrue("Test 4: Deflater should be finished.", defl.finished());
+ defl.end();
+ assertTrue("Test 5: Deflater should be finished.", defl.finished());
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#getAdler()
+ */
+ public void test_getAdler() {
+ byte byteArray[] = { 'a', 'b', 'c', 1, 2, 3 };
+ byte outPutBuf[] = new byte[100];
+ Deflater defl = new Deflater();
+
+ // getting the checkSum value using the Adler
+ defl.setInput(byteArray);
+ defl.finish();
+ while (!defl.finished()) {
defl.deflate(outPutBuf);
}
- long checkSumD = defl.getAdler();
- defl.end();
-
- // getting the checkSum value through the Adler32 class
- Adler32 adl = new Adler32();
- adl.update(byteArray);
- long checkSumR = adl.getValue();
- assertEquals(
+ long checkSumD = defl.getAdler();
+ defl.end();
+
+ // getting the checkSum value through the Adler32 class
+ Adler32 adl = new Adler32();
+ adl.update(byteArray);
+ long checkSumR = adl.getValue();
+ assertEquals(
"The checksum value returned by getAdler() is not the same as the checksum returned by creating the adler32 instance",
checkSumD, checkSumR);
- }
-
- /**
- * @tests java.util.zip.Deflater#getTotalIn()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTotalIn",
- args = {}
- )
- public void test_getTotalIn() {
- byte outPutBuf[] = new byte[5];
- byte byteArray[] = {1, 3, 4, 7, 8};
-
- Deflater defl = new Deflater();
- defl.setInput(byteArray);
- defl.finish();
- while (!defl.finished()) {
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#getTotalIn()
+ */
+ public void test_getTotalIn() {
+ byte outPutBuf[] = new byte[5];
+ byte byteArray[] = { 1, 3, 4, 7, 8 };
+
+ Deflater defl = new Deflater();
+ defl.setInput(byteArray);
+ defl.finish();
+ while (!defl.finished()) {
defl.deflate(outPutBuf);
}
assertEquals(byteArray.length, defl.getTotalIn());
- defl.end();
-
- defl = new Deflater();
- int offSet = 2;
- int length = 3;
- outPutBuf = new byte[5];
- defl.setInput(byteArray, offSet, length);
- defl.finish();
- while (!defl.finished()) {
+ defl.end();
+
+ defl = new Deflater();
+ int offSet = 2;
+ int length = 3;
+ outPutBuf = new byte[5];
+ defl.setInput(byteArray, offSet, length);
+ defl.finish();
+ while (!defl.finished()) {
defl.deflate(outPutBuf);
}
assertEquals(length, defl.getTotalIn());
- defl.end();
- }
-
- /**
- * @tests java.util.zip.Deflater#getTotalOut()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTotalOut",
- args = {}
- )
- public void test_getTotalOut() {
- // the getTotalOut should equal the sum of value returned by deflate()
- byte outPutBuf[] = new byte[5];
- byte byteArray[] = {5, 2, 3, 7, 8};
- int x = 0;
- Deflater defl = new Deflater();
- defl.setInput(byteArray);
- defl.finish();
- while (!defl.finished()) {
+ defl.end();
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#getTotalOut()
+ */
+ public void test_getTotalOut() {
+ // the getTotalOut should equal the sum of value returned by deflate()
+ byte outPutBuf[] = new byte[5];
+ byte byteArray[] = { 5, 2, 3, 7, 8 };
+ int x = 0;
+ Deflater defl = new Deflater();
+ defl.setInput(byteArray);
+ defl.finish();
+ while (!defl.finished()) {
x += defl.deflate(outPutBuf);
}
assertEquals(x, defl.getTotalOut());
- defl.end();
-
- x = 0;
- int offSet = 2;
- int length = 3;
- defl = new Deflater();
- outPutBuf = new byte[5];
- defl.setInput(byteArray, offSet, length);
- defl.finish();
- while (!defl.finished()) {
+ defl.end();
+
+ x = 0;
+ int offSet = 2;
+ int length = 3;
+ defl = new Deflater();
+ outPutBuf = new byte[5];
+ defl.setInput(byteArray, offSet, length);
+ defl.finish();
+ while (!defl.finished()) {
x += defl.deflate(outPutBuf);
}
assertEquals(x, defl.getTotalOut());
- }
-
- /**
- * @tests java.util.zip.Deflater#needsInput()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "needsInput",
- args = {}
- )
- public void test_needsInput() {
- Deflater defl = new Deflater();
- assertTrue(
- "needsInput give the wrong boolean value as a result of no input buffer",
- defl.needsInput());
- byte byteArray[] = {1, 2, 3};
- defl.setInput(byteArray);
- assertFalse(
- "needsInput give wrong boolean value as a result of a full input buffer",
- defl.needsInput());
- byte[] outPutBuf = new byte[50];
- while (!defl.needsInput()) {
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#needsInput()
+ */
+ public void test_needsInput() {
+ Deflater defl = new Deflater();
+ assertTrue(
+ "needsInput give the wrong boolean value as a result of no input buffer",
+ defl.needsInput());
+ byte byteArray[] = { 1, 2, 3 };
+ defl.setInput(byteArray);
+ assertFalse(
+ "needsInput give wrong boolean value as a result of a full input buffer",
+ defl.needsInput());
+ byte[] outPutBuf = new byte[50];
+ while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
- byte emptyByteArray[] = new byte[0];
- defl.setInput(emptyByteArray);
- assertTrue(
- "needsInput give wrong boolean value as a result of an empty input buffer",
- defl.needsInput());
- defl.setInput(byteArray);
- defl.finish();
- while (!defl.finished()) {
+ byte emptyByteArray[] = new byte[0];
+ defl.setInput(emptyByteArray);
+ assertTrue(
+ "needsInput give wrong boolean value as a result of an empty input buffer",
+ defl.needsInput());
+ defl.setInput(byteArray);
+ defl.finish();
+ while (!defl.finished()) {
defl.deflate(outPutBuf);
}
- // needsInput should NOT return true after finish() has been
- // called.
- if (System.getProperty("java.vendor").startsWith("IBM")) {
+ // needsInput should NOT return true after finish() has been
+ // called.
+ if (System.getProperty("java.vendor").startsWith("IBM")) {
assertFalse(
- "needsInput gave wrong boolean value as a result of finish() being called",
- defl.needsInput());
- }
- defl.end();
- }
-
- /**
- * @tests java.util.zip.Deflater#reset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reset",
- args = {}
- )
- public void test_reset() {
- byte outPutBuf[] = new byte[100];
- byte outPutInf[] = new byte[100];
- byte curArray[] = new byte[5];
- byte byteArray[] = {1, 3, 4, 7, 8};
- byte byteArray2[] = {8, 7, 4, 3, 1};
- int x = 0;
- int orgValue = 0;
- Deflater defl = new Deflater();
-
- for (int i = 0; i < 3; i++) {
- if (i == 0) {
+ "needsInput gave wrong boolean value as a result of finish() being called",
+ defl.needsInput());
+ }
+ defl.end();
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#reset()
+ */
+ public void test_reset() {
+ byte outPutBuf[] = new byte[100];
+ byte outPutInf[] = new byte[100];
+ byte curArray[] = new byte[5];
+ byte byteArray[] = { 1, 3, 4, 7, 8 };
+ byte byteArray2[] = { 8, 7, 4, 3, 1 };
+ int x = 0;
+ int orgValue = 0;
+ Deflater defl = new Deflater();
+
+ for (int i = 0; i < 3; i++) {
+ if (i == 0) {
curArray = byteArray;
} else if (i == 1) {
curArray = byteArray2;
@@ -481,13 +404,13 @@ public class DeflaterTest extends TestCase {
defl.reset();
}
- defl.setInput(curArray);
- defl.finish();
- while (!defl.finished()) {
+ defl.setInput(curArray);
+ defl.finish();
+ while (!defl.finished()) {
x += defl.deflate(outPutBuf);
}
- if (i == 0) {
+ if (i == 0) {
assertEquals(x, defl.getTotalOut());
} else if (i == 1) {
assertEquals(x, orgValue);
@@ -495,333 +418,296 @@ public class DeflaterTest extends TestCase {
assertEquals(x, orgValue * 2);
}
- if (i == 0) {
+ if (i == 0) {
orgValue = x;
}
- try {
- Inflater infl = new Inflater();
- infl.setInput(outPutBuf);
- while (!infl.finished()) {
+ try {
+ Inflater infl = new Inflater();
+ infl.setInput(outPutBuf);
+ while (!infl.finished()) {
infl.inflate(outPutInf);
}
- infl.end();
- } catch (DataFormatException e) {
- fail("Test " + i + ": Invalid input to be decompressed");
- }
+ infl.end();
+ } catch (DataFormatException e) {
+ fail("Test " + i + ": Invalid input to be decompressed");
+ }
- if (i == 1) {
+ if (i == 1) {
curArray = byteArray;
}
- for (int j = 0; j < curArray.length; j++) {
+ for (int j = 0; j < curArray.length; j++) {
assertEquals(curArray[j], outPutInf[j]);
}
assertEquals(0, outPutInf[curArray.length]);
- }
- }
-
- /**
- * @tests java.util.zip.Deflater#setDictionary(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setDictionary",
- args = {byte[].class}
- )
- public void test_setDictionary$B() {
- // This test is very close to getAdler()
- byte dictionaryArray[] = {'e', 'r', 't', 'a', 'b', 2, 3};
- byte byteArray[] = {
- 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3', 'w', 'r'};
- byte outPutBuf[] = new byte[100];
-
- Deflater defl = new Deflater();
- long deflAdler = defl.getAdler();
- assertEquals(
- "No dictionary set, no data deflated, getAdler should return 1",
- 1, deflAdler);
- defl.setDictionary(dictionaryArray);
- deflAdler = defl.getAdler();
-
- // getting the checkSum value through the Adler32 class
- Adler32 adl = new Adler32();
- adl.update(dictionaryArray);
- long realAdler = adl.getValue();
+ }
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#setDictionary(byte[])
+ */
+ public void test_setDictionary$B() {
+ // This test is very close to getAdler()
+ byte dictionaryArray[] = { 'e', 'r', 't', 'a', 'b', 2, 3 };
+ byte byteArray[] = { 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3',
+ 'w', 'r' };
+ byte outPutBuf[] = new byte[100];
+
+ Deflater defl = new Deflater();
+ long deflAdler = defl.getAdler();
+ assertEquals("No dictionary set, no data deflated, getAdler should return 1",
+ 1, deflAdler);
+ defl.setDictionary(dictionaryArray);
+ deflAdler = defl.getAdler();
+
+ // getting the checkSum value through the Adler32 class
+ Adler32 adl = new Adler32();
+ adl.update(dictionaryArray);
+ long realAdler = adl.getValue();
assertEquals(deflAdler, realAdler);
- defl.setInput(byteArray);
- defl.finish();
- while (!defl.finished()) {
+ defl.setInput(byteArray);
+ defl.finish();
+ while (!defl.finished()) {
defl.deflate(outPutBuf);
}
- deflAdler = defl.getAdler();
- adl = new Adler32();
- adl.update(byteArray);
- realAdler = adl.getValue();
- // Deflate is finished and there were bytes deflated that did not occur
- // in the dictionaryArray, therefore a new dictionary was automatically
- // set.
+ deflAdler = defl.getAdler();
+ adl = new Adler32();
+ adl.update(byteArray);
+ realAdler = adl.getValue();
+ // Deflate is finished and there were bytes deflated that did not occur
+ // in the dictionaryArray, therefore a new dictionary was automatically
+ // set.
assertEquals(realAdler, deflAdler);
- defl.end();
- }
-
- /**
- * @tests java.util.zip.Deflater#setDictionary(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setDictionary",
- args = {byte[].class, int.class, int.class}
- )
- public void test_setDictionary$BII() {
- // This test is very close to getAdler()
- byte dictionaryArray[] = {'e', 'r', 't', 'a', 'b', 2, 3, 'o', 't'};
- byte byteArray[] = {
- 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3', 'w', 'r', 't',
- 'u', 'i', 'o', 4, 5, 6, 7};
- byte outPutBuf[] = new byte[500];
-
- int offSet = 4;
- int length = 5;
-
- Deflater defl = new Deflater();
- long deflAdler = defl.getAdler();
- assertEquals(
- "No dictionary set, no data deflated, getAdler should return 1",
- 1, deflAdler);
- defl.setDictionary(dictionaryArray, offSet, length);
- deflAdler = defl.getAdler();
-
- // getting the checkSum value through the Adler32 class
- Adler32 adl = new Adler32();
- adl.update(dictionaryArray, offSet, length);
- long realAdler = adl.getValue();
+ defl.end();
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#setDictionary(byte[], int, int)
+ */
+ public void test_setDictionary$BII() {
+ // This test is very close to getAdler()
+ byte dictionaryArray[] = { 'e', 'r', 't', 'a', 'b', 2, 3, 'o', 't' };
+ byte byteArray[] = { 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3',
+ 'w', 'r', 't', 'u', 'i', 'o', 4, 5, 6, 7 };
+ byte outPutBuf[] = new byte[500];
+
+ int offSet = 4;
+ int length = 5;
+
+ Deflater defl = new Deflater();
+ long deflAdler = defl.getAdler();
+ assertEquals("No dictionary set, no data deflated, getAdler should return 1",
+ 1, deflAdler);
+ defl.setDictionary(dictionaryArray, offSet, length);
+ deflAdler = defl.getAdler();
+
+ // getting the checkSum value through the Adler32 class
+ Adler32 adl = new Adler32();
+ adl.update(dictionaryArray, offSet, length);
+ long realAdler = adl.getValue();
assertEquals(deflAdler, realAdler);
- defl.setInput(byteArray);
- while (!defl.needsInput()) {
+ defl.setInput(byteArray);
+ while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
- deflAdler = defl.getAdler();
- adl = new Adler32();
- adl.update(byteArray);
- realAdler = adl.getValue();
- // Deflate is finished and there were bytes deflated that did not occur
- // in the dictionaryArray, therefore a new dictionary was automatically
- // set.
+ deflAdler = defl.getAdler();
+ adl = new Adler32();
+ adl.update(byteArray);
+ realAdler = adl.getValue();
+ // Deflate is finished and there were bytes deflated that did not occur
+ // in the dictionaryArray, therefore a new dictionary was automatically
+ // set.
assertEquals(realAdler, deflAdler);
- defl.end();
-
- // boundary check
- defl = new Deflater();
- for (int i = 0; i < 2; i++) {
- if (i == 0) {
- offSet = 0;
- length = dictionaryArray.length + 1;
- } else {
- offSet = dictionaryArray.length + 1;
- length = 1;
- }
- try {
- defl.setDictionary(dictionaryArray, offSet, length);
- fail("Test "
- + i
- + ": boundary check for setDictionary failed for offset "
- + offSet + " and length " + length);
- } catch (ArrayIndexOutOfBoundsException e) {
- }
- }
- }
-
- /**
- * @tests java.util.zip.Deflater#setInput(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setInput",
- args = {byte[].class}
- )
- public void test_setInput$B() {
- byte[] byteArray = {1, 2, 3};
- byte[] outPutBuf = new byte[50];
- byte[] outPutInf = new byte[50];
-
- Deflater defl = new Deflater();
- defl.setInput(byteArray);
- assertTrue("the array buffer in setInput() is empty", !defl
- .needsInput());
- // The second setInput() should be ignored since needsInput() return
- // false
- defl.setInput(byteArray);
- defl.finish();
- while (!defl.finished()) {
+ defl.end();
+
+ // boundary check
+ defl = new Deflater();
+ for (int i = 0; i < 2; i++) {
+ if (i == 0) {
+ offSet = 0;
+ length = dictionaryArray.length + 1;
+ } else {
+ offSet = dictionaryArray.length + 1;
+ length = 1;
+ }
+ try {
+ defl.setDictionary(dictionaryArray, offSet, length);
+ fail(
+ "Test "
+ + i
+ + ": boundary check for setDictionary failed for offset "
+ + offSet + " and length " + length);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ }
+ }
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#setInput(byte[])
+ */
+ public void test_setInput$B() {
+ byte[] byteArray = { 1, 2, 3 };
+ byte[] outPutBuf = new byte[50];
+ byte[] outPutInf = new byte[50];
+
+ Deflater defl = new Deflater();
+ defl.setInput(byteArray);
+ assertTrue("the array buffer in setInput() is empty", !defl
+ .needsInput());
+ // The second setInput() should be ignored since needsInput() return
+ // false
+ defl.setInput(byteArray);
+ defl.finish();
+ while (!defl.finished()) {
defl.deflate(outPutBuf);
}
- defl.end();
+ defl.end();
- Inflater infl = new Inflater();
- try {
- infl.setInput(outPutBuf);
- while (!infl.finished()) {
+ Inflater infl = new Inflater();
+ try {
+ infl.setInput(outPutBuf);
+ while (!infl.finished()) {
infl.inflate(outPutInf);
}
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- }
- for (int i = 0; i < byteArray.length; i++) {
+ } catch (DataFormatException e) {
+ fail("Invalid input to be decompressed");
+ }
+ for (int i = 0; i < byteArray.length; i++) {
assertEquals(byteArray[i], outPutInf[i]);
}
- assertEquals(byteArray.length, infl.getTotalOut());
- infl.end();
- }
-
- /**
- * @tests java.util.zip.Deflater#setInput(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setInput",
- args = {byte[].class, int.class, int.class}
- )
- public void test_setInput$BII() throws Exception {
- byte[] byteArray = {1, 2, 3, 4, 5};
- byte[] outPutBuf = new byte[50];
- byte[] outPutInf = new byte[50];
- int offSet = 1;
- int length = 3;
-
- Deflater defl = new Deflater();
- defl.setInput(byteArray, offSet, length);
- assertFalse("the array buffer in setInput() is empty", defl
- .needsInput());
- // The second setInput() should be ignored since needsInput() return
- // false
- defl.setInput(byteArray, offSet, length);
- defl.finish();
- while (!defl.finished()) {
+ assertEquals(byteArray.length, infl.getTotalOut());
+ infl.end();
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#setInput(byte[], int, int)
+ */
+ public void test_setInput$BII() throws Exception {
+ byte[] byteArray = { 1, 2, 3, 4, 5 };
+ byte[] outPutBuf = new byte[50];
+ byte[] outPutInf = new byte[50];
+ int offSet = 1;
+ int length = 3;
+
+ Deflater defl = new Deflater();
+ defl.setInput(byteArray, offSet, length);
+ assertFalse("the array buffer in setInput() is empty", defl.needsInput());
+ // The second setInput() should be ignored since needsInput() return
+ // false
+ defl.setInput(byteArray, offSet, length);
+ defl.finish();
+ while (!defl.finished()) {
defl.deflate(outPutBuf);
}
- defl.end();
+ defl.end();
- Inflater infl = new Inflater();
- infl.setInput(outPutBuf);
- while (!infl.finished()) {
- infl.inflate(outPutInf);
- }
- for (int i = 0; i < length; i++) {
+ Inflater infl = new Inflater();
+ infl.setInput(outPutBuf);
+ while (!infl.finished()) {
+ infl.inflate(outPutInf);
+ }
+ for (int i = 0; i < length; i++) {
assertEquals(byteArray[i + offSet], outPutInf[i]);
}
- assertEquals(length, infl.getTotalOut());
- infl.end();
-
- // boundary check
- defl = new Deflater();
- for (int i = 0; i < 2; i++) {
- if (i == 0) {
- offSet = 0;
- length = byteArray.length + 1;
- } else {
- offSet = byteArray.length + 1;
- length = 1;
- }
- try {
- defl.setInput(byteArray, offSet, length);
- fail("Test " + i
- + ": boundary check for setInput failed for offset "
- + offSet + " and length " + length);
- } catch (ArrayIndexOutOfBoundsException e) {
- }
- }
- }
-
- /**
- * @tests java.util.zip.Deflater#setLevel(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setLevel",
- args = {int.class}
- )
- public void test_setLevelI() throws Exception {
- // Very similar to test_Constructor(int)
- byte[] byteArray = new byte[100];
- InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt");
- inFile.read(byteArray);
- inFile.close();
-
- byte[] outPutBuf;
- int totalOut;
- for (int i = 0; i < 10; i++) {
- Deflater defl = new Deflater();
- defl.setLevel(i);
- outPutBuf = new byte[500];
- defl.setInput(byteArray);
- while (!defl.needsInput()) {
+ assertEquals(length, infl.getTotalOut());
+ infl.end();
+
+ // boundary check
+ defl = new Deflater();
+ for (int i = 0; i < 2; i++) {
+ if (i == 0) {
+ offSet = 0;
+ length = byteArray.length + 1;
+ } else {
+ offSet = byteArray.length + 1;
+ length = 1;
+ }
+ try {
+ defl.setInput(byteArray, offSet, length);
+ fail("Test " + i
+ + ": boundary check for setInput failed for offset "
+ + offSet + " and length " + length);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ }
+ }
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#setLevel(int)
+ */
+ public void test_setLevelI() throws Exception {
+ // Very similar to test_Constructor(int)
+ byte[] byteArray = new byte[100];
+ InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt");
+ inFile.read(byteArray);
+ inFile.close();
+
+ byte[] outPutBuf;
+ int totalOut;
+ for (int i = 0; i < 10; i++) {
+ Deflater defl = new Deflater();
+ defl.setLevel(i);
+ outPutBuf = new byte[500];
+ defl.setInput(byteArray);
+ while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
- defl.finish();
- while (!defl.finished()) {
+ defl.finish();
+ while (!defl.finished()) {
defl.deflate(outPutBuf);
}
- totalOut = defl.getTotalOut();
- defl.end();
+ totalOut = defl.getTotalOut();
+ defl.end();
- outPutBuf = new byte[500];
- defl = new Deflater(i);
- defl.setInput(byteArray);
- while (!defl.needsInput()) {
+ outPutBuf = new byte[500];
+ defl = new Deflater(i);
+ defl.setInput(byteArray);
+ while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
- defl.finish();
- while (!defl.finished()) {
+ defl.finish();
+ while (!defl.finished()) {
defl.deflate(outPutBuf);
}
- assertEquals(totalOut, defl.getTotalOut());
- defl.end();
- }
-
- // testing boundaries
- try {
- Deflater boundDefl = new Deflater();
- // Level must be between 0-9
- boundDefl.setLevel(-2);
- fail("IllegalArgumentException not thrown when setting level to a number < 0.");
- } catch (IllegalArgumentException e) {
- }
- try {
- Deflater boundDefl = new Deflater();
- boundDefl.setLevel(10);
- fail("IllegalArgumentException not thrown when setting level to a number > 9.");
- } catch (IllegalArgumentException e) {
- }
- }
-
- /**
- * @tests java.util.zip.Deflater#setStrategy(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setStrategy",
- args = {int.class}
- )
- public void test_setStrategyI() throws Exception {
- byte[] byteArray = new byte[100];
- InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt");
- inFile.read(byteArray);
- inFile.close();
-
- for (int i = 0; i < 3; i++) {
- byte outPutBuf[] = new byte[500];
- MyDeflater mdefl = new MyDeflater();
-
- if (i == 0) {
+ assertEquals(totalOut, defl.getTotalOut());
+ defl.end();
+ }
+
+ // testing boundaries
+ try {
+ Deflater boundDefl = new Deflater();
+ // Level must be between 0-9
+ boundDefl.setLevel(-2);
+ fail(
+ "IllegalArgumentException not thrown when setting level to a number < 0.");
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ Deflater boundDefl = new Deflater();
+ boundDefl.setLevel(10);
+ fail(
+ "IllegalArgumentException not thrown when setting level to a number > 9.");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#setStrategy(int)
+ */
+ public void test_setStrategyI() throws Exception {
+ byte[] byteArray = new byte[100];
+ InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt");
+ inFile.read(byteArray);
+ inFile.close();
+
+ for (int i = 0; i < 3; i++) {
+ byte outPutBuf[] = new byte[500];
+ MyDeflater mdefl = new MyDeflater();
+
+ if (i == 0) {
mdefl.setStrategy(mdefl.getDefStrategy());
} else if (i == 1) {
mdefl.setStrategy(mdefl.getHuffman());
@@ -829,335 +715,325 @@ public class DeflaterTest extends TestCase {
mdefl.setStrategy(mdefl.getFiltered());
}
- mdefl.setInput(byteArray);
- while (!mdefl.needsInput()) {
+ mdefl.setInput(byteArray);
+ while (!mdefl.needsInput()) {
mdefl.deflate(outPutBuf);
}
- mdefl.finish();
- while (!mdefl.finished()) {
+ mdefl.finish();
+ while (!mdefl.finished()) {
mdefl.deflate(outPutBuf);
}
- if (i == 0) {
- // System.out.println(mdefl.getTotalOut());
- // ran JDK and found that getTotalOut() = 86 for this particular
- // file
- assertEquals(
- "getTotalOut() for the default strategy did not correspond with JDK",
- 86, mdefl.getTotalOut());
- } else if (i == 1) {
- // System.out.println(mdefl.getTotalOut());
- // ran JDK and found that getTotalOut() = 100 for this
- // particular file
- assertEquals(
- "getTotalOut() for the Huffman strategy did not correspond with JDK",
- 100, mdefl.getTotalOut());
- } else {
- // System.out.println(mdefl.getTotalOut());
- // ran JDK and found that totalOut = 93 for this particular file
- assertEquals(
- "Total Out for the Filtered strategy did not correspond with JDK",
- 93, mdefl.getTotalOut());
- }
- mdefl.end();
- }
-
- // Attempting to setStrategy to an invalid value
- try {
- Deflater defl = new Deflater();
- defl.setStrategy(-412);
- fail("IllegalArgumentException not thrown when setting strategy to an invalid value.");
- } catch (IllegalArgumentException e) {
- }
- }
-
- /**
- * @tests java.util.zip.Deflater#Deflater()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Deflater",
- args = {}
- )
- public void test_Constructor() throws Exception {
- byte[] byteArray = new byte[100];
- InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt");
- inFile.read(byteArray);
- inFile.close();
-
- Deflater defl = new Deflater();
- byte[] outPutBuf = new byte[500];
- defl.setInput(byteArray);
- while (!defl.needsInput()) {
+ if (i == 0) {
+ // System.out.println(mdefl.getTotalOut());
+ // ran JDK and found that getTotalOut() = 86 for this particular
+ // file
+ assertEquals("getTotalOut() for the default strategy did not correspond with JDK",
+ 86, mdefl.getTotalOut());
+ } else if (i == 1) {
+ // System.out.println(mdefl.getTotalOut());
+ // ran JDK and found that getTotalOut() = 100 for this
+ // particular file
+ assertEquals("getTotalOut() for the Huffman strategy did not correspond with JDK",
+ 100, mdefl.getTotalOut());
+ } else {
+ // System.out.println(mdefl.getTotalOut());
+ // ran JDK and found that totalOut = 93 for this particular file
+ assertEquals("Total Out for the Filtered strategy did not correspond with JDK",
+ 93, mdefl.getTotalOut());
+ }
+ mdefl.end();
+ }
+
+ // Attempting to setStrategy to an invalid value
+ try {
+ Deflater defl = new Deflater();
+ defl.setStrategy(-412);
+ fail(
+ "IllegalArgumentException not thrown when setting strategy to an invalid value.");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#Deflater()
+ */
+ public void test_Constructor() throws Exception {
+ byte[] byteArray = new byte[100];
+ InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt");
+ inFile.read(byteArray);
+ inFile.close();
+
+ Deflater defl = new Deflater();
+ byte[] outPutBuf = new byte[500];
+ defl.setInput(byteArray);
+ while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
- defl.finish();
- while (!defl.finished()) {
+ defl.finish();
+ while (!defl.finished()) {
defl.deflate(outPutBuf);
}
- int totalOut = defl.getTotalOut();
- defl.end();
-
- // creating a Deflater using the DEFAULT_COMPRESSION as the int
- MyDeflater mdefl = new MyDeflater();
- mdefl = new MyDeflater(mdefl.getDefCompression());
- outPutBuf = new byte[500];
- mdefl.setInput(byteArray);
- while (!mdefl.needsInput()) {
+ int totalOut = defl.getTotalOut();
+ defl.end();
+
+ // creating a Deflater using the DEFAULT_COMPRESSION as the int
+ MyDeflater mdefl = new MyDeflater();
+ mdefl = new MyDeflater(mdefl.getDefCompression());
+ outPutBuf = new byte[500];
+ mdefl.setInput(byteArray);
+ while (!mdefl.needsInput()) {
mdefl.deflate(outPutBuf);
}
- mdefl.finish();
- while (!mdefl.finished()) {
+ mdefl.finish();
+ while (!mdefl.finished()) {
mdefl.deflate(outPutBuf);
}
- assertEquals(totalOut, mdefl.getTotalOut());
- mdefl.end();
- }
-
- /**
- * @tests java.util.zip.Deflater#Deflater(int, boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Deflater",
- args = {int.class, boolean.class}
- )
- public void test_ConstructorIZ() throws Exception {
- byte byteArray[] = {
- 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3', 'w', 'r'};
-
- Deflater defl = new Deflater();
- byte outPutBuf[] = new byte[500];
- defl.setLevel(2);
- defl.setInput(byteArray);
- while (!defl.needsInput()) {
+ assertEquals(totalOut, mdefl.getTotalOut());
+ mdefl.end();
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#Deflater(int, boolean)
+ */
+ public void test_ConstructorIZ() throws Exception {
+ byte byteArray[] = { 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3',
+ 'w', 'r' };
+
+ Deflater defl = new Deflater();
+ byte outPutBuf[] = new byte[500];
+ defl.setLevel(2);
+ defl.setInput(byteArray);
+ while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
- defl.finish();
- while (!defl.finished()) {
+ defl.finish();
+ while (!defl.finished()) {
defl.deflate(outPutBuf);
}
- int totalOut = defl.getTotalOut();
- defl.end();
+ int totalOut = defl.getTotalOut();
+ defl.end();
- outPutBuf = new byte[500];
- defl = new Deflater(2, false);
- defl.setInput(byteArray);
- while (!defl.needsInput()) {
+ outPutBuf = new byte[500];
+ defl = new Deflater(2, false);
+ defl.setInput(byteArray);
+ while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
- defl.finish();
- while (!defl.finished()) {
+ defl.finish();
+ while (!defl.finished()) {
defl.deflate(outPutBuf);
}
- assertEquals(totalOut, defl.getTotalOut());
- defl.end();
+ assertEquals(totalOut, defl.getTotalOut());
+ defl.end();
- outPutBuf = new byte[500];
- defl = new Deflater(2, true);
- defl.setInput(byteArray);
- while (!defl.needsInput()) {
+ outPutBuf = new byte[500];
+ defl = new Deflater(2, true);
+ defl.setInput(byteArray);
+ while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
- defl.finish();
- while (!defl.finished()) {
+ defl.finish();
+ while (!defl.finished()) {
defl.deflate(outPutBuf);
}
- assertTrue(
- "getTotalOut() should not be equal comparing two Deflaters with different header options.",
- defl.getTotalOut() != totalOut);
- defl.end();
-
- byte outPutInf[] = new byte[500];
- Inflater infl = new Inflater(true);
- while (!infl.finished()) {
- if (infl.needsInput()) {
- infl.setInput(outPutBuf);
- }
- infl.inflate(outPutInf);
- }
- for (int i = 0; i < byteArray.length; i++) {
+ assertTrue(
+ "getTotalOut() should not be equal comparing two Deflaters with different header options.",
+ defl.getTotalOut() != totalOut);
+ defl.end();
+
+ byte outPutInf[] = new byte[500];
+ Inflater infl = new Inflater(true);
+ while (!infl.finished()) {
+ if (infl.needsInput()) {
+ infl.setInput(outPutBuf);
+ }
+ infl.inflate(outPutInf);
+ }
+ for (int i = 0; i < byteArray.length; i++) {
assertEquals(byteArray[i], outPutInf[i]);
}
- assertEquals(
- "final decompressed data contained more bytes than original - constructorIZ",
- 0, outPutInf[byteArray.length]);
- infl.end();
-
- infl = new Inflater(false);
- outPutInf = new byte[500];
- int r = 0;
- try {
- while (!infl.finished()) {
- if (infl.needsInput()) {
+ assertEquals("final decompressed data contained more bytes than original - constructorIZ",
+ 0, outPutInf[byteArray.length]);
+ infl.end();
+
+ infl = new Inflater(false);
+ outPutInf = new byte[500];
+ int r = 0;
+ try {
+ while (!infl.finished()) {
+ if (infl.needsInput()) {
infl.setInput(outPutBuf);
}
- infl.inflate(outPutInf);
- }
- } catch (DataFormatException e) {
- r = 1;
- }
- assertEquals("header option did not correspond", 1, r);
-
- // testing boundaries
- try {
- Deflater boundDefl = new Deflater();
- // Level must be between 0-9
- boundDefl.setLevel(-2);
- fail("IllegalArgumentException not thrown when setting level to a number < 0.");
- } catch (IllegalArgumentException e) {
- }
- try {
- Deflater boundDefl = new Deflater();
- boundDefl.setLevel(10);
- fail("IllegalArgumentException not thrown when setting level to a number > 9.");
- } catch (IllegalArgumentException e) {
- }
- }
-
- /**
- * @tests java.util.zip.Deflater#Deflater(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Deflater",
- args = {int.class}
- )
- public void test_ConstructorI() throws Exception {
- byte[] byteArray = new byte[100];
+ infl.inflate(outPutInf);
+ }
+ } catch (DataFormatException e) {
+ r = 1;
+ }
+ assertEquals("header option did not correspond", 1, r);
+
+ // testing boundaries
+ try {
+ Deflater boundDefl = new Deflater();
+ // Level must be between 0-9
+ boundDefl.setLevel(-2);
+ fail("IllegalArgumentException not thrown when setting level to a number < 0.");
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ Deflater boundDefl = new Deflater();
+ boundDefl.setLevel(10);
+ fail("IllegalArgumentException not thrown when setting level to a number > 9.");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * @tests java.util.zip.Deflater#Deflater(int)
+ */
+ public void test_ConstructorI() throws Exception {
+ byte[] byteArray = new byte[100];
InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt");
inFile.read(byteArray);
inFile.close();
- byte outPutBuf[] = new byte[500];
- Deflater defl = new Deflater(3);
- defl.setInput(byteArray);
- while (!defl.needsInput()) {
+ byte outPutBuf[] = new byte[500];
+ Deflater defl = new Deflater(3);
+ defl.setInput(byteArray);
+ while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
- defl.finish();
- while (!defl.finished()) {
+ defl.finish();
+ while (!defl.finished()) {
defl.deflate(outPutBuf);
}
- int totalOut = defl.getTotalOut();
- defl.end();
-
- // test to see if the compression ratio is the same as setting the level
- // on a deflater
- outPutBuf = new byte[500];
- defl = new Deflater();
- defl.setLevel(3);
- defl.setInput(byteArray);
- while (!defl.needsInput()) {
+ int totalOut = defl.getTotalOut();
+ defl.end();
+
+ // test to see if the compression ratio is the same as setting the level
+ // on a deflater
+ outPutBuf = new byte[500];
+ defl = new Deflater();
+ defl.setLevel(3);
+ defl.setInput(byteArray);
+ while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
- defl.finish();
- while (!defl.finished()) {
+ defl.finish();
+ while (!defl.finished()) {
defl.deflate(outPutBuf);
}
- assertEquals(totalOut, defl.getTotalOut());
- defl.end();
+ assertEquals(totalOut, defl.getTotalOut());
+ defl.end();
- // testing boundaries
- try {
+ // testing boundaries
+ try {
Deflater boundDefl = new Deflater();
// Level must be between 0-9
boundDefl.setLevel(-2);
fail("IllegalArgumentException not thrown when setting level to a number < 0.");
} catch (IllegalArgumentException e) {
- }
- try {
+ }
+ try {
Deflater boundDefl = new Deflater();
boundDefl.setLevel(10);
fail("IllegalArgumentException not thrown when setting level to a number > 9.");
} catch (IllegalArgumentException e) {
}
- }
+ }
+
+ private void helper_end_test(Deflater defl, String desc) {
+ // Help tests for test_end() and test_reset().
+ byte byteArray[] = { 5, 2, 3, 7, 8 };
+
+ // Methods where we expect IllegalStateException or NullPointerException
+ // to be thrown
+ try {
+ defl.getTotalOut();
+ fail("defl.getTotalOut() can still be used after " + desc
+ + " is called in test_" + desc);
+ } catch (IllegalStateException e) {
+ } catch (NullPointerException e) {
+ }
+ try {
+ defl.getTotalIn();
+ fail("defl.getTotalIn() can still be used after " + desc
+ + " is called in test_" + desc);
+ } catch (IllegalStateException e) {
+ } catch (NullPointerException e) {
+ }
+ try {
+ defl.getAdler();
+ fail("defl.getAdler() can still be used after " + desc
+ + " is called in test_" + desc);
+ } catch (IllegalStateException e) {
+ } catch (NullPointerException e) {
+ }
+ try {
+ byte[] dict = { 'a', 'b', 'c' };
+ defl.setDictionary(dict);
+ fail("defl.setDictionary() can still be used after " + desc
+ + " is called in test_" + desc);
+ } catch (IllegalStateException e) {
+ } catch (NullPointerException e) {
+ }
+ try {
+ defl.getTotalIn();
+ fail("defl.getTotalIn() can still be used after " + desc
+ + " is called in test_" + desc);
+ } catch (IllegalStateException e) {
+ } catch (NullPointerException e) {
+ }
+ try {
+ defl.getTotalIn();
+ fail("defl.getTotalIn() can still be used after " + desc
+ + " is called in test_" + desc);
+ } catch (IllegalStateException e) {
+ } catch (NullPointerException e) {
+ }
+ try {
+ defl.deflate(byteArray);
+ fail("defl.deflate() can still be used after " + desc
+ + " is called in test_" + desc);
+ } catch (IllegalStateException e) {
+ } catch (NullPointerException e) {
+ }
+
+ // Methods where we expect NullPointerException to be thrown
+ try {
+ defl.reset();
+ fail("defl.reset() can still be used after " + desc
+ + " is called in test_" + desc);
+ } catch (NullPointerException e) {
+ }
+
+ // Methods that should be allowed to be called after end() is called
+ defl.needsInput();
+ defl.setStrategy(1);
+ defl.setLevel(1);
+ defl.end();
+
+ // Methods where exceptions should be thrown
+ String vendor = System.getProperty("java.vendor");
+ if (vendor.indexOf("IBM") != -1) {
+ try {
+ defl.setInput(byteArray);
+ fail("defl.setInput() can still be used after " + desc
+ + " is called in test_" + desc);
+ } catch (IllegalStateException e) {
+ }
+ }
+ }
- private void helper_end_test(Deflater defl, String desc) {
- // Help tests for test_end() and test_reset().
- byte byteArray[] = {5, 2, 3, 7, 8};
-
- // Methods where we expect IllegalStateException or NullPointerException
- // to be thrown
- try {
- defl.getTotalOut();
- fail("defl.getTotalOut() can still be used after " + desc
- + " is called in test_" + desc);
- } catch (IllegalStateException e) {
- } catch (NullPointerException e) {
- }
- try {
- defl.getTotalIn();
- fail("defl.getTotalIn() can still be used after " + desc
- + " is called in test_" + desc);
- } catch (IllegalStateException e) {
- } catch (NullPointerException e) {
- }
- try {
- defl.getAdler();
- fail("defl.getAdler() can still be used after " + desc
- + " is called in test_" + desc);
- } catch (IllegalStateException e) {
- } catch (NullPointerException e) {
- }
- try {
- byte[] dict = {'a', 'b', 'c'};
- defl.setDictionary(dict);
- fail("defl.setDictionary() can still be used after " + desc
- + " is called in test_" + desc);
- } catch (IllegalStateException e) {
- } catch (NullPointerException e) {
- }
- try {
- defl.getTotalIn();
- fail("defl.getTotalIn() can still be used after " + desc
- + " is called in test_" + desc);
- } catch (IllegalStateException e) {
- } catch (NullPointerException e) {
- }
- try {
- defl.getTotalIn();
- fail("defl.getTotalIn() can still be used after " + desc
- + " is called in test_" + desc);
- } catch (IllegalStateException e) {
- } catch (NullPointerException e) {
- }
- try {
- defl.deflate(byteArray);
- fail("defl.deflate() can still be used after " + desc
- + " is called in test_" + desc);
- } catch (IllegalStateException e) {
- } catch (NullPointerException e) {
- }
-
- // Methods where we expect NullPointerException to be thrown
- try {
- defl.reset();
- fail("defl.reset() can still be used after " + desc
- + " is called in test_" + desc);
- } catch (NullPointerException e) {
- }
-
- // Methods that should be allowed to be called after end() is called
- defl.needsInput();
- defl.setStrategy(1);
- defl.setLevel(1);
- defl.end();
-
- // Methods where exceptions should be thrown
- String vendor = System.getProperty("java.vendor");
- if (vendor.indexOf("IBM") != -1) {
- try {
- defl.setInput(byteArray);
- fail("defl.setInput() can still be used after " + desc
- + " is called in test_" + desc);
- } catch (IllegalStateException e) {
- }
- }
+ /**
+ * @tests java.util.zip.Deflater()
+ */
+ public void test_needsDictionary() {
+ Deflater inf = new Deflater();
+ assertEquals(0, inf.getTotalIn());
+ assertEquals(0, inf.getTotalOut());
+ assertEquals(0, inf.getBytesRead());
+ assertEquals(0, inf.getBytesWritten());
}
/**
@@ -1165,12 +1041,6 @@ public class DeflaterTest extends TestCase {
* @throws UnsupportedEncodingException
* @tests java.util.zip.Deflater#getBytesRead()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBytesRead",
- args = {}
- )
public void test_getBytesRead() throws DataFormatException,
UnsupportedEncodingException {
// Regression test for HARMONY-158
@@ -1197,12 +1067,6 @@ public class DeflaterTest extends TestCase {
* @throws UnsupportedEncodingException
* @tests java.util.zip.Deflater#getBytesRead()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBytesWritten",
- args = {}
- )
public void test_getBytesWritten() throws DataFormatException,
UnsupportedEncodingException {
// Regression test for HARMONY-158
@@ -1223,21 +1087,16 @@ public class DeflaterTest extends TestCase {
assertEquals(compressedDataLength, def.getTotalOut());
assertEquals(compressedDataLength, def.getBytesWritten());
}
-
- // BEGIN android-removed
- // We use different default settings for deflating, so our output won't be
- // the
- // same.
- // //Regression Test for HARMONY-2481
- // public void test_deflate_beforeSetInput() throws Exception {
- // Deflater deflater = new Deflater();
- // deflater.finish();
- // byte[] buffer = new byte[1024];
- // assertEquals(8, deflater.deflate(buffer));
- // byte[] expectedBytes = { 120, -100, 3, 0, 0, 0, 0, 1 };
- // for (int i = 0; i < expectedBytes.length; i++) {
- // assertEquals(expectedBytes[i], buffer[i]);
- // }
- // }
- // END android-removed
+
+ //Regression Test for HARMONY-2481
+ public void test_deflate_beforeSetInput() throws Exception {
+ Deflater deflater = new Deflater();
+ deflater.finish();
+ byte[] buffer = new byte[1024];
+ assertEquals(8, deflater.deflate(buffer));
+ byte[] expectedBytes = { 120, -100, 3, 0, 0, 0, 0, 1 };
+ for (int i = 0; i < expectedBytes.length; i++) {
+ assertEquals(expectedBytes[i], buffer[i]);
+ }
+ }
}
diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPInputStreamTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPInputStreamTest.java
index 1e8ddb4..3431510 100644
--- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPInputStreamTest.java
+++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPInputStreamTest.java
@@ -14,14 +14,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.harmony.archive.tests.java.util.zip;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -31,127 +25,85 @@ import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.zip.Checksum;
-
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import tests.support.resource.Support_Resources;
-@TestTargetClass(GZIPInputStream.class)
public class GZIPInputStreamTest extends junit.framework.TestCase {
- File resources;
+ File resources;
- class TestGZIPInputStream extends GZIPInputStream {
- TestGZIPInputStream(InputStream in) throws IOException {
- super(in);
- }
+ class TestGZIPInputStream extends GZIPInputStream {
+ TestGZIPInputStream(InputStream in) throws IOException {
+ super(in);
+ }
- TestGZIPInputStream(InputStream in, int size) throws IOException {
- super(in, size);
- }
+ TestGZIPInputStream(InputStream in, int size) throws IOException {
+ super(in, size);
+ }
- Checksum getChecksum() {
- return crc;
- }
+ Checksum getChecksum() {
+ return crc;
+ }
- boolean endofInput() {
- return eos;
- }
- }
+ boolean endofInput() {
+ return eos;
+ }
+ }
- /**
- * @tests java.util.zip.GZIPInputStream#GZIPInputStream(java.io.InputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "GZIPInputStream",
- args = {java.io.InputStream.class}
- )
- public void test_ConstructorLjava_io_InputStream() {
- // test method java.util.zip.GZIPInputStream.constructor
- try {
- Support_Resources.copyFile(resources, "GZIPInputStream",
- "hyts_gInput.txt.gz");
- final URL gInput = new File(resources.toString()
- + "/GZIPInputStream/hyts_gInput.txt.gz").toURL();
- TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput
- .openConnection().getInputStream());
- assertNotNull("the constructor for GZIPInputStream is null", inGZIP);
- assertEquals("the CRC value of the inputStream is not zero", 0,
- inGZIP.getChecksum().getValue());
- inGZIP.close();
- } catch (IOException e) {
- fail("an IO error occured while trying to open the input file");
- }
- }
+ /**
+ * @tests java.util.zip.GZIPInputStream#GZIPInputStream(java.io.InputStream)
+ */
+ public void test_ConstructorLjava_io_InputStream() {
+ // test method java.util.zip.GZIPInputStream.constructor
+ try {
+ Support_Resources.copyFile(resources, "GZIPInputStream",
+ "hyts_gInput.txt.gz");
+ final URL gInput = new File(resources.toString()
+ + "/GZIPInputStream/hyts_gInput.txt.gz").toURL();
+ TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput
+ .openConnection().getInputStream());
+ assertNotNull("the constructor for GZIPInputStream is null",
+ inGZIP);
+ assertEquals("the CRC value of the inputStream is not zero", 0, inGZIP
+ .getChecksum().getValue());
+ inGZIP.close();
+ } catch (IOException e) {
+ fail(
+ "an IO error occured while trying to open the input file");
+ }
+ }
- /**
- * @tests java.util.zip.GZIPInputStream#GZIPInputStream(java.io.InputStream,
- * int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "GZIPInputStream",
- args = {java.io.InputStream.class, int.class}
- )
- public void test_ConstructorLjava_io_InputStreamI() {
- // test method java.util.zip.GZIPInputStream.constructorI
- try {
- Support_Resources.copyFile(resources, "GZIPInputStream",
- "hyts_gInput.txt.gz");
- final URL gInput = new File(resources.toString()
- + "/GZIPInputStream/hyts_gInput.txt.gz").toURL();
- TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput
- .openConnection().getInputStream(), 200);
- assertNotNull("the constructor for GZIPInputStream is null", inGZIP);
- assertEquals("the CRC value of the inputStream is not zero", 0,
- inGZIP.getChecksum().getValue());
- inGZIP.close();
- } catch (IOException e) {
- fail("an IO error occured while trying to open the input file");
- }
- try {
- Support_Resources.copyFile(resources, "GZIPInputStream",
- "hyts_gInput.txt.gz");
- final URL gInput = new File(resources.toString()
- + "/GZIPInputStream/hyts_gInput.txt.gz").toURL();
- TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput
- .openConnection().getInputStream(), 0);
- fail("Expected IllegalArgumentException");
- } catch (IOException e) {
- fail("an IO error occured while trying to open the input file");
- } catch (IllegalArgumentException ee) {
- // expected
- }
- try {
- Support_Resources.copyFile(resources, "GZIPInputStream",
- "hyts_gInput.txt.gz");
- final URL gInput = new File(resources.toString()
- + "/GZIPInputStream/hyts_gInput.txt.gz").toURL();
- TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput
- .openConnection().getInputStream(), -1);
- fail("Expected IllegalArgumentException");
- } catch (IOException e) {
- fail("an IO error occured while trying to open the input file");
- } catch (IllegalArgumentException ee) {
- // expected
- }
- }
+ /**
+ * @tests java.util.zip.GZIPInputStream#GZIPInputStream(java.io.InputStream,
+ * int)
+ */
+ public void test_ConstructorLjava_io_InputStreamI() {
+ // test method java.util.zip.GZIPInputStream.constructorI
+ try {
+ Support_Resources.copyFile(resources, "GZIPInputStream",
+ "hyts_gInput.txt.gz");
+ final URL gInput = new File(resources.toString()
+ + "/GZIPInputStream/hyts_gInput.txt.gz").toURL();
+ TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput
+ .openConnection().getInputStream(), 200);
+ assertNotNull("the constructor for GZIPInputStream is null",
+ inGZIP);
+ assertEquals("the CRC value of the inputStream is not zero", 0, inGZIP
+ .getChecksum().getValue());
+ inGZIP.close();
+ } catch (IOException e) {
+ fail(
+ "an IO error occured while trying to open the input file");
+ }
+ }
- /**
- * @tests java.util.zip.GZIPInputStream#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 {
- // test method java.util.zip.GZIPInputStream.readBII
- byte orgBuf[] = {'3', '5', '2', 'r', 'g', 'e', 'f', 'd', 'e', 'w'};
+ /**
+ * @tests java.util.zip.GZIPInputStream#read(byte[], int, int)
+ */
+ public void test_read$BII() throws IOException {
+ // test method java.util.zip.GZIPInputStream.readBII
+ byte orgBuf[] = { '3', '5', '2', 'r', 'g', 'e', 'f', 'd', 'e', 'w' };
byte outBuf[] = new byte[100];
int result = 0;
Support_Resources.copyFile(resources, "GZIPInputStream",
@@ -240,14 +192,13 @@ public class GZIPInputStreamTest extends junit.framework.TestCase {
exception = true;
}
assertTrue("Exception expected", exception);
-
+
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream zipout = new GZIPOutputStream(baos);
zipout.write(test);
zipout.close();
outBuf = new byte[530];
- GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(baos
- .toByteArray()));
+ GZIPInputStream in= new GZIPInputStream(new ByteArrayInputStream(baos.toByteArray()));
try {
in.read(outBuf, 530, 1);
fail("Test failed IOOBE was not thrown");
@@ -256,7 +207,7 @@ public class GZIPInputStreamTest extends junit.framework.TestCase {
while (true) {
result = in.read(outBuf, 0, 5);
if (result == -1) {
- // "EOF was reached";
+ //"EOF was reached";
break;
}
}
@@ -264,64 +215,50 @@ public class GZIPInputStreamTest extends junit.framework.TestCase {
result = in.read(null, 100, 1);
result = in.read(outBuf, -100, 1);
result = in.read(outBuf, -1, 1);// 100, 1);
- }
+ }
- /**
- * @tests java.util.zip.GZIPInputStream#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "close",
- args = {}
- )
- public void test_close() {
- // test method java.util.zip.GZIPInputStream.close
- byte outBuf[] = new byte[100];
- try {
- int result = 0;
- Support_Resources.copyFile(resources, "GZIPInputStream",
- "hyts_gInput.txt.gz");
- String resPath = resources.toString();
- if (resPath.charAt(0) == '/' || resPath.charAt(0) == '\\') {
+ /**
+ * @tests java.util.zip.GZIPInputStream#close()
+ */
+ public void test_close() {
+ // test method java.util.zip.GZIPInputStream.close
+ byte outBuf[] = new byte[100];
+ try {
+ int result = 0;
+ Support_Resources.copyFile(resources, "GZIPInputStream",
+ "hyts_gInput.txt.gz");
+ String resPath = resources.toString();
+ if (resPath.charAt(0) == '/' || resPath.charAt(0) == '\\') {
resPath = resPath.substring(1);
}
- final URL gInput = new URL("file:/" + resPath
- + "/GZIPInputStream/hyts_gInput.txt.gz");
- TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput
- .openConnection().getInputStream());
- while (!(inGZIP.endofInput())) {
- result += inGZIP.read(outBuf, result, outBuf.length - result);
- }
- assertEquals(
- "the checkSum value of the compressed and decompressed data does not equal",
- 2074883667L, inGZIP.getChecksum().getValue());
- inGZIP.close();
- int r = 0;
- try {
- inGZIP.read(outBuf, 0, 1);
- } catch (IOException e) {
- r = 1;
- }
- assertEquals(
- "GZIPInputStream can still be used after close is called",
- 1, r);
- } catch (IOException e) {
- e.printStackTrace();
- fail("unexpected: " + e);
- }
- }
+ final URL gInput = new URL("file:/" + resPath
+ + "/GZIPInputStream/hyts_gInput.txt.gz");
+ TestGZIPInputStream inGZIP = new TestGZIPInputStream(gInput
+ .openConnection().getInputStream());
+ while (!(inGZIP.endofInput())) {
+ result += inGZIP.read(outBuf, result, outBuf.length - result);
+ }
+ assertEquals("the checkSum value of the compressed and decompressed data does not equal",
+ 2074883667L, inGZIP.getChecksum().getValue());
+ inGZIP.close();
+ int r = 0;
+ try {
+ inGZIP.read(outBuf, 0, 1);
+ } catch (IOException e) {
+ r = 1;
+ }
+ assertEquals("GZIPInputStream can still be used after close is called",
+ 1, r);
+ } catch (IOException e) {
+ e.printStackTrace();
+ fail("unexpected: " + e);
+ }
+ }
/**
* Regression test for HARMONY-3703.
* @tests java.util.zip.GZIPInputStream#read()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "read",
- args = {byte[].class}
- )
public void test_read() throws IOException {
GZIPInputStream gis = null;
int result = 0;
@@ -350,11 +287,11 @@ public class GZIPInputStreamTest extends junit.framework.TestCase {
@Override
protected void setUp() {
- resources = Support_Resources.createTempFolder();
- }
+ resources = Support_Resources.createTempFolder();
+ }
- @Override
+ @Override
protected void tearDown() {
- }
+ }
}
diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPOutputStreamTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPOutputStreamTest.java
index b71ce63..fdcc3fa 100644
--- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPOutputStreamTest.java
+++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/GZIPOutputStreamTest.java
@@ -14,14 +14,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.harmony.archive.tests.java.util.zip;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@@ -29,213 +23,160 @@ import java.io.OutputStream;
import java.util.zip.Checksum;
import java.util.zip.GZIPOutputStream;
-@TestTargetClass(GZIPOutputStream.class)
public class GZIPOutputStreamTest extends junit.framework.TestCase {
- class TestGZIPOutputStream extends GZIPOutputStream {
- TestGZIPOutputStream(OutputStream out) throws IOException {
- super(out);
- }
-
- TestGZIPOutputStream(OutputStream out, int size) throws IOException {
- super(out, size);
- }
-
- Checksum getChecksum() {
- return crc;
- }
- }
-
- /**
- * @tests java.util.zip.GZIPOutputStream#GZIPOutputStream(java.io.OutputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "GZIPOutputStream",
- args = {java.io.OutputStream.class}
- )
- public void test_ConstructorLjava_io_OutputStream() {
- try {
- FileOutputStream outFile = new FileOutputStream(
- File.createTempFile("GZIPOutCon", ".txt"));
- TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile);
- assertNotNull("the constructor for GZIPOutputStream is null",
- outGZIP);
- assertEquals("the CRC value of the outputStream is not zero", 0,
- outGZIP.getChecksum().getValue());
- outGZIP.close();
- } catch (IOException e) {
- fail("an IO error occured while trying to find the output file or creating GZIP constructor");
- }
- }
-
- /**
- * @tests java.util.zip.GZIPOutputStream#GZIPOutputStream(java.io.OutputStream,
- * int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "GZIPOutputStream",
- args = {java.io.OutputStream.class, int.class}
- )
- public void test_ConstructorLjava_io_OutputStreamI() {
- try {
- FileOutputStream outFile = new FileOutputStream(
- File.createTempFile("GZIPOutCon", ".txt"));
- TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile,
- 100);
- assertNotNull("the constructor for GZIPOutputStream is null",
- outGZIP);
- assertEquals("the CRC value of the outputStream is not zero", 0,
- outGZIP.getChecksum().getValue());
- outGZIP.close();
- } catch (IOException e) {
- fail("an IO error occured while trying to find the output file or creating GZIP constructor");
- }
- }
-
- /**
- * @tests java.util.zip.GZIPOutputStream#finish()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "finish",
- args = {}
- )
- public void test_finish() {
- // test method java.util.zip.GZIPOutputStream.finish()
- byte byteArray[] = {3, 5, 2, 'r', 'g', 'e', 'f', 'd', 'e', 'w'};
- TestGZIPOutputStream outGZIP = null;
- FileOutputStream outFile = null;
- try {
- outFile = new FileOutputStream(
- File.createTempFile("GZIPOutCon", ".txt"));
- outGZIP = new TestGZIPOutputStream(outFile);
-
- outGZIP.finish();
- int r = 0;
- try {
- outGZIP.write(byteArray, 0, 1);
- } catch (IOException e) {
- r = 1;
- }
-
- assertEquals(
- "GZIP instance can still be used after finish is called",
- 1, r);
- outGZIP.close();
- } catch (IOException e) {
- fail("an IO error occured while trying to find the output file or creating GZIP constructor");
- }
- try {
- outFile = new FileOutputStream("GZIPOutFinish.txt");
- outGZIP = new TestGZIPOutputStream(outFile);
- outFile.close();
-
- outGZIP.finish();
- fail("Expected IOException");
- } catch (IOException e) {
- // expected
- }
- }
-
- /**
- * @tests java.util.zip.GZIPOutputStream#close()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException checking missed.",
- method = "close",
- args = {}
- )
- public void test_close() {
- // test method java.util.zip.GZIPOutputStream.close()
- byte byteArray[] = {3, 5, 2, 'r', 'g', 'e', 'f', 'd', 'e', 'w'};
- try {
- FileOutputStream outFile = new FileOutputStream(
- File.createTempFile("GZIPOutCon", ".txt"));
- TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile);
- outGZIP.close();
- int r = 0;
- try {
- outGZIP.write(byteArray, 0, 1);
- } catch (IOException e) {
- r = 1;
- }
- assertEquals(
- "GZIP instance can still be used after close is called", 1,
- r);
- } catch (IOException e) {
- fail("an IO error occured while trying to find the output file or creating GZIP constructor");
- }
- }
-
- /**
- * @tests java.util.zip.GZIPOutputStream#write(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {byte[].class, int.class, int.class}
- )
- public void test_write$BII() {
- // test method java.util.zip.GZIPOutputStream.writeBII
- byte byteArray[] = {3, 5, 2, 'r', 'g', 'e', 'f', 'd', 'e', 'w'};
- TestGZIPOutputStream outGZIP = null;
- try {
- FileOutputStream outFile = new FileOutputStream(
- File.createTempFile("GZIPOutCon", ".txt"));
- outGZIP = new TestGZIPOutputStream(outFile);
- outGZIP.write(byteArray, 0, 10);
- // ran JDK and found this CRC32 value is 3097700292
- // System.out.print(outGZIP.getChecksum().getValue());
- assertEquals(
- "the checksum value was incorrect result of write from GZIP",
- 3097700292L, outGZIP.getChecksum().getValue());
-
- // test for boundary check
- int r = 0;
- try {
- outGZIP.write(byteArray, 0, 11);
- } catch (IndexOutOfBoundsException ee) {
- r = 1;
- }
- assertEquals("out of bounds exception is not present", 1, r);
- outGZIP.close();
- } catch (IOException e) {
- fail("an IO error occured while trying to find the output file or creating GZIP constructor");
- }
- try {
- outGZIP.write(byteArray, 0, 10);
- fail("Expected IOException");
- } catch (IOException e) {
- // expected
- }
- }
-
- @Override
+ class TestGZIPOutputStream extends GZIPOutputStream {
+ TestGZIPOutputStream(OutputStream out) throws IOException {
+ super(out);
+ }
+
+ TestGZIPOutputStream(OutputStream out, int size) throws IOException {
+ super(out, size);
+ }
+
+ Checksum getChecksum() {
+ return crc;
+ }
+ }
+
+ /**
+ * @tests java.util.zip.GZIPOutputStream#GZIPOutputStream(java.io.OutputStream)
+ */
+ public void test_ConstructorLjava_io_OutputStream() {
+ try {
+ FileOutputStream outFile = new FileOutputStream("GZIPOutCon.txt");
+ TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile);
+ assertNotNull("the constructor for GZIPOutputStream is null",
+ outGZIP);
+ assertEquals("the CRC value of the outputStream is not zero", 0, outGZIP
+ .getChecksum().getValue());
+ outGZIP.close();
+ } catch (IOException e) {
+ fail(
+ "an IO error occured while trying to find the output file or creating GZIP constructor");
+ }
+ }
+
+ /**
+ * @tests java.util.zip.GZIPOutputStream#GZIPOutputStream(java.io.OutputStream,
+ * int)
+ */
+ public void test_ConstructorLjava_io_OutputStreamI() {
+ try {
+ FileOutputStream outFile = new FileOutputStream("GZIPOutCon.txt");
+ TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile,
+ 100);
+ assertNotNull("the constructor for GZIPOutputStream is null",
+ outGZIP);
+ assertEquals("the CRC value of the outputStream is not zero", 0, outGZIP
+ .getChecksum().getValue());
+ outGZIP.close();
+ } catch (IOException e) {
+ fail(
+ "an IO error occured while trying to find the output file or creating GZIP constructor");
+ }
+ }
+
+ /**
+ * @tests java.util.zip.GZIPOutputStream#finish()
+ */
+ public void test_finish() {
+ // test method java.util.zip.GZIPOutputStream.finish()
+ byte byteArray[] = { 3, 5, 2, 'r', 'g', 'e', 'f', 'd', 'e', 'w' };
+ try {
+ FileOutputStream outFile = new FileOutputStream("GZIPOutFinish.txt");
+ TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile);
+
+ outGZIP.finish();
+ int r = 0;
+ try {
+ outGZIP.write(byteArray, 0, 1);
+ } catch (IOException e) {
+ r = 1;
+ }
+
+ assertEquals("GZIP instance can still be used after finish is called",
+ 1, r);
+ outGZIP.close();
+ } catch (IOException e) {
+ fail(
+ "an IO error occured while trying to find the output file or creating GZIP constructor");
+ }
+ }
+
+ /**
+ * @tests java.util.zip.GZIPOutputStream#close()
+ */
+ public void test_close() {
+ // test method java.util.zip.GZIPOutputStream.close()
+ byte byteArray[] = { 3, 5, 2, 'r', 'g', 'e', 'f', 'd', 'e', 'w' };
+ try {
+ FileOutputStream outFile = new FileOutputStream("GZIPOutClose2.txt");
+ TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile);
+ outGZIP.close();
+ int r = 0;
+ try {
+ outGZIP.write(byteArray, 0, 1);
+ } catch (IOException e) {
+ r = 1;
+ }
+ assertEquals("GZIP instance can still be used after close is called",
+ 1, r);
+ } catch (IOException e) {
+ fail(
+ "an IO error occured while trying to find the output file or creating GZIP constructor");
+ }
+ }
+
+ /**
+ * @tests java.util.zip.GZIPOutputStream#write(byte[], int, int)
+ */
+ public void test_write$BII() {
+ // test method java.util.zip.GZIPOutputStream.writeBII
+ byte byteArray[] = { 3, 5, 2, 'r', 'g', 'e', 'f', 'd', 'e', 'w' };
+ try {
+ FileOutputStream outFile = new FileOutputStream("GZIPOutWrite.txt");
+ TestGZIPOutputStream outGZIP = new TestGZIPOutputStream(outFile);
+ outGZIP.write(byteArray, 0, 10);
+ // ran JDK and found this CRC32 value is 3097700292
+ // System.out.print(outGZIP.getChecksum().getValue());
+ assertEquals("the checksum value was incorrect result of write from GZIP",
+ 3097700292L, outGZIP.getChecksum().getValue());
+
+ // test for boundary check
+ int r = 0;
+ try {
+ outGZIP.write(byteArray, 0, 11);
+ } catch (IndexOutOfBoundsException e) {
+ r = 1;
+ }
+ assertEquals("out of bounds exception is not present", 1, r);
+ outGZIP.close();
+ } catch (IOException e) {
+ fail(
+ "an IO error occured while trying to find the output file or creating GZIP constructor");
+ }
+ }
+
+ @Override
protected void setUp() {
- }
+ }
- @Override
+ @Override
protected void tearDown() {
- try {
- File dFile = new File("GZIPOutCon.txt");
- dFile.delete();
- File dFile2 = new File("GZIPOutFinish.txt");
+ try {
+ File dFile = new File("GZIPOutCon.txt");
+ dFile.delete();
+ File dFile2 = new File("GZIPOutFinish.txt");
dFile2.delete();
- File dFile3 = new File("GZIPOutWrite.txt");
+ File dFile3 = new File("GZIPOutWrite.txt");
dFile3.delete();
- File dFile4 = new File("GZIPOutClose2.txt");
- dFile4.delete();
- } catch (SecurityException e) {
- fail("Cannot delete file for security reasons");
- }
- }
+ File dFile4 = new File("GZIPOutClose2.txt");
+ dFile4.delete();
+ } catch (SecurityException e) {
+ fail("Cannot delete file for security reasons");
+ }
+ }
}
diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterInputStreamTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterInputStreamTest.java
index 707f13b..3ab7a64 100644
--- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterInputStreamTest.java
+++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterInputStreamTest.java
@@ -14,139 +14,107 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.harmony.archive.tests.java.util.zip;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-import junit.framework.TestCase;
-
-import tests.support.resource.Support_Resources;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
+import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
-import java.io.FileOutputStream;
-import java.io.EOFException;
+import java.io.File;
+import java.io.FileInputStream;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
-@TestTargetClass(InflaterInputStream.class)
-public class InflaterInputStreamTest extends TestCase {
-
- // files hyts_constru(O),hyts_constru(OD),hyts_constru(ODI) needs to be
- // included as resources
- byte outPutBuf[] = new byte[500];
-
- class MyInflaterInputStream extends InflaterInputStream {
- MyInflaterInputStream(InputStream in) {
- super(in);
- }
-
- MyInflaterInputStream(InputStream in, Inflater infl) {
- super(in, infl);
- }
-
- MyInflaterInputStream(InputStream in, Inflater infl, int size) {
- super(in, infl, size);
- }
-
- void myFill() throws IOException {
- fill();
- }
- }
-
- /**
- * @tests java.util.zip.InflaterInputStream#InflaterInputStream(java.io.InputStream)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InflaterInputStream",
- args = {java.io.InputStream.class}
- )
- public void test_ConstructorLjava_io_InputStream() throws IOException {
- byte byteArray[] = new byte[100];
- InputStream infile = Support_Resources.getStream("hyts_constru_OD.txt");
- InflaterInputStream inflatIP = new InflaterInputStream(infile);
-
- inflatIP.read(byteArray, 0, 5);// only suppose to read in 5 bytes
- inflatIP.close();
- }
-
- /**
- * @tests java.util.zip.InflaterInputStream#InflaterInputStream(java.io.InputStream,
- * java.util.zip.Inflater)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InflaterInputStream",
- args = {java.io.InputStream.class, java.util.zip.Inflater.class}
- )
- public void test_ConstructorLjava_io_InputStreamLjava_util_zip_Inflater()
- throws IOException {
- byte byteArray[] = new byte[100];
- InputStream infile = Support_Resources.getStream("hyts_constru_OD.txt");
- Inflater inflate = new Inflater();
- InflaterInputStream inflatIP = new InflaterInputStream(infile, inflate);
-
- inflatIP.read(byteArray, 0, 5);// only suppose to read in 5 bytes
- inflatIP.close();
- }
-
- /**
- * @tests java.util.zip.InflaterInputStream#InflaterInputStream(java.io.InputStream,
- * java.util.zip.Inflater, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "IllegalArgumentException checking missed.",
- method = "InflaterInputStream",
- args = {java.io.InputStream.class, java.util.zip.Inflater.class, int.class}
- )
- public void test_ConstructorLjava_io_InputStreamLjava_util_zip_InflaterI()
- throws IOException {
- int result = 0;
- int buffer[] = new int[500];
- InputStream infile = Support_Resources
- .getStream("hyts_constru_ODI.txt");
- Inflater inflate = new Inflater();
- InflaterInputStream inflatIP = new InflaterInputStream(infile, inflate,
- 1);
-
- int i = 0;
- while ((result = inflatIP.read()) != -1) {
- buffer[i] = result;
- i++;
- }
- inflatIP.close();
+import junit.framework.TestCase;
+import tests.support.resource.Support_Resources;
- try {
- inflatIP = new InflaterInputStream(infile, inflate, -1);
- fail("IllegalArgumentException expected.");
- } catch (IllegalArgumentException ee) {
- // expected
- }
+public class InflaterInputStreamTest extends TestCase {
- }
+ // files hyts_constru(O),hyts_constru(OD),hyts_constru(ODI) needs to be
+ // included as resources
+ // android-changed: we removed the parentheses for the benefit of our broken build system.
+ byte outPutBuf[] = new byte[500];
+
+ class MyInflaterInputStream extends InflaterInputStream {
+ MyInflaterInputStream(InputStream in) {
+ super(in);
+ }
+
+ MyInflaterInputStream(InputStream in, Inflater infl) {
+ super(in, infl);
+ }
+
+ MyInflaterInputStream(InputStream in, Inflater infl, int size) {
+ super(in, infl, size);
+ }
+
+ void myFill() throws IOException {
+ fill();
+ }
+ }
+
+ /**
+ * @tests java.util.zip.InflaterInputStream#InflaterInputStream(java.io.InputStream)
+ */
+ public void test_ConstructorLjava_io_InputStream() throws IOException {
+ //FIXME This test doesn't pass in Harmony classlib or Sun 5.0_7 RI
+ /*
+ int result = 0;
+ int buffer[] = new int[500];
+ InputStream infile = Support_Resources
+ .getStream("hyts_constru_O.txt"); // android-changed
+
+ InflaterInputStream inflatIP = new InflaterInputStream(infile);
+
+ int i = 0;
+ while ((result = inflatIP.read()) != -1) {
+ buffer[i] = result;
+ i++;
+ }
+ inflatIP.close();
+ */
+ }
+
+ /**
+ * @tests java.util.zip.InflaterInputStream#InflaterInputStream(java.io.InputStream,
+ * java.util.zip.Inflater)
+ */
+ public void test_ConstructorLjava_io_InputStreamLjava_util_zip_Inflater() throws IOException {
+ byte byteArray[] = new byte[100];
+ InputStream infile = Support_Resources.getStream("hyts_constru_OD.txt"); // android-changed
+ Inflater inflate = new Inflater();
+ InflaterInputStream inflatIP = new InflaterInputStream(infile,
+ inflate);
+
+ inflatIP.read(byteArray, 0, 5);// only suppose to read in 5 bytes
+ inflatIP.close();
+ }
+
+ /**
+ * @tests java.util.zip.InflaterInputStream#InflaterInputStream(java.io.InputStream,
+ * java.util.zip.Inflater, int)
+ */
+ public void test_ConstructorLjava_io_InputStreamLjava_util_zip_InflaterI() throws IOException {
+ int result = 0;
+ int buffer[] = new int[500];
+ InputStream infile = Support_Resources.getStream("hyts_constru_ODI.txt"); // android-changed
+ Inflater inflate = new Inflater();
+ InflaterInputStream inflatIP = new InflaterInputStream(infile,
+ inflate, 1);
+
+ int i = 0;
+ while ((result = inflatIP.read()) != -1) {
+ buffer[i] = result;
+ i++;
+ }
+ inflatIP.close();
+ }
/**
* @tests java.util.zip.InflaterInputStream#mark(int)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "mark",
- args = {int.class}
- )
public void test_markI() {
InputStream is = new ByteArrayInputStream(new byte[10]);
InflaterInputStream iis = new InflaterInputStream(is);
@@ -159,12 +127,6 @@ public class InflaterInputStreamTest extends TestCase {
/**
* @tests java.util.zip.InflaterInputStream#markSupported()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "markSupported",
- args = {}
- )
public void test_markSupported() {
InputStream is = new ByteArrayInputStream(new byte[10]);
InflaterInputStream iis = new InflaterInputStream(is);
@@ -172,43 +134,32 @@ public class InflaterInputStreamTest extends TestCase {
assertTrue(is.markSupported());
}
- /**
+ /**
* @tests java.util.zip.InflaterInputStream#read()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "read",
- args = {}
- )
- public void test_read() throws IOException {
- int result = 0;
- int buffer[] = new int[500];
- byte orgBuffer[] = {1, 3, 4, 7, 8};
- InputStream infile = Support_Resources.getStream("hyts_constru_OD.txt");
- Inflater inflate = new Inflater();
- InflaterInputStream inflatIP = new InflaterInputStream(infile, inflate);
-
- int i = 0;
- while ((result = inflatIP.read()) != -1) {
- buffer[i] = result;
- i++;
- }
- inflatIP.close();
-
- for (int j = 0; j < orgBuffer.length; j++) {
- assertTrue(
- "original compressed data did not equal decompressed data",
- buffer[j] == orgBuffer[j]);
- }
- inflatIP.close();
- try {
- inflatIP.read();
- fail("IOException expected");
- } catch (IOException ee) {
- // expected.
- }
- }
+ public void test_read() throws IOException {
+ int result = 0;
+ int buffer[] = new int[500];
+ byte orgBuffer[] = { 1, 3, 4, 7, 8 };
+ InputStream infile = Support_Resources
+ .getStream("hyts_constru_OD.txt"); // android-changed
+ Inflater inflate = new Inflater();
+ InflaterInputStream inflatIP = new InflaterInputStream(infile,
+ inflate);
+
+ int i = 0;
+ while ((result = inflatIP.read()) != -1) {
+ buffer[i] = result;
+ i++;
+ }
+ inflatIP.close();
+
+ for (int j = 0; j < orgBuffer.length; j++) {
+ assertTrue(
+ "original compressed data did not equal decompressed data",
+ buffer[j] == orgBuffer[j]);
+ }
+ }
public void testAvailableNonEmptySource() throws Exception {
// this byte[] is a deflation of these bytes: { 1, 3, 4, 6 }
@@ -246,24 +197,10 @@ public class InflaterInputStreamTest extends TestCase {
assertEquals(0, in.available());
}
- /**
- * @tests java.util.zip.InflaterInputStream#read(byte[], int, int)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException & ZipException checking missed. Additional tests for fill method is not needed.",
- method = "read",
- args = {byte[].class, int.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException & ZipException checking missed. Additional tests for fill method is not needed.",
- method = "fill",
- args = {}
- )
- })
- public void test_read$BII() throws IOException {
+ /**
+ * @tests java.util.zip.InflaterInputStream#read(byte[], int, int)
+ */
+ public void test_read$BII() throws IOException{
byte[] test = new byte[507];
for (int i = 0; i < 256; i++) {
test[i] = (byte) i;
@@ -282,7 +219,7 @@ public class InflaterInputStreamTest extends TestCase {
while (true) {
result = iis.read(outBuf, 0, 5);
if (result == -1) {
- // "EOF was reached";
+ //"EOF was reached";
break;
}
}
@@ -292,26 +229,8 @@ public class InflaterInputStreamTest extends TestCase {
} catch (IndexOutOfBoundsException e) {
// expected;
}
- iis.close();
- }
+ }
- /**
- * @tests java.util.zip.InflaterInputStream#read(byte[], int, int)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException checking.",
- method = "read",
- args = {byte[].class, int.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException checking.",
- method = "fill",
- args = {}
- )
- })
public void test_read$BII2() throws IOException {
File resources = Support_Resources.createTempFolder();
Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
@@ -329,20 +248,6 @@ public class InflaterInputStreamTest extends TestCase {
}
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException checking.",
- method = "read",
- args = {byte[].class, int.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException checking.",
- method = "fill",
- args = {}
- )
- })
public void test_read$BII3() throws IOException {
File resources = Support_Resources.createTempFolder();
Support_Resources.copyFile(resources, null, "Broken_manifest.jar");
@@ -362,12 +267,6 @@ public class InflaterInputStreamTest extends TestCase {
/**
* @tests java.util.zip.InflaterInputStream#reset()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reset",
- args = {}
- )
public void test_reset() {
InputStream is = new ByteArrayInputStream(new byte[10]);
InflaterInputStream iis = new InflaterInputStream(is);
@@ -378,135 +277,110 @@ public class InflaterInputStreamTest extends TestCase {
// correct
}
}
-
- /**
- * @tests java.util.zip.InflaterInputStream#skip(long)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException checking missed.",
- method = "skip",
- args = {long.class}
- )
- public void test_skipJ() throws IOException {
- InputStream is = Support_Resources.getStream("hyts_available.tst");
- InflaterInputStream iis = new InflaterInputStream(is);
-
- // Tests for skipping a negative number of bytes.
- try {
- iis.skip(-3);
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
+
+ /**
+ * @tests java.util.zip.InflaterInputStream#skip(long)
+ */
+ public void test_skipJ() throws IOException {
+ InputStream is = Support_Resources.getStream("hyts_available.tst");
+ InflaterInputStream iis = new InflaterInputStream(is);
+
+ // Tests for skipping a negative number of bytes.
+ try {
+ iis.skip(-3);
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
// Expected
- }
- assertEquals("Incorrect Byte Returned.", 5, iis.read());
+ }
+ assertEquals("Incorrect Byte Returned.", 5, iis.read());
- try {
- iis.skip(Integer.MIN_VALUE);
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
+ try {
+ iis.skip(Integer.MIN_VALUE);
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
// Expected
- }
- assertEquals("Incorrect Byte Returned.", 4, iis.read());
+ }
+ assertEquals("Incorrect Byte Returned.", 4, iis.read());
- // Test to make sure the correct number of bytes were skipped
- assertEquals("Incorrect Number Of Bytes Skipped.", 3, iis.skip(3));
+ // Test to make sure the correct number of bytes were skipped
+ assertEquals("Incorrect Number Of Bytes Skipped.", 3, iis.skip(3));
- // Test to see if the number of bytes skipped returned is true.
- assertEquals("Incorrect Byte Returned.", 7, iis.read());
+ // Test to see if the number of bytes skipped returned is true.
+ assertEquals("Incorrect Byte Returned.", 7, iis.read());
- assertEquals("Incorrect Number Of Bytes Skipped.", 0, iis.skip(0));
- assertEquals("Incorrect Byte Returned.", 0, iis.read());
+ assertEquals("Incorrect Number Of Bytes Skipped.", 0, iis.skip(0));
+ assertEquals("Incorrect Byte Returned.", 0, iis.read());
- // Test for skipping more bytes than available in the stream
- assertEquals("Incorrect Number Of Bytes Skipped.", 2, iis.skip(4));
- assertEquals("Incorrect Byte Returned.", -1, iis.read());
- iis.close();
- }
+ // Test for skipping more bytes than available in the stream
+ assertEquals("Incorrect Number Of Bytes Skipped.", 2, iis.skip(4));
+ assertEquals("Incorrect Byte Returned.", -1, iis.read());
+ iis.close();
+ }
- /**
- * @tests java.util.zip.InflaterInputStream#skip(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "IOException checking missed.",
- method = "skip",
- args = {long.class}
- )
- public void test_skipJ2() throws IOException {
- int result = 0;
- int buffer[] = new int[100];
- byte orgBuffer[] = {1, 3, 4, 7, 8};
+ /**
+ * @tests java.util.zip.InflaterInputStream#skip(long)
+ */
+ public void test_skipJ2() throws IOException {
+ int result = 0;
+ int buffer[] = new int[100];
+ byte orgBuffer[] = { 1, 3, 4, 7, 8 };
// testing for negative input to skip
- InputStream infile = Support_Resources.getStream("hyts_constru_OD.txt");
- Inflater inflate = new Inflater();
- InflaterInputStream inflatIP = new InflaterInputStream(infile, inflate,
- 10);
- long skip;
- try {
- skip = inflatIP.skip(Integer.MIN_VALUE);
- fail("Expected IllegalArgumentException when skip() is called with negative parameter");
- } catch (IllegalArgumentException e) {
+ InputStream infile = Support_Resources
+ .getStream("hyts_constru_OD.txt"); // android-changed
+ Inflater inflate = new Inflater();
+ InflaterInputStream inflatIP = new InflaterInputStream(infile,
+ inflate, 10);
+ long skip;
+ try {
+ skip = inflatIP.skip(Integer.MIN_VALUE);
+ fail("Expected IllegalArgumentException when skip() is called with negative parameter");
+ } catch (IllegalArgumentException e) {
// Expected
- }
- inflatIP.close();
-
- // testing for number of bytes greater than input.
- InputStream infile2 = Support_Resources
- .getStream("hyts_constru_OD.txt");
- InflaterInputStream inflatIP2 = new InflaterInputStream(infile2);
-
- // looked at how many bytes the skip skipped. It is
- // 5 and its supposed to be the entire input stream.
-
- skip = inflatIP2.skip(Integer.MAX_VALUE);
- // System.out.println(skip);
- assertEquals("method skip() returned wrong number of bytes skipped", 5,
- skip);
-
- // test for skipping of 2 bytes
- InputStream infile3 = Support_Resources
- .getStream("hyts_constru_OD.txt");
- InflaterInputStream inflatIP3 = new InflaterInputStream(infile3);
- skip = inflatIP3.skip(2);
- assertEquals(
- "the number of bytes returned by skip did not correspond with its input parameters",
- 2, skip);
- int i = 0;
- result = 0;
- while ((result = inflatIP3.read()) != -1) {
- buffer[i] = result;
- i++;
- }
- inflatIP2.close();
-
- for (int j = 2; j < orgBuffer.length; j++) {
- assertTrue(
- "original compressed data did not equal decompressed data",
- buffer[j - 2] == orgBuffer[j]);
- }
-
- try {
- inflatIP2.skip(4);
- fail("IOException expected.");
- } catch (IOException ee) {
- // expected
- }
- }
-
- /**
- * @tests java.util.zip.InflaterInputStream#available()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "available",
- args = {}
- )
- public void test_available() throws IOException {
- InputStream is = Support_Resources.getStream("hyts_available.tst");
- InflaterInputStream iis = new InflaterInputStream(is);
+ }
+ inflatIP.close();
+
+ // testing for number of bytes greater than input.
+ InputStream infile2 = Support_Resources
+ .getStream("hyts_constru_OD.txt"); // android-changed
+ InflaterInputStream inflatIP2 = new InflaterInputStream(infile2);
+
+ // looked at how many bytes the skip skipped. It is
+ // 5 and its supposed to be the entire input stream.
+
+ skip = inflatIP2.skip(Integer.MAX_VALUE);
+ // System.out.println(skip);
+ assertEquals("method skip() returned wrong number of bytes skipped",
+ 5, skip);
+
+ // test for skipping of 2 bytes
+ InputStream infile3 = Support_Resources
+ .getStream("hyts_constru_OD.txt"); // android-changed
+ InflaterInputStream inflatIP3 = new InflaterInputStream(infile3);
+ skip = inflatIP3.skip(2);
+ assertEquals("the number of bytes returned by skip did not correspond with its input parameters",
+ 2, skip);
+ int i = 0;
+ result = 0;
+ while ((result = inflatIP3.read()) != -1) {
+ buffer[i] = result;
+ i++;
+ }
+ inflatIP2.close();
+
+ for (int j = 2; j < orgBuffer.length; j++) {
+ assertTrue(
+ "original compressed data did not equal decompressed data",
+ buffer[j - 2] == orgBuffer[j]);
+ }
+ }
+
+ /**
+ * @tests java.util.zip.InflaterInputStream#available()
+ */
+ public void test_available() throws IOException {
+ InputStream is = Support_Resources.getStream("hyts_available.tst");
+ InflaterInputStream iis = new InflaterInputStream(is);
int available;
for (int i = 0; i < 11; i++) {
@@ -519,31 +393,24 @@ public class InflaterInputStreamTest extends TestCase {
}
}
- iis.close();
- try {
- iis.available();
- fail("available after close should throw IOException.");
- } catch (IOException e) {
+ iis.close();
+ try {
+ iis.available();
+ fail("available after close should throw IOException.");
+ } catch (IOException e) {
// Expected
- }
- }
+ }
+ }
- /**
- * @tests java.util.zip.InflaterInputStream#close()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "IOException can not be tested.",
- method = "close",
- args = {}
- )
- public void test_close() throws IOException {
- InflaterInputStream iin = new InflaterInputStream(
- new ByteArrayInputStream(new byte[0]));
- iin.close();
+ /**
+ * @tests java.util.zip.InflaterInputStream#close()
+ */
+ public void test_close() throws IOException {
+ InflaterInputStream iin = new InflaterInputStream(
+ new ByteArrayInputStream(new byte[0]));
+ iin.close();
// test for exception
- iin.close();
-
- }
+ iin.close();
+ }
}
diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterTest.java
index cd5d538..49be8d0 100644
--- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterTest.java
+++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/InflaterTest.java
@@ -14,17 +14,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.harmony.archive.tests.java.util.zip;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
+import java.util.Arrays;
import java.util.zip.Adler32;
import java.io.UnsupportedEncodingException;
import java.util.zip.DataFormatException;
@@ -34,345 +29,292 @@ import java.util.zip.ZipException;
import tests.support.resource.Support_Resources;
-@TestTargetClass(Inflater.class)
public class InflaterTest extends junit.framework.TestCase {
- byte outPutBuff1[] = new byte[500];
-
- byte outPutDiction[] = new byte[500];
-
- /**
- * @tests java.util.zip.Inflater#end()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "end",
- args = {}
- )
- public void test_end() {
- // test method of java.util.zip.inflater.end()
- byte byteArray[] = {5, 2, 3, 7, 8};
-
- int r = 0;
- Inflater inflate = new Inflater();
- inflate.setInput(byteArray);
- inflate.end();
- try {
- inflate.reset();
- inflate.setInput(byteArray);
- } catch (NullPointerException e) {
- r = 1;
- }
- assertEquals("inflate can still be used after end is called", 1, r);
-
- Inflater i = new Inflater();
- i.end();
- // check for exception
- i.end();
- }
-
- /**
- * @tests java.util.zip.Inflater#finished()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "finished",
- args = {}
- )
- public void test_finished() {
- // test method of java.util.zip.inflater.finished()
- byte byteArray[] = {1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5'};
- Inflater inflate = new Inflater(false);
- byte outPutInf[] = new byte[500];
- try {
- while (!(inflate.finished())) {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuff1);
- }
-
- inflate.inflate(outPutInf);
- }
- assertTrue(
- "the method finished() returned false when no more data needs to be decompressed",
- inflate.finished());
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- }
- for (int i = 0; i < byteArray.length; i++) {
- assertTrue(
- "Final decompressed data does not equal the original data",
- byteArray[i] == outPutInf[i]);
- }
- assertEquals(
- "final decompressed data contained more bytes than original - finished()",
- 0, outPutInf[byteArray.length]);
- }
-
- /**
- * @tests java.util.zip.Inflater#getAdler()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAdler",
- args = {}
- )
- public void test_getAdler() {
- // test method of java.util.zip.inflater.getAdler()
- byte dictionaryArray[] = {'e', 'r', 't', 'a', 'b', 2, 3};
-
- Inflater inflateDiction = new Inflater();
- inflateDiction.setInput(outPutDiction);
- if (inflateDiction.needsDictionary() == true) {
- // getting the checkSum value through the Adler32 class
- Adler32 adl = new Adler32();
- adl.update(dictionaryArray);
- long checkSumR = adl.getValue();
- assertTrue(
- "the checksum value returned by getAdler() is not the same as the checksum returned by creating the adler32 instance",
- checkSumR == inflateDiction.getAdler());
- }
- }
+ byte outPutBuff1[] = new byte[500];
+
+ byte outPutDiction[] = new byte[500];
+
+ /**
+ * @tests java.util.zip.Inflater#end()
+ */
+ public void test_end() {
+ // test method of java.util.zip.inflater.end()
+ byte byteArray[] = { 5, 2, 3, 7, 8 };
+
+ int r = 0;
+ Inflater inflate = new Inflater();
+ inflate.setInput(byteArray);
+ inflate.end();
+ try {
+ inflate.reset();
+ inflate.setInput(byteArray);
+ } catch (NullPointerException e) {
+ r = 1;
+ }
+ assertEquals("inflate can still be used after end is called", 1, r);
+
+ Inflater i = new Inflater();
+ i.end();
+ // check for exception
+ i.end();
+ }
+
+ /**
+ * @tests java.util.zip.Inflater#finished()
+ */
+ public void test_finished() {
+ // test method of java.util.zip.inflater.finished()
+ byte byteArray[] = { 1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5' };
+ Inflater inflate = new Inflater(false);
+ byte outPutInf[] = new byte[500];
+ try {
+ while (!(inflate.finished())) {
+ if (inflate.needsInput()) {
+ inflate.setInput(outPutBuff1);
+ }
+
+ inflate.inflate(outPutInf);
+ }
+ assertTrue(
+ "the method finished() returned false when no more data needs to be decompressed",
+ inflate.finished());
+ } catch (DataFormatException e) {
+ fail("Invalid input to be decompressed");
+ }
+ for (int i = 0; i < byteArray.length; i++) {
+ assertTrue(
+ "Final decompressed data does not equal the original data",
+ byteArray[i] == outPutInf[i]);
+ }
+ assertEquals("final decompressed data contained more bytes than original - finished()",
+ 0, outPutInf[byteArray.length]);
+ }
+
+ /**
+ * @tests java.util.zip.Inflater#getAdler()
+ */
+ public void test_getAdler() {
+ // test method of java.util.zip.inflater.getAdler()
+ byte dictionaryArray[] = { 'e', 'r', 't', 'a', 'b', 2, 3 };
+
+ Inflater inflateDiction = new Inflater();
+ inflateDiction.setInput(outPutDiction);
+ if (inflateDiction.needsDictionary() == true) {
+ // getting the checkSum value through the Adler32 class
+ Adler32 adl = new Adler32();
+ adl.update(dictionaryArray);
+ long checkSumR = adl.getValue();
+ assertTrue(
+ "the checksum value returned by getAdler() is not the same as the checksum returned by creating the adler32 instance",
+ checkSumR == inflateDiction.getAdler());
+ }
+ }
+
+ /**
+ * @tests java.util.zip.Inflater#getRemaining()
+ */
+ public void test_getRemaining() {
+ // test method of java.util.zip.inflater.getRemaining()
+ byte byteArray[] = { 1, 3, 5, 6, 7 };
+ Inflater inflate = new Inflater();
+ assertEquals("upon creating an instance of inflate, getRemaining returned a non zero value",
+ 0, inflate.getRemaining());
+ inflate.setInput(byteArray);
+ assertTrue(
+ "getRemaining returned zero when there is input in the input buffer",
+ inflate.getRemaining() != 0);
+ }
+
+ /**
+ * @tests java.util.zip.Inflater#getTotalIn()
+ */
+ public void test_getTotalIn() {
+ // test method of java.util.zip.inflater.getTotalIn()
+ // creating the decompressed data
+ byte outPutBuf[] = new byte[500];
+ byte byteArray[] = { 1, 3, 4, 7, 8 };
+ byte outPutInf[] = new byte[500];
+ int x = 0;
+ Deflater deflate = new Deflater(1);
+ deflate.setInput(byteArray);
+ while (!(deflate.needsInput())) {
+ x += deflate.deflate(outPutBuf, x, outPutBuf.length - x);
+ }
+ deflate.finish();
+ while (!(deflate.finished())) {
+ x = x + deflate.deflate(outPutBuf, x, outPutBuf.length - x);
+ }
+
+ Inflater inflate = new Inflater();
+ try {
+ while (!(inflate.finished())) {
+ if (inflate.needsInput()) {
+ inflate.setInput(outPutBuf);
+ }
+
+ inflate.inflate(outPutInf);
+ }
+ } catch (DataFormatException e) {
+ fail("Input to inflate is invalid or corrupted - getTotalIn");
+ }
+ // System.out.print(deflate.getTotalOut() + " " + inflate.getTotalIn());
+ assertTrue(
+ "the total byte in outPutBuf did not equal the byte returned in getTotalIn",
+ inflate.getTotalIn() == deflate.getTotalOut());
+
+ Inflater inflate2 = new Inflater();
+ int offSet = 0;// seems only can start as 0
+ int length = 4;
+ try {
+ // seems no while loops allowed
+ if (inflate2.needsInput()) {
+ inflate2.setInput(outPutBuff1, offSet, length);
+ }
+
+ inflate2.inflate(outPutInf);
+
+ } catch (DataFormatException e) {
+ fail("Input to inflate is invalid or corrupted - getTotalIn");
+ }
+ // System.out.print(inflate2.getTotalIn() + " " + length);
+ assertTrue(
+ "total byte dictated by length did not equal byte returned in getTotalIn",
+ inflate2.getTotalIn() == length);
+ }
+
+ /**
+ * @tests java.util.zip.Inflater#getTotalOut()
+ */
+ public void test_getTotalOut() {
+ // test method of java.util.zip.inflater.Inflater()
+ // creating the decompressed data
+ byte outPutBuf[] = new byte[500];
+ byte byteArray[] = { 1, 3, 4, 7, 8 };
+ int y = 0;
+ int x = 0;
+ Deflater deflate = new Deflater(1);
+ deflate.setInput(byteArray);
+ while (!(deflate.needsInput())) {
+ x += deflate.deflate(outPutBuf, x, outPutBuf.length - x);
+ }
+ deflate.finish();
+ while (!(deflate.finished())) {
+ x = x + deflate.deflate(outPutBuf, x, outPutBuf.length - x);
+ }
+
+ Inflater inflate = new Inflater();
+ byte outPutInf[] = new byte[500];
+ try {
+ while (!(inflate.finished())) {
+ if (inflate.needsInput()) {
+ inflate.setInput(outPutBuf);
+ }
+
+ y += inflate.inflate(outPutInf);
+ }
+ } catch (DataFormatException e) {
+ fail("Input to inflate is invalid or corrupted - getTotalIn");
+ }
+
+ assertTrue(
+ "the sum of the bytes returned from inflate does not equal the bytes of getTotalOut()",
+ y == inflate.getTotalOut());
+ assertTrue(
+ "the total number of bytes to be compressed does not equal the total bytes decompressed",
+ inflate.getTotalOut() == deflate.getTotalIn());
+
+ // testing inflate(byte,int,int)
+ inflate.reset();
+ y = 0;
+ int offSet = 0;// seems only can start as 0
+ int length = 4;
+ try {
+ while (!(inflate.finished())) {
+ if (inflate.needsInput()) {
+ inflate.setInput(outPutBuf);
+ }
+
+ y += inflate.inflate(outPutInf, offSet, length);
+ }
+ } catch (DataFormatException e) {
+ System.out
+ .println("Input to inflate is invalid or corrupted - getTotalIn");
+ }
+ assertTrue(
+ "the sum of the bytes returned from inflate does not equal the bytes of getTotalOut()",
+ y == inflate.getTotalOut());
+ assertTrue(
+ "the total number of bytes to be compressed does not equal the total bytes decompressed",
+ inflate.getTotalOut() == deflate.getTotalIn());
+ }
+
+ /**
+ * @tests java.util.zip.Inflater#inflate(byte[])
+ */
+ public void test_inflate$B() {
+ // test method of java.util.zip.inflater.inflate(byte)
+
+ byte byteArray[] = { 1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5' };
+ byte outPutInf[] = new byte[500];
+ Inflater inflate = new Inflater();
+ try {
+ while (!(inflate.finished())) {
+ if (inflate.needsInput()) {
+ inflate.setInput(outPutBuff1);
+ }
+ inflate.inflate(outPutInf);
+ }
+ } catch (DataFormatException e) {
+ fail("Invalid input to be decompressed");
+ }
+ for (int i = 0; i < byteArray.length; i++) {
+ assertTrue(
+ "Final decompressed data does not equal the original data",
+ byteArray[i] == outPutInf[i]);
+ }
+ assertEquals("final decompressed data contained more bytes than original - inflateB",
+ 0, outPutInf[byteArray.length]);
+ // testing for an empty input array
+ byte outPutBuf[] = new byte[500];
+ byte emptyArray[] = new byte[11];
+ int x = 0;
+ Deflater defEmpty = new Deflater(3);
+ defEmpty.setInput(emptyArray);
+ while (!(defEmpty.needsInput())) {
+ x += defEmpty.deflate(outPutBuf, x, outPutBuf.length - x);
+ }
+ defEmpty.finish();
+ while (!(defEmpty.finished())) {
+ x += defEmpty.deflate(outPutBuf, x, outPutBuf.length - x);
+ }
+ assertTrue(
+ "the total number of byte from deflate did not equal getTotalOut - inflate(byte)",
+ x == defEmpty.getTotalOut());
+ assertTrue(
+ "the number of input byte from the array did not correspond with getTotalIn - inflate(byte)",
+ defEmpty.getTotalIn() == emptyArray.length);
+ Inflater infEmpty = new Inflater();
+ try {
+ while (!(infEmpty.finished())) {
+ if (infEmpty.needsInput()) {
+ infEmpty.setInput(outPutBuf);
+ }
+ infEmpty.inflate(outPutInf);
+ }
+ } catch (DataFormatException e) {
+ fail("Invalid input to be decompressed");
+ }
+ for (int i = 0; i < emptyArray.length; i++) {
+ assertTrue(
+ "Final decompressed data does not equal the original data",
+ emptyArray[i] == outPutInf[i]);
+ assertEquals("Final decompressed data does not equal zero",
+ 0, outPutInf[i]);
+ }
+ assertEquals("Final decompressed data contains more element than original data",
+ 0, outPutInf[emptyArray.length]);
+ }
- /**
- * @tests java.util.zip.Inflater#getRemaining()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRemaining",
- args = {}
- )
- public void test_getRemaining() {
- // test method of java.util.zip.inflater.getRemaining()
- byte byteArray[] = {1, 3, 5, 6, 7};
- Inflater inflate = new Inflater();
- assertEquals(
- "upon creating an instance of inflate, getRemaining returned a non zero value",
- 0, inflate.getRemaining());
- inflate.setInput(byteArray);
- assertTrue(
- "getRemaining returned zero when there is input in the input buffer",
- inflate.getRemaining() != 0);
- }
-
- /**
- * @tests java.util.zip.Inflater#getTotalIn()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTotalIn",
- args = {}
- )
- public void test_getTotalIn() {
- // test method of java.util.zip.inflater.getTotalIn()
- // creating the decompressed data
- byte outPutBuf[] = new byte[500];
- byte byteArray[] = {1, 3, 4, 7, 8};
- byte outPutInf[] = new byte[500];
- int x = 0;
- Deflater deflate = new Deflater(1);
- deflate.setInput(byteArray);
- while (!(deflate.needsInput())) {
- x += deflate.deflate(outPutBuf, x, outPutBuf.length - x);
- }
- deflate.finish();
- while (!(deflate.finished())) {
- x = x + deflate.deflate(outPutBuf, x, outPutBuf.length - x);
- }
-
- Inflater inflate = new Inflater();
- try {
- while (!(inflate.finished())) {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuf);
- }
-
- inflate.inflate(outPutInf);
- }
- } catch (DataFormatException e) {
- fail("Input to inflate is invalid or corrupted - getTotalIn");
- }
- // System.out.print(deflate.getTotalOut() + " " + inflate.getTotalIn());
- assertTrue(
- "the total byte in outPutBuf did not equal the byte returned in getTotalIn",
- inflate.getTotalIn() == deflate.getTotalOut());
-
- Inflater inflate2 = new Inflater();
- int offSet = 0;// seems only can start as 0
- int length = 4;
- try {
- // seems no while loops allowed
- if (inflate2.needsInput()) {
- inflate2.setInput(outPutBuff1, offSet, length);
- }
-
- inflate2.inflate(outPutInf);
-
- } catch (DataFormatException e) {
- fail("Input to inflate is invalid or corrupted - getTotalIn");
- }
- // System.out.print(inflate2.getTotalIn() + " " + length);
- assertTrue(
- "total byte dictated by length did not equal byte returned in getTotalIn",
- inflate2.getTotalIn() == length);
- }
-
- /**
- * @tests java.util.zip.Inflater#getTotalOut()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTotalOut",
- args = {}
- )
- public void test_getTotalOut() {
- // test method of java.util.zip.inflater.Inflater()
- // creating the decompressed data
- byte outPutBuf[] = new byte[500];
- byte byteArray[] = {1, 3, 4, 7, 8};
- int y = 0;
- int x = 0;
- Deflater deflate = new Deflater(1);
- deflate.setInput(byteArray);
- while (!(deflate.needsInput())) {
- x += deflate.deflate(outPutBuf, x, outPutBuf.length - x);
- }
- deflate.finish();
- while (!(deflate.finished())) {
- x = x + deflate.deflate(outPutBuf, x, outPutBuf.length - x);
- }
-
- Inflater inflate = new Inflater();
- byte outPutInf[] = new byte[500];
- try {
- while (!(inflate.finished())) {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuf);
- }
-
- y += inflate.inflate(outPutInf);
- }
- } catch (DataFormatException e) {
- fail("Input to inflate is invalid or corrupted - getTotalIn");
- }
-
- assertTrue(
- "the sum of the bytes returned from inflate does not equal the bytes of getTotalOut()",
- y == inflate.getTotalOut());
- assertTrue(
- "the total number of bytes to be compressed does not equal the total bytes decompressed",
- inflate.getTotalOut() == deflate.getTotalIn());
-
- // testing inflate(byte,int,int)
- inflate.reset();
- y = 0;
- int offSet = 0;// seems only can start as 0
- int length = 4;
- try {
- while (!(inflate.finished())) {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuf);
- }
-
- y += inflate.inflate(outPutInf, offSet, length);
- }
- } catch (DataFormatException e) {
- System.out
- .println("Input to inflate is invalid or corrupted - getTotalIn");
- }
- assertTrue(
- "the sum of the bytes returned from inflate does not equal the bytes of getTotalOut()",
- y == inflate.getTotalOut());
- assertTrue(
- "the total number of bytes to be compressed does not equal the total bytes decompressed",
- inflate.getTotalOut() == deflate.getTotalIn());
- }
-
- /**
- * @tests java.util.zip.Inflater#inflate(byte[])
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "DataFormatException checking missed.",
- method = "inflate",
- args = {byte[].class}
- )
- public void test_inflate$B() {
- // test method of java.util.zip.inflater.inflate(byte)
-
- byte byteArray[] = {1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5'};
- byte outPutInf[] = new byte[500];
- Inflater inflate = new Inflater();
- try {
- while (!(inflate.finished())) {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuff1);
- }
- inflate.inflate(outPutInf);
- }
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- }
- for (int i = 0; i < byteArray.length; i++) {
- assertTrue(
- "Final decompressed data does not equal the original data",
- byteArray[i] == outPutInf[i]);
- }
- assertEquals(
- "final decompressed data contained more bytes than original - inflateB",
- 0, outPutInf[byteArray.length]);
- // testing for an empty input array
- byte outPutBuf[] = new byte[500];
- byte emptyArray[] = new byte[11];
- int x = 0;
- Deflater defEmpty = new Deflater(3);
- defEmpty.setInput(emptyArray);
- while (!(defEmpty.needsInput())) {
- x += defEmpty.deflate(outPutBuf, x, outPutBuf.length - x);
- }
- defEmpty.finish();
- while (!(defEmpty.finished())) {
- x += defEmpty.deflate(outPutBuf, x, outPutBuf.length - x);
- }
- assertTrue(
- "the total number of byte from deflate did not equal getTotalOut - inflate(byte)",
- x == defEmpty.getTotalOut());
- assertTrue(
- "the number of input byte from the array did not correspond with getTotalIn - inflate(byte)",
- defEmpty.getTotalIn() == emptyArray.length);
- Inflater infEmpty = new Inflater();
- try {
- while (!(infEmpty.finished())) {
- if (infEmpty.needsInput()) {
- infEmpty.setInput(outPutBuf);
- }
- infEmpty.inflate(outPutInf);
- }
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- }
- for (int i = 0; i < emptyArray.length; i++) {
- assertTrue(
- "Final decompressed data does not equal the original data",
- emptyArray[i] == outPutInf[i]);
- assertEquals("Final decompressed data does not equal zero", 0,
- outPutInf[i]);
- }
- assertEquals(
- "Final decompressed data contains more element than original data",
- 0, outPutInf[emptyArray.length]);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "inflate",
- args = {byte[].class}
- )
public void test_inflate$B1() {
byte codedData[] = {
120, -38, 75, -54, 73, -52, 80, 40, 46, 41, -54, -52, 75, 87,
@@ -408,82 +350,53 @@ public class InflaterTest extends junit.framework.TestCase {
infl2.end();
}
- /**
- * @tests java.util.zip.Inflater#Inflater()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Inflater",
- args = {}
- )
- public void test_Constructor() {
- // test method of java.util.zip.inflater.Inflater()
- Inflater inflate = new Inflater();
- assertNotNull("failed to create the instance of inflater",
- inflate);
- }
-
- /**
- * @tests java.util.zip.Inflater#inflate(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "DataFormatException checking missed.",
- method = "inflate",
- args = {byte[].class, int.class, int.class}
- )
- public void test_inflate$BII() {
- // test method of java.util.zip.inflater.inflate(byte,int,int)
-
- byte byteArray[] = {1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5'};
- byte outPutInf[] = new byte[100];
- int y = 0;
- Inflater inflate = new Inflater();
- try {
- while (!(inflate.finished())) {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuff1);
- }
- y += inflate.inflate(outPutInf, y, outPutInf.length - y);
- }
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- }
- for (int i = 0; i < byteArray.length; i++) {
- assertTrue(
- "Final decompressed data does not equal the original data",
- byteArray[i] == outPutInf[i]);
- }
- assertEquals(
- "final decompressed data contained more bytes than original - inflateB",
- 0, outPutInf[byteArray.length]);
-
- // test boundary checks
- inflate.reset();
- int r = 0;
- int offSet = 0;
- int lengthError = 101;
- try {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuff1);
- }
- inflate.inflate(outPutInf, offSet, lengthError);
-
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- } catch (ArrayIndexOutOfBoundsException e) {
- r = 1;
- }
- assertEquals("out of bounds error did not get caught", 1, r);
- }
+ /**
+ * @tests java.util.zip.Inflater#inflate(byte[], int, int)
+ */
+ public void test_inflate$BII() {
+ // test method of java.util.zip.inflater.inflate(byte,int,int)
+
+ byte byteArray[] = { 1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5' };
+ byte outPutInf[] = new byte[100];
+ int y = 0;
+ Inflater inflate = new Inflater();
+ try {
+ while (!(inflate.finished())) {
+ if (inflate.needsInput()) {
+ inflate.setInput(outPutBuff1);
+ }
+ y += inflate.inflate(outPutInf, y, outPutInf.length - y);
+ }
+ } catch (DataFormatException e) {
+ fail("Invalid input to be decompressed");
+ }
+ for (int i = 0; i < byteArray.length; i++) {
+ assertTrue(
+ "Final decompressed data does not equal the original data",
+ byteArray[i] == outPutInf[i]);
+ }
+ assertEquals("final decompressed data contained more bytes than original - inflateB",
+ 0, outPutInf[byteArray.length]);
+
+ // test boundary checks
+ inflate.reset();
+ int r = 0;
+ int offSet = 0;
+ int lengthError = 101;
+ try {
+ if (inflate.needsInput()) {
+ inflate.setInput(outPutBuff1);
+ }
+ inflate.inflate(outPutInf, offSet, lengthError);
+
+ } catch (DataFormatException e) {
+ fail("Invalid input to be decompressed");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ r = 1;
+ }
+ assertEquals("out of bounds error did not get caught", 1, r);
+ }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "inflate",
- args = {byte[].class, int.class, int.class}
- )
public void test_inflate$BII1() {
byte codedData[] = {
120, -38, 75, -54, 73, -52, 80, 40, 46, 41, -54, -52, 75, 87,
@@ -519,271 +432,292 @@ public class InflaterTest extends junit.framework.TestCase {
infl2.end();
}
- /**
- * @tests java.util.zip.Inflater#Inflater(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Inflater",
- args = {boolean.class}
- )
- public void test_ConstructorZ() {
- // test method of java.util.zip.inflater.Inflater(boolean)
- // note does not throw exception if deflater has a header, but inflater
- // doesn't or vice versa.
- byte byteArray[] = {1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5'};
- Inflater inflate = new Inflater(true);
- assertNotNull("failed to create the instance of inflater", inflate);
- byte outPutInf[] = new byte[500];
- int r = 0;
- try {
- while (!(inflate.finished())) {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuff1);
- }
-
- inflate.inflate(outPutInf);
- }
- for (int i = 0; i < byteArray.length; i++) {
- assertEquals(
- "the output array from inflate should contain 0 because the header of inflate and deflate did not match, but this failed",
- 0, outPutBuff1[i]);
- }
- } catch (DataFormatException e) {
- r = 1;
- }
- assertEquals(
- "Error: exception should be thrown because of header inconsistency",
- 1, r);
-
- }
-
- /**
- * @tests java.util.zip.Inflater#needsDictionary()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "needsDictionary",
- args = {}
- )
- public void test_needsDictionary() {
- // test method of java.util.zip.inflater.needsDictionary()
- // note: this flag is set after inflate is called
- byte outPutInf[] = new byte[500];
-
- // testing with dictionary set.
- Inflater inflateDiction = new Inflater();
- if (inflateDiction.needsInput()) {
- inflateDiction.setInput(outPutDiction);
- }
- try {
- assertEquals("should return 0 because needs dictionary", 0,
- inflateDiction.inflate(outPutInf));
- } catch (DataFormatException e) {
- fail("Should not cause exception");
- }
- assertTrue(
- "method needsDictionary returned false when dictionary was used in deflater",
- inflateDiction.needsDictionary());
-
- // testing without dictionary
- Inflater inflate = new Inflater();
- try {
- inflate.setInput(outPutBuff1);
- inflate.inflate(outPutInf);
- assertFalse(
- "method needsDictionary returned true when dictionary was not used in deflater",
- inflate.needsDictionary());
- } catch (DataFormatException e) {
- fail("Input to inflate is invalid or corrupted - needsDictionary");
- }
+ /**
+ * @tests java.util.zip.Inflater#Inflater()
+ */
+ public void test_Constructor() {
+ // test method of java.util.zip.inflater.Inflater()
+ Inflater inflate = new Inflater();
+ assertNotNull("failed to create the instance of inflater",
+ inflate);
+ }
+
+ /**
+ * @tests java.util.zip.Inflater#Inflater(boolean)
+ */
+ public void test_ConstructorZ() {
+ // test method of java.util.zip.inflater.Inflater(boolean)
+ // note does not throw exception if deflater has a header, but inflater
+ // doesn't or vice versa.
+ byte byteArray[] = { 1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5' };
+ Inflater inflate = new Inflater(true);
+ assertNotNull("failed to create the instance of inflater", inflate);
+ byte outPutInf[] = new byte[500];
+ int r = 0;
+ try {
+ while (!(inflate.finished())) {
+ if (inflate.needsInput()) {
+ inflate.setInput(outPutBuff1);
+ }
+
+ inflate.inflate(outPutInf);
+ }
+ for (int i = 0; i < byteArray.length; i++) {
+ assertEquals("the output array from inflate should contain 0 because the header of inflate and deflate did not match, but this failed",
+ 0, outPutBuff1[i]);
+ }
+ } catch (DataFormatException e) {
+ r = 1;
+ }
+ assertEquals("Error: exception should be thrown because of header inconsistency",
+ 1, r);
+
+ }
+
+ /**
+ * @tests java.util.zip.Inflater#needsDictionary()
+ */
+ public void test_needsDictionary() {
+ // test method of java.util.zip.inflater.needsDictionary()
+ // note: this flag is set after inflate is called
+ byte outPutInf[] = new byte[500];
+
+ // testing with dictionary set.
+ Inflater inflateDiction = new Inflater();
+ if (inflateDiction.needsInput()) {
+ inflateDiction.setInput(outPutDiction);
+ }
+ try {
+ assertEquals("should return 0 because needs dictionary",
+ 0, inflateDiction.inflate(outPutInf));
+ } catch (DataFormatException e) {
+ fail("Should not cause exception");
+ }
+ assertTrue(
+ "method needsDictionary returned false when dictionary was used in deflater",
+ inflateDiction.needsDictionary());
+
+ // testing without dictionary
+ Inflater inflate = new Inflater();
+ try {
+ inflate.setInput(outPutBuff1);
+ inflate.inflate(outPutInf);
+ assertFalse(
+ "method needsDictionary returned true when dictionary was not used in deflater",
+ inflate.needsDictionary());
+ } catch (DataFormatException e) {
+ fail(
+ "Input to inflate is invalid or corrupted - needsDictionary");
+ }
// Regression test for HARMONY-86
Inflater inf = new Inflater();
assertFalse(inf.needsDictionary());
- assertEquals(0, inf.getTotalIn());
- assertEquals(0, inf.getTotalOut());
- assertEquals(0, inf.getBytesRead());
- assertEquals(0, inf.getBytesWritten());
- }
-
- /**
- * @tests java.util.zip.Inflater#needsInput()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "needsInput",
- args = {}
- )
- public void test_needsInput() {
- // test method of java.util.zip.inflater.needsInput()
- Inflater inflate = new Inflater();
- assertTrue(
- "needsInput give the wrong boolean value as a result of no input buffer",
- inflate.needsInput());
-
- byte byteArray[] = {2, 3, 4, 't', 'y', 'u', 'e', 'w', 7, 6, 5, 9};
- inflate.setInput(byteArray);
- assertFalse(
- "methodNeedsInput returned true when the input buffer is full",
- inflate.needsInput());
-
- inflate.reset();
- byte byteArrayEmpty[] = new byte[0];
- inflate.setInput(byteArrayEmpty);
- assertTrue(
- "needsInput give wrong boolean value as a result of an empty input buffer",
- inflate.needsInput());
- }
-
- /**
- * @tests java.util.zip.Inflater#reset()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reset",
- args = {}
- )
- public void test_reset() {
- // test method of java.util.zip.inflater.reset()
- byte byteArray[] = {1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5'};
- byte outPutInf[] = new byte[100];
- int y = 0;
- Inflater inflate = new Inflater();
- try {
- while (!(inflate.finished())) {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuff1);
- }
- y += inflate.inflate(outPutInf, y, outPutInf.length - y);
- }
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- }
- for (int i = 0; i < byteArray.length; i++) {
- assertTrue(
- "Final decompressed data does not equal the original data",
- byteArray[i] == outPutInf[i]);
- }
- assertEquals(
- "final decompressed data contained more bytes than original - reset",
- 0, outPutInf[byteArray.length]);
-
- // testing that resetting the inflater will also return the correct
- // decompressed data
-
- inflate.reset();
- try {
- while (!(inflate.finished())) {
- if (inflate.needsInput()) {
- inflate.setInput(outPutBuff1);
- }
- inflate.inflate(outPutInf);
- }
- } catch (DataFormatException e) {
- fail("Invalid input to be decompressed");
- }
- for (int i = 0; i < byteArray.length; i++) {
- assertTrue(
- "Final decompressed data does not equal the original data",
- byteArray[i] == outPutInf[i]);
- }
- assertEquals(
- "final decompressed data contained more bytes than original - reset",
- 0, outPutInf[byteArray.length]);
-
- }
-
-
- /**
- * @tests java.util.zip.Inflater#setInput(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setInput",
- args = {byte[].class}
- )
- public void test_setInput$B() {
- // test method of java.util.zip.inflater.setInput(byte)
- byte byteArray[] = {2, 3, 4, 't', 'y', 'u', 'e', 'w', 7, 6, 5, 9};
- Inflater inflate = new Inflater();
- inflate.setInput(byteArray);
- assertTrue("setInputB did not deliver any byte to the input buffer",
- inflate.getRemaining() != 0);
- }
-
- /**
- * @tests java.util.zip.Inflater#setInput(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setInput",
- args = {byte[].class, int.class, int.class}
- )
- public void test_setInput$BII() {
- // test method of java.util.zip.inflater.setInput(byte,int,int)
- byte byteArray[] = {2, 3, 4, 't', 'y', 'u', 'e', 'w', 7, 6, 5, 9};
- int offSet = 6;
- int length = 6;
- Inflater inflate = new Inflater();
- inflate.setInput(byteArray, offSet, length);
- assertTrue(
- "setInputBII did not deliver the right number of bytes to the input buffer",
- inflate.getRemaining() == length);
- // boundary check
- inflate.reset();
- int r = 0;
- try {
- inflate.setInput(byteArray, 100, 100);
- } catch (ArrayIndexOutOfBoundsException e) {
- r = 1;
- }
- assertEquals("boundary check is not present for setInput", 1, r);
- }
-
- @Override
+ assertEquals(0,inf.getTotalIn());
+ assertEquals(0,inf.getTotalOut());
+ assertEquals(0,inf.getBytesRead());
+ assertEquals(0,inf.getBytesWritten());
+ }
+
+ /**
+ * @tests java.util.zip.Inflater#needsInput()
+ */
+ public void test_needsInput() {
+ // test method of java.util.zip.inflater.needsInput()
+ Inflater inflate = new Inflater();
+ assertTrue(
+ "needsInput give the wrong boolean value as a result of no input buffer",
+ inflate.needsInput());
+
+ byte byteArray[] = { 2, 3, 4, 't', 'y', 'u', 'e', 'w', 7, 6, 5, 9 };
+ inflate.setInput(byteArray);
+ assertFalse(
+ "methodNeedsInput returned true when the input buffer is full",
+ inflate.needsInput());
+
+ inflate.reset();
+ byte byteArrayEmpty[] = new byte[0];
+ inflate.setInput(byteArrayEmpty);
+ assertTrue(
+ "needsInput give wrong boolean value as a result of an empty input buffer",
+ inflate.needsInput());
+ }
+
+ /**
+ * @tests java.util.zip.Inflater#reset()
+ */
+ public void test_reset() {
+ // test method of java.util.zip.inflater.reset()
+ byte byteArray[] = { 1, 3, 4, 7, 8, 'e', 'r', 't', 'y', '5' };
+ byte outPutInf[] = new byte[100];
+ int y = 0;
+ Inflater inflate = new Inflater();
+ try {
+ while (!(inflate.finished())) {
+ if (inflate.needsInput()) {
+ inflate.setInput(outPutBuff1);
+ }
+ y += inflate.inflate(outPutInf, y, outPutInf.length - y);
+ }
+ } catch (DataFormatException e) {
+ fail("Invalid input to be decompressed");
+ }
+ for (int i = 0; i < byteArray.length; i++) {
+ assertTrue(
+ "Final decompressed data does not equal the original data",
+ byteArray[i] == outPutInf[i]);
+ }
+ assertEquals("final decompressed data contained more bytes than original - reset",
+ 0, outPutInf[byteArray.length]);
+
+ // testing that resetting the inflater will also return the correct
+ // decompressed data
+
+ inflate.reset();
+ try {
+ while (!(inflate.finished())) {
+ if (inflate.needsInput()) {
+ inflate.setInput(outPutBuff1);
+ }
+ inflate.inflate(outPutInf);
+ }
+ } catch (DataFormatException e) {
+ fail("Invalid input to be decompressed");
+ }
+ for (int i = 0; i < byteArray.length; i++) {
+ assertTrue(
+ "Final decompressed data does not equal the original data",
+ byteArray[i] == outPutInf[i]);
+ }
+ assertEquals("final decompressed data contained more bytes than original - reset",
+ 0, outPutInf[byteArray.length]);
+
+ }
+
+ /**
+ * @tests java.util.zip.Inflater#setDictionary(byte[])
+ */
+ public void test_setDictionary$B() {
+ //FIXME This test doesn't pass in Harmony classlib or Sun 5.0_7 RI
+ /*
+ // test method of java.util.zip.inflater.setDictionary(byte)
+ byte dictionaryArray[] = { 'e', 'r', 't', 'a', 'b', 2, 3 };
+ byte byteArray[] = { 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3',
+ 'w', 'r' };
+
+ byte outPutInf[] = new byte[100];
+
+ // trying to inflate without setting a dictionary
+
+ Inflater inflateWO = new Inflater();
+ byte outPutInf2[] = new byte[100];
+ int r = 0;
+ try {
+ while (!(inflateWO.finished())) {
+ if (inflateWO.needsInput()) {
+ inflateWO.setInput(outPutDiction);
+ }
+ inflateWO.inflate(outPutInf2);
+ }
+ } catch (DataFormatException e) {
+ r = 1;
+ }
+ assertEquals("invalid input to be decompressed due to dictionary not set",
+ 1, r);
+ // now setting the dictionary in inflater
+ Inflater inflate = new Inflater();
+ try {
+ while (!(inflate.finished())) {
+ if (inflate.needsInput()) {
+ inflate.setInput(outPutDiction);
+ }
+ if (inflate.needsDictionary()) {
+ inflate.setDictionary(dictionaryArray);
+ }
+ inflate.inflate(outPutInf);
+ }
+ } catch (DataFormatException e) {
+ fail("Invalid input to be decompressed");
+ }
+ for (int i = 0; i < byteArray.length; i++) {
+ assertTrue(
+ "Final decompressed data does not equal the original data",
+ byteArray[i] == outPutInf[i]);
+ }
+ assertEquals("final decompressed data contained more bytes than original - deflateB",
+ 0, outPutInf[byteArray.length]);
+ */
+ }
+
+ /**
+ * @tests java.util.zip.Inflater#setInput(byte[])
+ */
+ public void test_setInput$B() {
+ // test method of java.util.zip.inflater.setInput(byte)
+ byte byteArray[] = { 2, 3, 4, 't', 'y', 'u', 'e', 'w', 7, 6, 5, 9 };
+ Inflater inflate = new Inflater();
+ inflate.setInput(byteArray);
+ assertTrue("setInputB did not deliver any byte to the input buffer",
+ inflate.getRemaining() != 0);
+ }
+
+ /**
+ * @tests java.util.zip.Inflater#setInput(byte[], int, int)
+ */
+ public void test_setInput$BII() {
+ // test method of java.util.zip.inflater.setInput(byte,int,int)
+ byte byteArray[] = { 2, 3, 4, 't', 'y', 'u', 'e', 'w', 7, 6, 5, 9 };
+ int offSet = 6;
+ int length = 6;
+ Inflater inflate = new Inflater();
+ inflate.setInput(byteArray, offSet, length);
+ assertTrue(
+ "setInputBII did not deliver the right number of bytes to the input buffer",
+ inflate.getRemaining() == length);
+ // boundary check
+ inflate.reset();
+ int r = 0;
+ try {
+ inflate.setInput(byteArray, 100, 100);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ r = 1;
+ }
+ assertEquals("boundary check is not present for setInput", 1, r);
+ }
+
+ @Override
protected void setUp() {
- try {
- java.io.InputStream infile = Support_Resources
- .getStream("hyts_compressD.txt");
- BufferedInputStream inflatIP = new BufferedInputStream(infile);
- inflatIP.read(outPutBuff1, 0, outPutBuff1.length);
- inflatIP.close();
-
- java.io.InputStream infile2 = Support_Resources
- .getStream("hyts_compDiction.txt");
- BufferedInputStream inflatIP2 = new BufferedInputStream(infile2);
- inflatIP2.read(outPutDiction, 0, outPutDiction.length);
- inflatIP2.close();
-
- } catch (FileNotFoundException e) {
- fail("input file to test InflaterInputStream constructor is not found");
- } catch (ZipException e) {
- fail("read() threw an zip exception while testing constructor");
- } catch (IOException e) {
- fail("read() threw an exception while testing constructor");
- }
- }
-
- @Override
+ try {
+ java.io.InputStream infile = Support_Resources
+ .getStream("hyts_compressD.txt");
+ BufferedInputStream inflatIP = new BufferedInputStream(infile);
+ inflatIP.read(outPutBuff1, 0, outPutBuff1.length);
+ inflatIP.close();
+
+ java.io.InputStream infile2 = Support_Resources
+ .getStream("hyts_compDiction.txt");
+ BufferedInputStream inflatIP2 = new BufferedInputStream(infile2);
+ inflatIP2.read(outPutDiction, 0, outPutDiction.length);
+ inflatIP2.close();
+
+ } catch (FileNotFoundException e) {
+ fail(
+ "input file to test InflaterInputStream constructor is not found");
+ } catch (ZipException e) {
+ fail(
+ "read() threw an zip exception while testing constructor");
+ } catch (IOException e) {
+ fail("read() threw an exception while testing constructor");
+ }
+ }
+
+ @Override
protected void tearDown() {
- }
-
+ }
+
/**
* @tests java.util.zip.Deflater#getBytesRead()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBytesRead",
- args = {}
- )
public void test_getBytesRead() throws DataFormatException,
UnsupportedEncodingException {
// Regression test for HARMONY-158
@@ -802,23 +736,16 @@ public class InflaterTest extends junit.framework.TestCase {
def.finish();
def.deflate(output);
inf.setInput(output);
- int compressedDataLength = inf.inflate(input);
+ int compressedDataLength =inf.inflate(input);
assertEquals(16, inf.getTotalIn());
assertEquals(compressedDataLength, inf.getTotalOut());
assertEquals(16, inf.getBytesRead());
}
-
+
/**
* @tests java.util.zip.Deflater#getBytesRead()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBytesWritten",
- args = {}
- )
- public void test_getBytesWritten() throws DataFormatException,
- UnsupportedEncodingException {
+ public void test_getBytesWritten() throws DataFormatException, UnsupportedEncodingException {
// Regression test for HARMONY-158
Deflater def = new Deflater();
Inflater inf = new Inflater();
@@ -835,7 +762,7 @@ public class InflaterTest extends junit.framework.TestCase {
def.finish();
def.deflate(output);
inf.setInput(output);
- int compressedDataLength = inf.inflate(input);
+ int compressedDataLength =inf.inflate(input);
assertEquals(16, inf.getTotalIn());
assertEquals(compressedDataLength, inf.getTotalOut());
assertEquals(14, inf.getBytesWritten());
@@ -844,14 +771,8 @@ public class InflaterTest extends junit.framework.TestCase {
/**
* @tests java.util.zip.Deflater#inflate(byte[], int, int)
*/
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test",
- method = "inflate",
- args = {byte[].class, int.class, int.class}
- )
public void testInflate() throws Exception {
- // Regression for HARMONY-81
+ // Regression for HARMONY-81
Inflater inf = new Inflater();
int res = inf.inflate(new byte[0], 0, 0);
@@ -862,30 +783,32 @@ public class InflaterTest extends junit.framework.TestCase {
byte[] b = new byte[1024];
assertEquals(0, inflater.inflate(b));
inflater.end();
- }
- /**
- * @tests java.util.zip.Deflater#inflate(byte[], int, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Can not be checked. Should be tested in DX test package.",
- method = "finalize",
- args = {}
- )
- public void testFinalize() throws Exception {
+ // Regression for HARMONY-2510
+ inflater = new Inflater();
+ inflater.setInput(new byte[] { -1 });
+ try {
+ inflater.inflate(b);
+
+ // The RI detects malformed data on the malformed input { -1 }. Both
+ // this implementation and the native zlib API return "need input"
+ // on that data. This is an error if the stream is exhausted, but
+ // not one that results in an exception in the Inflater API.
+ assertTrue(inflater.needsInput());
+ } catch (DataFormatException e) {
+ // expected
+ }
+
+ inflater = new Inflater();
+ inflater.setInput(new byte[] { -1, -1, -1 });
+ try {
+ inflater.inflate(b);
+ } catch (DataFormatException e) {
+ // expected
+ }
}
- /**
- * @tests java.util.zip.Inflater#setDictionary(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Checks setDictionary. Can be splitted for 2 separate tests for Deflater & Inflater. Can be used as a base for setDictionary with additional params.",
- method = "setDictionary",
- args = {byte[].class}
- )
- public void testsetDictionary$B() throws Exception {
+ public void testSetDictionary$B() throws Exception {
int i = 0;
String inputString = "blah string contains blahblahblahblah and blah";
String dictionary1 = "blah";
@@ -1003,16 +926,7 @@ public class InflaterTest extends junit.framework.TestCase {
infl1.end();
}
- /**
- * @tests java.util.zip.Inflater#setDictionary(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Checks setDictionary. Can be splitted for 2 separate tests for Deflater & Inflater. Can be used as a base for setDictionary with additional params.",
- method = "setDictionary",
- args = {byte[].class, int.class, int.class}
- )
- public void testsetDictionary$BII() throws Exception {
+ public void testSetDictionary$BII() throws Exception {
int i = 0;
String inputString = "blah string contains blahblahblahblah and blah";
String dictionary1 = "blah";
@@ -1113,4 +1027,5 @@ public class InflaterTest extends junit.framework.TestCase {
assertEquals(inputString, new String(result, 0, decLen));
}
+
}
diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipEntryTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipEntryTest.java
index ee7aceb..be5d0c6 100644
--- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipEntryTest.java
+++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipEntryTest.java
@@ -14,27 +14,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.harmony.archive.tests.java.util.zip;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import tests.support.resource.Support_Resources;
-
+import java.util.TimeZone;
+import java.util.zip.ZipEntry;
import java.io.ByteArrayOutputStream;
-import java.io.File;
import java.io.IOException;
import java.io.InputStream;
-import java.util.TimeZone;
-import java.util.zip.ZipEntry;
-@TestTargetClass(ZipEntry.class)
+import tests.support.resource.Support_Resources;
+
public class ZipEntryTest extends junit.framework.TestCase {
- // BEGIN android-added
public byte[] getAllBytesFromStream(InputStream is) throws IOException {
ByteArrayOutputStream bs = new ByteArrayOutputStream();
byte[] buf = new byte[512];
@@ -47,601 +38,463 @@ public class ZipEntryTest extends junit.framework.TestCase {
return bs.toByteArray();
}
- // END android-added
-
- // zip file hyts_ZipFile.zip must be included as a resource
- java.util.zip.ZipEntry zentry;
-
- java.util.zip.ZipFile zfile;
-
- private static final String platformId = System.getProperty(
- "com.ibm.oti.configuration", "JDK")
- + System.getProperty("java.vm.version");
-
- static final String tempFileName = platformId + "zipentrytest.zip";
-
- long orgSize;
-
- long orgCompressedSize;
-
- long orgCrc;
-
- long orgTime;
-
- String orgComment;
-
- /**
- * @tests java.util.zip.ZipEntry#ZipEntry(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ZipEntry",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.util.zip.ZipEntry(java.lang.String)
- zentry = zfile.getEntry("File3.txt");
- assertNotNull("Failed to create ZipEntry", zentry);
- try {
- zentry = zfile.getEntry(null);
- fail("NullPointerException not thrown");
- } catch (NullPointerException e) {
- }
- StringBuffer s = new StringBuffer();
- for (int i = 0; i < 65535; i++) {
- s.append('a');
- }
- try {
- zentry = new ZipEntry(s.toString());
- } catch (IllegalArgumentException e) {
- fail("Unexpected IllegalArgumentException During Test.");
- }
- try {
- s.append('a');
- zentry = new ZipEntry(s.toString());
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- }
- try {
- String n = null;
- zentry = new ZipEntry(n);
- fail("NullPointerException not thrown");
- } catch (NullPointerException e) {
- }
- }
-
- /**
- * @tests java.util.zip.ZipEntry#getComment()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getComment",
- args = {}
- )
- public void test_getComment() {
- // Test for method java.lang.String java.util.zip.ZipEntry.getComment()
- ZipEntry zipEntry = new ZipEntry("zippy.zip");
- assertNull("Incorrect Comment Returned.", zipEntry.getComment());
- zipEntry.setComment("This Is A Comment");
- assertEquals("Incorrect Comment Returned.", "This Is A Comment",
- zipEntry.getComment());
- }
+ // zip file hyts_ZipFile.zip must be included as a resource
+ java.util.zip.ZipEntry zentry;
- /**
- * @tests java.util.zip.ZipEntry#getCompressedSize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCompressedSize",
- args = {}
- )
- public void test_getCompressedSize() {
- // Test for method long java.util.zip.ZipEntry.getCompressedSize()
- assertTrue("Incorrect compressed size returned", zentry
- .getCompressedSize() == orgCompressedSize);
- }
+ java.util.zip.ZipFile zfile;
- /**
- * @tests java.util.zip.ZipEntry#getCrc()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCrc",
- args = {}
- )
- public void test_getCrc() {
- // Test for method long java.util.zip.ZipEntry.getCrc()
- assertTrue("Failed to get Crc", zentry.getCrc() == orgCrc);
- }
+ private static final String platformId = System.getProperty(
+ "com.ibm.oti.configuration", "JDK")
+ + System.getProperty("java.vm.version");
- /**
- * @tests java.util.zip.ZipEntry#getExtra()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getExtra",
- args = {}
- )
- public void test_getExtra() {
- // Test for method byte [] java.util.zip.ZipEntry.getExtra()
- assertNull("Incorrect extra information returned", zentry.getExtra());
- byte[] ba = {'T', 'E', 'S', 'T'};
- zentry = new ZipEntry("test.tst");
- zentry.setExtra(ba);
- assertTrue("Incorrect Extra Information Returned.",
- zentry.getExtra() == ba);
- }
+ static final String tempFileName = platformId + "zfzezi.zip";
- /**
- * @tests java.util.zip.ZipEntry#getMethod()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMethod",
- args = {}
- )
- public void test_getMethod() {
- // Test for method int java.util.zip.ZipEntry.getMethod()
- zentry = zfile.getEntry("File1.txt");
- assertTrue("Incorrect compression method returned",
- zentry.getMethod() == java.util.zip.ZipEntry.STORED);
- zentry = zfile.getEntry("File3.txt");
- assertTrue("Incorrect compression method returned",
- zentry.getMethod() == java.util.zip.ZipEntry.DEFLATED);
- zentry = new ZipEntry("test.tst");
- assertEquals("Incorrect Method Returned.", -1, zentry.getMethod());
- }
+ long orgSize;
- /**
- * @tests java.util.zip.ZipEntry#getName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getName",
- args = {}
- )
- public void test_getName() {
- // Test for method java.lang.String java.util.zip.ZipEntry.getName()
- assertEquals(
- "Incorrect name returned - Note return result somewhat ambiguous in spec",
- "File1.txt", zentry.getName());
- }
+ long orgCompressedSize;
- /**
- * @tests java.util.zip.ZipEntry#getSize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSize",
- args = {}
- )
- public void test_getSize() {
- // Test for method long java.util.zip.ZipEntry.getSize()
- assertTrue("Incorrect size returned", zentry.getSize() == orgSize);
- }
+ long orgCrc;
- /**
- * @tests java.util.zip.ZipEntry#getTime()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTime",
- args = {}
- )
- public void test_getTime() {
- // Test for method long java.util.zip.ZipEntry.getTime()
- assertTrue("Failed to get time", zentry.getTime() == orgTime);
- }
+ long orgTime;
- /**
- * @tests java.util.zip.ZipEntry#isDirectory()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isDirectory",
- args = {}
- )
- public void test_isDirectory() {
- // Test for method boolean java.util.zip.ZipEntry.isDirectory()
- assertTrue("Entry should not answer true to isDirectory", !zentry
- .isDirectory());
- zentry = new ZipEntry("Directory/");
- assertTrue("Entry should answer true to isDirectory", zentry
- .isDirectory());
- }
+ String orgComment;
- /**
- * @tests java.util.zip.ZipEntry#setComment(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setComment",
- args = {java.lang.String.class}
- )
- public void test_setCommentLjava_lang_String() {
- // Test for method void
- // java.util.zip.ZipEntry.setComment(java.lang.String)
- zentry = zfile.getEntry("File1.txt");
- zentry.setComment("Set comment using api");
- assertEquals("Comment not correctly set", "Set comment using api",
- zentry.getComment());
- String n = null;
- zentry.setComment(n);
- assertNull("Comment not correctly set", zentry.getComment());
- StringBuffer s = new StringBuffer();
- for (int i = 0; i < 0xFFFF; i++) {
+ /**
+ * @tests java.util.zip.ZipEntry#ZipEntry(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method java.util.zip.ZipEntry(java.lang.String)
+ zentry = zfile.getEntry("File3.txt");
+ assertNotNull("Failed to create ZipEntry", zentry);
+ try {
+ zentry = zfile.getEntry(null);
+ fail("NullPointerException not thrown");
+ } catch (NullPointerException e) {
+ }
+ StringBuffer s = new StringBuffer();
+ for (int i = 0; i < 65535; i++) {
s.append('a');
}
- try {
- zentry.setComment(s.toString());
- } catch (IllegalArgumentException e) {
- fail("Unexpected IllegalArgumentException During Test.");
- }
- try {
+ try {
+ zentry = new ZipEntry(s.toString());
+ } catch (IllegalArgumentException e) {
+ fail("Unexpected IllegalArgumentException During Test.");
+ }
+ try {
+ s.append('a');
+ zentry = new ZipEntry(s.toString());
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ String n = null;
+ zentry = new ZipEntry(n);
+ fail("NullPointerException not thrown");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /**
+ * @tests java.util.zip.ZipEntry#getComment()
+ */
+ public void test_getComment() {
+ // Test for method java.lang.String java.util.zip.ZipEntry.getComment()
+ ZipEntry zipEntry = new ZipEntry("zippy.zip");
+ assertNull("Incorrect Comment Returned.", zipEntry.getComment());
+ zipEntry.setComment("This Is A Comment");
+ assertEquals("Incorrect Comment Returned.",
+ "This Is A Comment", zipEntry.getComment());
+ }
+
+ /**
+ * @tests java.util.zip.ZipEntry#getCompressedSize()
+ */
+ public void test_getCompressedSize() {
+ // Test for method long java.util.zip.ZipEntry.getCompressedSize()
+ assertTrue("Incorrect compressed size returned", zentry
+ .getCompressedSize() == orgCompressedSize);
+ }
+
+ /**
+ * @tests java.util.zip.ZipEntry#getCrc()
+ */
+ public void test_getCrc() {
+ // Test for method long java.util.zip.ZipEntry.getCrc()
+ assertTrue("Failed to get Crc", zentry.getCrc() == orgCrc);
+ }
+
+ /**
+ * @tests java.util.zip.ZipEntry#getExtra()
+ */
+ public void test_getExtra() {
+ // Test for method byte [] java.util.zip.ZipEntry.getExtra()
+ assertNull("Incorrect extra information returned",
+ zentry.getExtra());
+ byte[] ba = { 'T', 'E', 'S', 'T' };
+ zentry = new ZipEntry("test.tst");
+ zentry.setExtra(ba);
+ assertTrue("Incorrect Extra Information Returned.",
+ zentry.getExtra() == ba);
+ }
+
+ /**
+ * @tests java.util.zip.ZipEntry#getMethod()
+ */
+ public void test_getMethod() {
+ // Test for method int java.util.zip.ZipEntry.getMethod()
+ zentry = zfile.getEntry("File1.txt");
+ assertTrue("Incorrect compression method returned",
+ zentry.getMethod() == java.util.zip.ZipEntry.STORED);
+ zentry = zfile.getEntry("File3.txt");
+ assertTrue("Incorrect compression method returned",
+ zentry.getMethod() == java.util.zip.ZipEntry.DEFLATED);
+ zentry = new ZipEntry("test.tst");
+ assertEquals("Incorrect Method Returned.", -1, zentry.getMethod());
+ }
+
+ /**
+ * @tests java.util.zip.ZipEntry#getName()
+ */
+ public void test_getName() {
+ // Test for method java.lang.String java.util.zip.ZipEntry.getName()
+ assertEquals("Incorrect name returned - Note return result somewhat ambiguous in spec",
+ "File1.txt", zentry.getName());
+ }
+
+ /**
+ * @tests java.util.zip.ZipEntry#getSize()
+ */
+ public void test_getSize() {
+ // Test for method long java.util.zip.ZipEntry.getSize()
+ assertTrue("Incorrect size returned", zentry.getSize() == orgSize);
+ }
+
+ /**
+ * @tests java.util.zip.ZipEntry#getTime()
+ */
+ public void test_getTime() {
+ // Test for method long java.util.zip.ZipEntry.getTime()
+ assertTrue("Failed to get time", zentry.getTime() == orgTime);
+ }
+
+ /**
+ * @tests java.util.zip.ZipEntry#isDirectory()
+ */
+ public void test_isDirectory() {
+ // Test for method boolean java.util.zip.ZipEntry.isDirectory()
+ assertTrue("Entry should not answer true to isDirectory", !zentry
+ .isDirectory());
+ zentry = new ZipEntry("Directory/");
+ assertTrue("Entry should answer true to isDirectory", zentry
+ .isDirectory());
+ }
+
+ /**
+ * @tests java.util.zip.ZipEntry#setComment(java.lang.String)
+ */
+ public void test_setCommentLjava_lang_String() {
+ // Test for method void
+ // java.util.zip.ZipEntry.setComment(java.lang.String)
+ zentry = zfile.getEntry("File1.txt");
+ zentry.setComment("Set comment using api");
+ assertEquals("Comment not correctly set",
+ "Set comment using api", zentry.getComment());
+ String n = null;
+ zentry.setComment(n);
+ assertNull("Comment not correctly set", zentry.getComment());
+ StringBuffer s = new StringBuffer();
+ for (int i = 0; i < 0xFFFF; i++) {
s.append('a');
- zentry.setComment(s.toString());
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- }
- }
-
- /**
- * @tests java.util.zip.ZipEntry#setCompressedSize(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setCompressedSize",
- args = {long.class}
- )
- public void test_setCompressedSizeJ() {
- // Test for method void java.util.zip.ZipEntry.setCompressedSize(long)
- zentry.setCompressedSize(orgCompressedSize + 10);
- assertTrue("Set compressed size failed",
- zentry.getCompressedSize() == (orgCompressedSize + 10));
- zentry.setCompressedSize(0);
- assertEquals("Set compressed size failed", 0, zentry
- .getCompressedSize());
- zentry.setCompressedSize(-25);
- assertEquals("Set compressed size failed", -25, zentry
- .getCompressedSize());
- zentry.setCompressedSize(4294967296l);
- assertTrue("Set compressed size failed",
- zentry.getCompressedSize() == 4294967296l);
- }
-
- /**
- * @tests java.util.zip.ZipEntry#setCrc(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setCrc",
- args = {long.class}
- )
- public void test_setCrcJ() {
- // Test for method void java.util.zip.ZipEntry.setCrc(long)
- zentry.setCrc(orgCrc + 100);
- assertTrue("Failed to set Crc", zentry.getCrc() == (orgCrc + 100));
- zentry.setCrc(0);
- assertEquals("Failed to set Crc", 0, zentry.getCrc());
- try {
- zentry.setCrc(-25);
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- }
- try {
- zentry.setCrc(4294967295l);
- } catch (IllegalArgumentException e) {
- fail("Unexpected IllegalArgumentException during test");
- }
- try {
- zentry.setCrc(4294967296l);
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- }
- }
-
- /**
- * @tests java.util.zip.ZipEntry#setExtra(byte[])
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setExtra",
- args = {byte[].class}
- )
- public void test_setExtra$B() {
- // Test for method void java.util.zip.ZipEntry.setExtra(byte [])
- zentry = zfile.getEntry("File1.txt");
- zentry.setExtra("Test setting extra information".getBytes());
- assertEquals("Extra information not written properly",
- "Test setting extra information", new String(zentry.getExtra(),
- 0, zentry.getExtra().length));
- zentry = new ZipEntry("test.tst");
- byte[] ba = new byte[0xFFFF];
- try {
- zentry.setExtra(ba);
- } catch (IllegalArgumentException e) {
- fail("Unexpected IllegalArgumentException during test");
- }
- try {
- ba = new byte[0xFFFF + 1];
- zentry.setExtra(ba);
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- }
-
- // One constructor
- ZipEntry zeInput = new ZipEntry("InputZIP");
- byte[] extraB = {'a', 'b', 'd', 'e'};
- zeInput.setExtra(extraB);
- assertEquals(extraB, zeInput.getExtra());
- assertEquals(extraB[3], zeInput.getExtra()[3]);
- assertEquals(extraB.length, zeInput.getExtra().length);
-
- // test another constructor
- ZipEntry zeOutput = new ZipEntry(zeInput);
- assertEquals(zeInput.getExtra()[3], zeOutput.getExtra()[3]);
- assertEquals(zeInput.getExtra().length, zeOutput.getExtra().length);
- assertEquals(extraB[3], zeOutput.getExtra()[3]);
- assertEquals(extraB.length, zeOutput.getExtra().length);
- }
-
- /**
- * @tests java.util.zip.ZipEntry#setMethod(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setMethod",
- args = {int.class}
- )
- public void test_setMethodI() {
- // Test for method void java.util.zip.ZipEntry.setMethod(int)
- zentry = zfile.getEntry("File3.txt");
- zentry.setMethod(ZipEntry.STORED);
- assertTrue("Failed to set compression method",
- zentry.getMethod() == ZipEntry.STORED);
- zentry.setMethod(ZipEntry.DEFLATED);
- assertTrue("Failed to set compression method",
- zentry.getMethod() == ZipEntry.DEFLATED);
- try {
- int error = 1;
- zentry = new ZipEntry("test.tst");
- zentry.setMethod(error);
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- }
- }
-
- /**
- * @tests java.util.zip.ZipEntry#setSize(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setSize",
- args = {long.class}
- )
- public void test_setSizeJ() {
- // Test for method void java.util.zip.ZipEntry.setSize(long)
- zentry.setSize(orgSize + 10);
- assertTrue("Set size failed", zentry.getSize() == (orgSize + 10));
- zentry.setSize(0);
- assertEquals("Set size failed", 0, zentry.getSize());
- try {
- zentry.setSize(-25);
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- }
- try {
- zentry.setCrc(4294967295l);
- } catch (IllegalArgumentException e) {
- fail("Unexpected IllegalArgumentException during test");
- }
- try {
- zentry.setCrc(4294967296l);
- fail("IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- }
- }
-
- /**
- * @tests java.util.zip.ZipEntry#setTime(long)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setTime",
- args = {long.class}
- )
- public void test_setTimeJ() {
- // Test for method void java.util.zip.ZipEntry.setTime(long)
- zentry.setTime(orgTime + 10000);
- assertTrue("Test 1: Failed to set time: " + zentry.getTime(), zentry
- .getTime() == (orgTime + 10000));
- zentry.setTime(orgTime - 10000);
- assertTrue("Test 2: Failed to set time: " + zentry.getTime(), zentry
- .getTime() == (orgTime - 10000));
- TimeZone zone = TimeZone.getDefault();
- try {
- TimeZone.setDefault(TimeZone.getTimeZone("EST"));
- zentry.setTime(0);
- assertTrue("Test 3: Failed to set time: " + zentry.getTime(),
- zentry.getTime() == 315550800000L);
- TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
- assertTrue("Test 3a: Failed to set time: " + zentry.getTime(),
- zentry.getTime() == 315532800000L);
- zentry.setTime(0);
- TimeZone.setDefault(TimeZone.getTimeZone("EST"));
- assertTrue("Test 3b: Failed to set time: " + zentry.getTime(),
- zentry.getTime() == 315550800000L);
-
- zentry.setTime(-25);
- assertTrue("Test 4: Failed to set time: " + zentry.getTime(),
- zentry.getTime() == 315550800000L);
- zentry.setTime(4354837200000L);
- assertTrue("Test 5: Failed to set time: " + zentry.getTime(),
- zentry.getTime() == 315550800000L);
- } finally {
- TimeZone.setDefault(zone);
- }
- }
-
- /**
- * @tests java.util.zip.ZipEntry#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- // Test for method java.lang.String java.util.zip.ZipEntry.toString()
- assertTrue("Returned incorrect entry name", zentry.toString().indexOf(
- "File1.txt") >= 0);
- }
-
- /**
- * @tests java.util.zip.ZipEntry#ZipEntry(java.util.zip.ZipEntry)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ZipEntry",
- args = {java.util.zip.ZipEntry.class}
- )
- public void test_ConstructorLjava_util_zip_ZipEntry() {
- // Test for method java.util.zip.ZipEntry(util.zip.ZipEntry)
- zentry.setSize(2);
- zentry.setCompressedSize(4);
- zentry.setComment("Testing");
- ZipEntry zentry2 = new ZipEntry(zentry);
- assertEquals("ZipEntry Created With Incorrect Size.", 2, zentry2
- .getSize());
- assertEquals("ZipEntry Created With Incorrect Compressed Size.", 4,
- zentry2.getCompressedSize());
- assertEquals("ZipEntry Created With Incorrect Comment.", "Testing",
- zentry2.getComment());
- assertTrue("ZipEntry Created With Incorrect Crc.",
- zentry2.getCrc() == orgCrc);
- assertTrue("ZipEntry Created With Incorrect Time.",
- zentry2.getTime() == orgTime);
- }
-
- /**
- * @tests java.util.zip.ZipEntry#clone()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "clone",
- args = {}
- )
- public void test_clone() {
- // Test for method java.util.zip.ZipEntry.clone()
- Object obj = zentry.clone();
- assertTrue("toString()", obj.toString().equals(zentry.toString()));
- assertTrue("hashCode()", obj.hashCode() == zentry.hashCode());
-
- // One constructor
- ZipEntry zeInput = new ZipEntry("InputZIP");
- byte[] extraB = {'a', 'b', 'd', 'e'};
- zeInput.setExtra(extraB);
- assertEquals(extraB, zeInput.getExtra());
- assertEquals(extraB[3], zeInput.getExtra()[3]);
- assertEquals(extraB.length, zeInput.getExtra().length);
-
- // test Clone()
- ZipEntry zeOutput = (ZipEntry) zeInput.clone();
- assertEquals(zeInput.getExtra()[3], zeOutput.getExtra()[3]);
- assertEquals(zeInput.getExtra().length, zeOutput.getExtra().length);
- assertEquals(extraB[3], zeOutput.getExtra()[3]);
- assertEquals(extraB.length, zeOutput.getExtra().length);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- try {
- zentry.hashCode();
- } catch (Exception ee) {
- fail("Unexpected exception " + ee);
}
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
-
- @Override
+ try {
+ zentry.setComment(s.toString());
+ } catch (IllegalArgumentException e) {
+ fail("Unexpected IllegalArgumentException During Test.");
+ }
+ try {
+ s.append('a');
+ zentry.setComment(s.toString());
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * @tests java.util.zip.ZipEntry#setCompressedSize(long)
+ */
+ public void test_setCompressedSizeJ() {
+ // Test for method void java.util.zip.ZipEntry.setCompressedSize(long)
+ zentry.setCompressedSize(orgCompressedSize + 10);
+ assertTrue("Set compressed size failed",
+ zentry.getCompressedSize() == (orgCompressedSize + 10));
+ zentry.setCompressedSize(0);
+ assertEquals("Set compressed size failed",
+ 0, zentry.getCompressedSize());
+ zentry.setCompressedSize(-25);
+ assertEquals("Set compressed size failed",
+ -25, zentry.getCompressedSize());
+ zentry.setCompressedSize(4294967296l);
+ assertTrue("Set compressed size failed",
+ zentry.getCompressedSize() == 4294967296l);
+ }
+
+ /**
+ * @tests java.util.zip.ZipEntry#setCrc(long)
+ */
+ public void test_setCrcJ() {
+ // Test for method void java.util.zip.ZipEntry.setCrc(long)
+ zentry.setCrc(orgCrc + 100);
+ assertTrue("Failed to set Crc", zentry.getCrc() == (orgCrc + 100));
+ zentry.setCrc(0);
+ assertEquals("Failed to set Crc", 0, zentry.getCrc());
+ try {
+ zentry.setCrc(-25);
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ zentry.setCrc(4294967295l);
+ } catch (IllegalArgumentException e) {
+ fail("Unexpected IllegalArgumentException during test");
+ }
+ try {
+ zentry.setCrc(4294967296l);
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * @tests java.util.zip.ZipEntry#setExtra(byte[])
+ */
+ public void test_setExtra$B() {
+ // Test for method void java.util.zip.ZipEntry.setExtra(byte [])
+ zentry = zfile.getEntry("File1.txt");
+ zentry.setExtra("Test setting extra information".getBytes());
+ assertEquals("Extra information not written properly", "Test setting extra information", new String(zentry
+ .getExtra(), 0, zentry.getExtra().length)
+ );
+ zentry = new ZipEntry("test.tst");
+ byte[] ba = new byte[0xFFFF];
+ try {
+ zentry.setExtra(ba);
+ } catch (IllegalArgumentException e) {
+ fail("Unexpected IllegalArgumentException during test");
+ }
+ try {
+ ba = new byte[0xFFFF + 1];
+ zentry.setExtra(ba);
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
+ }
+
+ // One constructor
+ ZipEntry zeInput = new ZipEntry("InputZIP");
+ byte[] extraB = { 'a', 'b', 'd', 'e' };
+ zeInput.setExtra(extraB);
+ assertEquals(extraB, zeInput.getExtra());
+ assertEquals(extraB[3], zeInput.getExtra()[3]);
+ assertEquals(extraB.length, zeInput.getExtra().length);
+
+ // test another constructor
+ ZipEntry zeOutput = new ZipEntry(zeInput);
+ assertEquals(zeInput.getExtra()[3], zeOutput.getExtra()[3]);
+ assertEquals(zeInput.getExtra().length, zeOutput.getExtra().length);
+ assertEquals(extraB[3], zeOutput.getExtra()[3]);
+ assertEquals(extraB.length, zeOutput.getExtra().length);
+ }
+
+ /**
+ * @tests java.util.zip.ZipEntry#setMethod(int)
+ */
+ public void test_setMethodI() {
+ // Test for method void java.util.zip.ZipEntry.setMethod(int)
+ zentry = zfile.getEntry("File3.txt");
+ zentry.setMethod(ZipEntry.STORED);
+ assertTrue("Failed to set compression method",
+ zentry.getMethod() == ZipEntry.STORED);
+ zentry.setMethod(ZipEntry.DEFLATED);
+ assertTrue("Failed to set compression method",
+ zentry.getMethod() == ZipEntry.DEFLATED);
+ try {
+ int error = 1;
+ zentry = new ZipEntry("test.tst");
+ zentry.setMethod(error);
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * @tests java.util.zip.ZipEntry#setSize(long)
+ */
+ public void test_setSizeJ() {
+ // Test for method void java.util.zip.ZipEntry.setSize(long)
+ zentry.setSize(orgSize + 10);
+ assertTrue("Set size failed", zentry.getSize() == (orgSize + 10));
+ zentry.setSize(0);
+ assertEquals("Set size failed", 0, zentry.getSize());
+ try {
+ zentry.setSize(-25);
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ zentry.setCrc(4294967295l);
+ } catch (IllegalArgumentException e) {
+ fail("Unexpected IllegalArgumentException during test");
+ }
+ try {
+ zentry.setCrc(4294967296l);
+ fail("IllegalArgumentException not thrown");
+ } catch (IllegalArgumentException e) {
+ }
+ }
+
+ /**
+ * @tests java.util.zip.ZipEntry#setTime(long)
+ */
+ public void test_setTimeJ() {
+ // Test for method void java.util.zip.ZipEntry.setTime(long)
+ zentry.setTime(orgTime + 10000);
+ assertTrue("Test 1: Failed to set time: " + zentry.getTime(), zentry
+ .getTime() == (orgTime + 10000));
+ zentry.setTime(orgTime - 10000);
+ assertTrue("Test 2: Failed to set time: " + zentry.getTime(), zentry
+ .getTime() == (orgTime - 10000));
+ TimeZone zone = TimeZone.getDefault();
+ try {
+ TimeZone.setDefault(TimeZone.getTimeZone("EST"));
+ zentry.setTime(0);
+ assertTrue("Test 3: Failed to set time: " + zentry.getTime(),
+ zentry.getTime() == 315550800000L);
+ TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
+ assertTrue("Test 3a: Failed to set time: " + zentry.getTime(),
+ zentry.getTime() == 315532800000L);
+ zentry.setTime(0);
+ TimeZone.setDefault(TimeZone.getTimeZone("EST"));
+ assertTrue("Test 3b: Failed to set time: " + zentry.getTime(),
+ zentry.getTime() == 315550800000L);
+
+ zentry.setTime(-25);
+ assertTrue("Test 4: Failed to set time: " + zentry.getTime(),
+ zentry.getTime() == 315550800000L);
+ zentry.setTime(4354837200000L);
+ assertTrue("Test 5: Failed to set time: " + zentry.getTime(),
+ zentry.getTime() == 315550800000L);
+ } finally {
+ TimeZone.setDefault(zone);
+ }
+ }
+
+ /**
+ * @tests java.util.zip.ZipEntry#toString()
+ */
+ public void test_toString() {
+ // Test for method java.lang.String java.util.zip.ZipEntry.toString()
+ assertTrue("Returned incorrect entry name", zentry.toString().indexOf(
+ "File1.txt") >= 0);
+ }
+
+ /**
+ * @tests java.util.zip.ZipEntry#ZipEntry(java.util.zip.ZipEntry)
+ */
+ public void test_ConstructorLjava_util_zip_ZipEntry() {
+ // Test for method java.util.zip.ZipEntry(util.zip.ZipEntry)
+ zentry.setSize(2);
+ zentry.setCompressedSize(4);
+ zentry.setComment("Testing");
+ ZipEntry zentry2 = new ZipEntry(zentry);
+ assertEquals("ZipEntry Created With Incorrect Size.",
+ 2, zentry2.getSize());
+ assertEquals("ZipEntry Created With Incorrect Compressed Size.", 4, zentry2
+ .getCompressedSize());
+ assertEquals("ZipEntry Created With Incorrect Comment.", "Testing", zentry2
+ .getComment());
+ assertTrue("ZipEntry Created With Incorrect Crc.",
+ zentry2.getCrc() == orgCrc);
+ assertTrue("ZipEntry Created With Incorrect Time.",
+ zentry2.getTime() == orgTime);
+ }
+
+ /**
+ * @tests java.util.zip.ZipEntry#clone()
+ */
+ public void test_clone() {
+ // Test for method java.util.zip.ZipEntry.clone()
+ Object obj = zentry.clone();
+ assertTrue("toString()", obj.toString().equals(zentry.toString()));
+ assertTrue("hashCode()", obj.hashCode() == zentry.hashCode());
+
+ // One constructor
+ ZipEntry zeInput = new ZipEntry("InputZIP");
+ byte[] extraB = { 'a', 'b', 'd', 'e' };
+ zeInput.setExtra(extraB);
+ assertEquals(extraB, zeInput.getExtra());
+ assertEquals(extraB[3], zeInput.getExtra()[3]);
+ assertEquals(extraB.length, zeInput.getExtra().length);
+
+ // test Clone()
+ ZipEntry zeOutput = (ZipEntry) zeInput.clone();
+ assertEquals(zeInput.getExtra()[3], zeOutput.getExtra()[3]);
+ assertEquals(zeInput.getExtra().length, zeOutput.getExtra().length);
+ assertEquals(extraB[3], zeOutput.getExtra()[3]);
+ assertEquals(extraB.length, zeOutput.getExtra().length);
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+
+ @Override
protected void setUp() {
- java.io.File f = null;
- try {
- // BEGIN android-changed
- // Create a local copy of the file since some tests want to alter
- // information.
- f = File.createTempFile(tempFileName, ".zip");
- // Create absolute filename as ZipFile does not resolve using
- // user.dir
- f = new java.io.File(f.getAbsolutePath());
- f.delete();
- java.io.InputStream is = Support_Resources
- .getStream("hyts_ZipFile.zip");
- java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
+ java.io.File f = null;
+ try {
+ // Create a local copy of the file since some tests want to alter
+ // information.
+ f = new java.io.File(tempFileName);
+ // Create absolute filename as ZipFile does not resolve using
+ // user.dir
+ f = new java.io.File(f.getAbsolutePath());
+ f.delete();
+ java.io.InputStream is = Support_Resources
+ .getStream("hyts_ZipFile.zip");
+ java.io.FileOutputStream fos = new java.io.FileOutputStream(f);
byte[] rbuf = getAllBytesFromStream(is);
- // END android-changed
- fos.write(rbuf, 0, rbuf.length);
- is.close();
- fos.close();
- zfile = new java.util.zip.ZipFile(f);
- zentry = zfile.getEntry("File1.txt");
- orgSize = zentry.getSize();
- orgCompressedSize = zentry.getCompressedSize();
- orgCrc = zentry.getCrc();
- orgTime = zentry.getTime();
- orgComment = zentry.getComment();
- } catch (Exception e) {
- System.out.println("Exception during ZipFile setup <"
- + f.getAbsolutePath() + ">: ");
- e.printStackTrace();
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
-
- @Override
+ fos.write(rbuf, 0, rbuf.length);
+ is.close();
+ fos.close();
+ zfile = new java.util.zip.ZipFile(f);
+ zentry = zfile.getEntry("File1.txt");
+ orgSize = zentry.getSize();
+ orgCompressedSize = zentry.getCompressedSize();
+ orgCrc = zentry.getCrc();
+ orgTime = zentry.getTime();
+ orgComment = zentry.getComment();
+ } catch (Exception e) {
+ System.out.println("Exception during ZipFile setup <"
+ + f.getAbsolutePath() + ">: ");
+ 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() {
- try {
- if (zfile != null) {
+ try {
+ if (zfile != null) {
zfile.close();
}
- java.io.File f = new java.io.File(tempFileName);
- f.delete();
- } catch (java.io.IOException e) {
- System.out.println("Exception during tearDown");
- }
- }
+ java.io.File f = new java.io.File(tempFileName);
+ f.delete();
+ } catch (java.io.IOException e) {
+ System.out.println("Exception during tearDown");
+ }
+ }
}
diff --git a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipOutputStreamTest.java b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipOutputStreamTest.java
index 0398f03..7adfeff 100644
--- a/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipOutputStreamTest.java
+++ b/archive/src/test/java/org/apache/harmony/archive/tests/java/util/zip/ZipOutputStreamTest.java
@@ -14,14 +14,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package org.apache.harmony.archive.tests.java.util.zip;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -33,27 +27,20 @@ import java.util.zip.ZipException;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
-@TestTargetClass(ZipOutputStream.class)
public class ZipOutputStreamTest extends junit.framework.TestCase {
- ZipOutputStream zos;
+ ZipOutputStream zos;
- ByteArrayOutputStream bos;
+ ByteArrayOutputStream bos;
- ZipInputStream zis;
+ ZipInputStream zis;
- static final String data = "HelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorld";
+ static final String data = "HelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorldHelloWorld";
- /**
+ /**
* @tests java.util.zip.ZipOutputStream#close()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Can not check IOException.",
- method = "close",
- args = {}
- )
- public void test_close() throws Exception {
+ public void test_close() throws Exception {
try {
zos.close();
fail("Close on empty stream failed to throw exception");
@@ -76,12 +63,6 @@ public class ZipOutputStreamTest extends junit.framework.TestCase {
/**
* @tests java.util.zip.ZipOutputStream#closeEntry()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "ZipException can not be checked.",
- method = "closeEntry",
- args = {}
- )
public void test_closeEntry() throws IOException {
ZipEntry ze = new ZipEntry("testEntry");
ze.setTime(System.currentTimeMillis());
@@ -90,25 +71,12 @@ public class ZipOutputStreamTest extends junit.framework.TestCase {
zos.closeEntry();
assertTrue("closeEntry failed to update required fields",
ze.getSize() == 11 && ze.getCompressedSize() == 13);
- ze = new ZipEntry("testEntry1");
- zos.close();
- try {
- zos.closeEntry();
- fail("IOException expected");
- } catch (IOException ee) {
- // expected
- }
+
}
/**
* @tests java.util.zip.ZipOutputStream#finish()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "ZipException can not be checked.",
- method = "finish",
- args = {}
- )
public void test_finish() throws Exception {
ZipEntry ze = new ZipEntry("test");
zos.putNextEntry(ze);
@@ -131,12 +99,6 @@ public class ZipOutputStreamTest extends junit.framework.TestCase {
/**
* @tests java.util.zip.ZipOutputStream#putNextEntry(java.util.zip.ZipEntry)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "ZipException can not be checked.",
- method = "putNextEntry",
- args = {java.util.zip.ZipEntry.class}
- )
public void test_putNextEntryLjava_util_zip_ZipEntry() throws IOException {
ZipEntry ze = new ZipEntry("testEntry");
ze.setTime(System.currentTimeMillis());
@@ -161,12 +123,6 @@ public class ZipOutputStreamTest extends junit.framework.TestCase {
/**
* @tests java.util.zip.ZipOutputStream#setComment(java.lang.String)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setComment",
- args = {java.lang.String.class}
- )
public void test_setCommentLjava_lang_String() {
// There is no way to get the comment back, so no way to determine if
// the comment is set correct
@@ -183,12 +139,6 @@ public class ZipOutputStreamTest extends junit.framework.TestCase {
/**
* @tests java.util.zip.ZipOutputStream#setLevel(int)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setLevel",
- args = {int.class}
- )
public void test_setLevelI() throws IOException {
ZipEntry ze = new ZipEntry("test");
zos.putNextEntry(ze);
@@ -200,23 +150,11 @@ public class ZipOutputStreamTest extends junit.framework.TestCase {
zos.write(data.getBytes());
zos.closeEntry();
assertTrue("setLevel failed", csize <= ze.getCompressedSize());
- try {
- zos.setLevel(-9); // Max Compression
- fail("IllegalArgumentException ecpected.");
- } catch (IllegalArgumentException ee) {
- // expected
- }
}
/**
* @tests java.util.zip.ZipOutputStream#setMethod(int)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setMethod",
- args = {int.class}
- )
public void test_setMethodI() throws IOException {
ZipEntry ze = new ZipEntry("test");
zos.setMethod(ZipOutputStream.STORED);
@@ -233,23 +171,11 @@ public class ZipOutputStreamTest extends junit.framework.TestCase {
zos.write(data.getBytes());
zos.closeEntry();
assertTrue("setLevel failed", csize >= ze.getCompressedSize());
- try {
- zos.setMethod(-ZipOutputStream.DEFLATED);
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException ee) {
- // expected
- }
}
/**
* @tests java.util.zip.ZipOutputStream#write(byte[], int, int)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "write",
- args = {byte[].class, int.class, int.class}
- )
public void test_write$BII() throws IOException {
ZipEntry ze = new ZipEntry("test");
zos.putNextEntry(ze);
@@ -314,12 +240,6 @@ public class ZipOutputStreamTest extends junit.framework.TestCase {
/**
* @tests java.util.zip.ZipOutputStream#write(byte[], int, int)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Regression",
- method = "write",
- args = {byte[].class, int.class, int.class}
- )
public void test_write$BII_2() throws IOException {
// Regression for HARMONY-577
File f1 = File.createTempFile("testZip1", "tst");
@@ -331,7 +251,7 @@ public class ZipOutputStreamTest extends junit.framework.TestCase {
zip1.setMethod(ZipEntry.STORED);
zip1.write(new byte[2]);
-
+
try {
zip1.putNextEntry(new ZipEntry("Second"));
fail("ZipException expected");
@@ -364,18 +284,7 @@ public class ZipOutputStreamTest extends junit.framework.TestCase {
if (zis != null) {
zis.close();
}
- } catch (Exception e) {
- }
+ } catch (Exception e) {}
super.tearDown();
}
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "See setUp procedure for more info.",
- method = "ZipOutputStream",
- args = {java.io.OutputStream.class}
- )
- public void test_ConstructorLjava_io_OutputStream() {
- assertTrue(true);
- }
}
diff --git a/archive/src/test/java/tests/archive/AllTests.java b/archive/src/test/java/tests/archive/AllTests.java
index a5c461c..4c1fca2 100644
--- a/archive/src/test/java/tests/archive/AllTests.java
+++ b/archive/src/test/java/tests/archive/AllTests.java
@@ -21,13 +21,8 @@ import junit.framework.Test;
import junit.framework.TestSuite;
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 Archive test suites");
+ TestSuite suite = new TestSuite("All Archive test suites");
// $JUnit-BEGIN$
suite.addTest(org.apache.harmony.archive.tests.java.util.jar.AllTests
.suite());
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractExecutorServiceTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractExecutorServiceTest.java
index 99a007a..b80fe64 100644
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractExecutorServiceTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractExecutorServiceTest.java
@@ -15,9 +15,6 @@ import java.math.BigInteger;
import java.security.*;
public class AbstractExecutorServiceTest extends JSR166TestCase{
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(AbstractExecutorServiceTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractQueueTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractQueueTest.java
index 0251390..660fec9 100644
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractQueueTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractQueueTest.java
@@ -15,9 +15,6 @@ import java.util.concurrent.locks.*;
import java.io.*;
public class AbstractQueueTest extends JSR166TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(AbstractQueueTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractQueuedSynchronizerTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractQueuedSynchronizerTest.java
index db89645..e2cfe92 100644
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractQueuedSynchronizerTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AbstractQueuedSynchronizerTest.java
@@ -15,9 +15,6 @@ import java.util.concurrent.locks.*;
import java.io.*;
public class AbstractQueuedSynchronizerTest extends JSR166TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(AbstractQueuedSynchronizerTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ArrayBlockingQueueTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ArrayBlockingQueueTest.java
index b650ede..1deea2c 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/ArrayBlockingQueueTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ArrayBlockingQueueTest.java
@@ -14,9 +14,6 @@ import java.util.concurrent.*;
import java.io.*;
public class ArrayBlockingQueueTest extends JSR166TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(ArrayBlockingQueueTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicBooleanTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicBooleanTest.java
index 230357a..c76196b 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicBooleanTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicBooleanTest.java
@@ -13,9 +13,6 @@ import java.util.concurrent.atomic.*;
import java.io.*;
public class AtomicBooleanTest extends JSR166TestCase {
- public static void main (String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(AtomicBooleanTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerArrayTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerArrayTest.java
index cd13fcf..d8afe4e 100644
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerArrayTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerArrayTest.java
@@ -14,10 +14,6 @@ import java.io.*;
import java.util.*;
public class AtomicIntegerArrayTest extends JSR166TestCase {
-
- public static void main (String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(AtomicIntegerArrayTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerFieldUpdaterTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerFieldUpdaterTest.java
index 4c3ecb4..a4ec85e 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerFieldUpdaterTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerFieldUpdaterTest.java
@@ -16,9 +16,6 @@ public class AtomicIntegerFieldUpdaterTest extends JSR166TestCase {
volatile int x = 0;
int w;
long z;
- public static void main(String[] args){
- junit.textui.TestRunner.run(suite());
- }
public static Test suite() {
return new TestSuite(AtomicIntegerFieldUpdaterTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerTest.java
index d484785..a6b2a17 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicIntegerTest.java
@@ -13,9 +13,6 @@ import java.util.concurrent.atomic.*;
import java.io.*;
public class AtomicIntegerTest extends JSR166TestCase {
- public static void main (String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(AtomicIntegerTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongArrayTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongArrayTest.java
index 99ce204..262d273 100644
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongArrayTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongArrayTest.java
@@ -14,9 +14,6 @@ import java.io.*;
import java.util.*;
public class AtomicLongArrayTest extends JSR166TestCase {
- public static void main (String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(AtomicLongArrayTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongFieldUpdaterTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongFieldUpdaterTest.java
index 9310795..bac25dc 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongFieldUpdaterTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongFieldUpdaterTest.java
@@ -17,9 +17,6 @@ public class AtomicLongFieldUpdaterTest extends JSR166TestCase {
int z;
long w;
- public static void main(String[] args){
- junit.textui.TestRunner.run(suite());
- }
public static Test suite() {
return new TestSuite(AtomicLongFieldUpdaterTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongTest.java
index 143c84a..f4805bf 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicLongTest.java
@@ -13,9 +13,6 @@ import java.util.concurrent.atomic.*;
import java.io.*;
public class AtomicLongTest extends JSR166TestCase {
- public static void main (String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(AtomicLongTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicMarkableReferenceTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicMarkableReferenceTest.java
index 7b3dcb1..7857dde 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicMarkableReferenceTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicMarkableReferenceTest.java
@@ -12,9 +12,6 @@ import junit.framework.*;
import java.util.concurrent.atomic.*;
public class AtomicMarkableReferenceTest extends JSR166TestCase{
- public static void main (String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(AtomicMarkableReferenceTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceArrayTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceArrayTest.java
index 9330d39..81248cc 100644
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceArrayTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceArrayTest.java
@@ -15,9 +15,6 @@ import java.util.*;
public class AtomicReferenceArrayTest extends JSR166TestCase
{
- public static void main (String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(AtomicReferenceArrayTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceFieldUpdaterTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceFieldUpdaterTest.java
index feddce7..7f71781 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceFieldUpdaterTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceFieldUpdaterTest.java
@@ -17,9 +17,6 @@ public class AtomicReferenceFieldUpdaterTest extends JSR166TestCase{
Object z;
Integer w;
- public static void main(String[] args){
- junit.textui.TestRunner.run(suite());
- }
public static Test suite() {
return new TestSuite(AtomicReferenceFieldUpdaterTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceTest.java
index 33da30d..bcb4701 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicReferenceTest.java
@@ -13,9 +13,6 @@ import java.util.concurrent.atomic.*;
import java.io.*;
public class AtomicReferenceTest extends JSR166TestCase {
- public static void main (String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(AtomicReferenceTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicStampedReferenceTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicStampedReferenceTest.java
index 3ffc0a7..9f4e4f7 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicStampedReferenceTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/AtomicStampedReferenceTest.java
@@ -12,9 +12,6 @@ import junit.framework.*;
import java.util.concurrent.atomic.*;
public class AtomicStampedReferenceTest extends JSR166TestCase{
- public static void main (String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(AtomicStampedReferenceTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ConcurrentHashMapTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ConcurrentHashMapTest.java
index d7f2210..b7549a4 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/ConcurrentHashMapTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ConcurrentHashMapTest.java
@@ -15,9 +15,6 @@ import java.util.Enumeration;
import java.io.*;
public class ConcurrentHashMapTest extends JSR166TestCase{
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(ConcurrentHashMapTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ConcurrentLinkedQueueTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ConcurrentLinkedQueueTest.java
index 8d8e13b..c84dc59 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/ConcurrentLinkedQueueTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ConcurrentLinkedQueueTest.java
@@ -14,11 +14,6 @@ import java.util.concurrent.*;
import java.io.*;
public class ConcurrentLinkedQueueTest extends JSR166TestCase {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
-
public static Test suite() {
return new TestSuite(ConcurrentLinkedQueueTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArrayListTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArrayListTest.java
index d208039..53a1f70 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArrayListTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArrayListTest.java
@@ -14,11 +14,6 @@ import java.util.concurrent.*;
import java.io.*;
public class CopyOnWriteArrayListTest extends JSR166TestCase{
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
-
public static Test suite() {
return new TestSuite(CopyOnWriteArrayListTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArraySetTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArraySetTest.java
index 809fc59..abb33fa 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArraySetTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/CopyOnWriteArraySetTest.java
@@ -14,9 +14,6 @@ import java.util.concurrent.*;
import java.io.*;
public class CopyOnWriteArraySetTest extends JSR166TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(CopyOnWriteArraySetTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/CountDownLatchTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/CountDownLatchTest.java
index 0d69889..179c81e 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/CountDownLatchTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/CountDownLatchTest.java
@@ -13,9 +13,6 @@ import java.util.*;
import java.util.concurrent.*;
public class CountDownLatchTest extends JSR166TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(CountDownLatchTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/CyclicBarrierTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/CyclicBarrierTest.java
index ecd6e45..3b99ef8 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/CyclicBarrierTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/CyclicBarrierTest.java
@@ -15,9 +15,6 @@ import java.util.concurrent.locks.*;
import java.util.concurrent.atomic.*;
public class CyclicBarrierTest extends JSR166TestCase{
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(CyclicBarrierTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/DelayQueueTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/DelayQueueTest.java
index 978edb4..3d851e8 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/DelayQueueTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/DelayQueueTest.java
@@ -13,10 +13,6 @@ import java.util.*;
import java.util.concurrent.*;
public class DelayQueueTest extends JSR166TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
-
public static Test suite() {
return new TestSuite(DelayQueueTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ExchangerTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ExchangerTest.java
index 9811e82..bc0df85 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/ExchangerTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ExchangerTest.java
@@ -13,10 +13,6 @@ import java.util.*;
import java.util.concurrent.*;
public class ExchangerTest extends JSR166TestCase {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(ExchangerTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ExecutorCompletionServiceTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ExecutorCompletionServiceTest.java
index b1988cc..91bedf9 100644
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/ExecutorCompletionServiceTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ExecutorCompletionServiceTest.java
@@ -16,9 +16,6 @@ import java.math.BigInteger;
import java.security.*;
public class ExecutorCompletionServiceTest extends JSR166TestCase{
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(ExecutorCompletionServiceTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ExecutorsTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ExecutorsTest.java
index e8fc7e5..b0a2ccd 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/ExecutorsTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ExecutorsTest.java
@@ -15,9 +15,6 @@ import java.math.BigInteger;
import java.security.*;
public class ExecutorsTest extends JSR166TestCase{
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(ExecutorsTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/FutureTaskTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/FutureTaskTest.java
index 2108986..2635054 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/FutureTaskTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/FutureTaskTest.java
@@ -13,10 +13,6 @@ import java.util.concurrent.*;
import java.util.*;
public class FutureTaskTest extends JSR166TestCase {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(FutureTaskTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/JSR166TestCase.java b/concurrent/src/test/java/tests/api/java/util/concurrent/JSR166TestCase.java
index c900616..4e0de95 100644
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/JSR166TestCase.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/JSR166TestCase.java
@@ -97,7 +97,7 @@ public class JSR166TestCase extends TestCase {
iters = Integer.parseInt(args[0]);
Test s = suite();
for (int i = 0; i < iters; ++i) {
- junit.textui.TestRunner.run (s);
+ // junit.textui.TestRunner.run (s); android-changed
System.gc();
System.runFinalization();
}
@@ -108,8 +108,8 @@ public class JSR166TestCase extends TestCase {
* Collects all JSR166 unit tests as one suite
*/
public static Test suite ( ) {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("JSR166 Unit Tests");
// BEGIN android-changed
+ TestSuite suite = new TestSuite("JSR166 Unit Tests");
suite.addTest(AbstractExecutorServiceTest.suite());
suite.addTest(AbstractQueueTest.suite());
suite.addTest(AbstractQueuedSynchronizerTest.suite());
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/LinkedBlockingQueueTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/LinkedBlockingQueueTest.java
index 6648afb..dd6be9a 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/LinkedBlockingQueueTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/LinkedBlockingQueueTest.java
@@ -14,11 +14,6 @@ import java.util.concurrent.*;
import java.io.*;
public class LinkedBlockingQueueTest extends JSR166TestCase {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
-
public static Test suite() {
return new TestSuite(LinkedBlockingQueueTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/LinkedListTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/LinkedListTest.java
index 3a20207..3017c52 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/LinkedListTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/LinkedListTest.java
@@ -13,10 +13,6 @@ import java.util.*;
import java.util.concurrent.*;
public class LinkedListTest extends JSR166TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
-
public static Test suite() {
return new TestSuite(LinkedListTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/LockSupportTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/LockSupportTest.java
index b39db2e..0a74f91 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/LockSupportTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/LockSupportTest.java
@@ -14,9 +14,6 @@ import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class LockSupportTest extends JSR166TestCase{
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(LockSupportTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/PriorityBlockingQueueTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/PriorityBlockingQueueTest.java
index 3857e0f..a764866 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/PriorityBlockingQueueTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/PriorityBlockingQueueTest.java
@@ -14,9 +14,6 @@ import java.util.concurrent.*;
import java.io.*;
public class PriorityBlockingQueueTest extends JSR166TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(PriorityBlockingQueueTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/PriorityQueueTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/PriorityQueueTest.java
index 409e1ed..3d3c1be 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/PriorityQueueTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/PriorityQueueTest.java
@@ -14,9 +14,6 @@ import java.util.concurrent.*;
import java.io.*;
public class PriorityQueueTest extends JSR166TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(PriorityQueueTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ReentrantLockTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ReentrantLockTest.java
index c50482d..8372251 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/ReentrantLockTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ReentrantLockTest.java
@@ -15,9 +15,6 @@ import java.util.*;
import java.io.*;
public class ReentrantLockTest extends JSR166TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(ReentrantLockTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ReentrantReadWriteLockTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ReentrantReadWriteLockTest.java
index e38165a..4191a13 100644
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/ReentrantReadWriteLockTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ReentrantReadWriteLockTest.java
@@ -15,9 +15,6 @@ import java.io.*;
import java.util.*;
public class ReentrantReadWriteLockTest extends JSR166TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(ReentrantReadWriteLockTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ScheduledExecutorTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ScheduledExecutorTest.java
index da5704e..14e98b4 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/ScheduledExecutorTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ScheduledExecutorTest.java
@@ -14,9 +14,6 @@ import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class ScheduledExecutorTest extends JSR166TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(ScheduledExecutorTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/SemaphoreTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/SemaphoreTest.java
index 4019812..3f2ff33 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/SemaphoreTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/SemaphoreTest.java
@@ -14,9 +14,6 @@ import java.util.concurrent.*;
import java.io.*;
public class SemaphoreTest extends JSR166TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(SemaphoreTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/SynchronousQueueTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/SynchronousQueueTest.java
index debce5d..c2ae396 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/SynchronousQueueTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/SynchronousQueueTest.java
@@ -14,11 +14,6 @@ import java.util.concurrent.*;
import java.io.*;
public class SynchronousQueueTest extends JSR166TestCase {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
-
public static Test suite() {
return new TestSuite(SynchronousQueueTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/SystemTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/SystemTest.java
index 4433cb1..439039a 100644
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/SystemTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/SystemTest.java
@@ -11,10 +11,6 @@ package tests.api.java.util.concurrent;
import junit.framework.*;
public class SystemTest extends JSR166TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
-
public static Test suite() {
return new TestSuite(SystemTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadLocalTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadLocalTest.java
index 0c2256a..b9b7ba5 100644
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadLocalTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadLocalTest.java
@@ -12,10 +12,6 @@ import junit.framework.*;
import java.util.concurrent.Semaphore;
public class ThreadLocalTest extends JSR166TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
-
public static Test suite() {
return new TestSuite(ThreadLocalTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadPoolExecutorTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadPoolExecutorTest.java
index 4f7cc46..ee27e51 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadPoolExecutorTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadPoolExecutorTest.java
@@ -14,9 +14,6 @@ import junit.framework.*;
import java.util.*;
public class ThreadPoolExecutorTest extends JSR166TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run (suite());
- }
public static Test suite() {
return new TestSuite(ThreadPoolExecutorTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadTest.java
index 253d9eb..405e5be 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/ThreadTest.java
@@ -15,10 +15,6 @@ import dalvik.annotation.BrokenTest;
import junit.framework.*;
public class ThreadTest extends JSR166TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
-
public static Test suite() {
return new TestSuite(ThreadTest.class);
}
diff --git a/concurrent/src/test/java/tests/api/java/util/concurrent/TimeUnitTest.java b/concurrent/src/test/java/tests/api/java/util/concurrent/TimeUnitTest.java
index 54fdc69..f6504d8 100755
--- a/concurrent/src/test/java/tests/api/java/util/concurrent/TimeUnitTest.java
+++ b/concurrent/src/test/java/tests/api/java/util/concurrent/TimeUnitTest.java
@@ -13,10 +13,6 @@ import java.util.concurrent.*;
import java.io.*;
public class TimeUnitTest extends JSR166TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
-
public static Test suite() {
return new TestSuite(TimeUnitTest.class);
}
diff --git a/concurrent/src/test/java/tests/concurrent/AllTests.java b/concurrent/src/test/java/tests/concurrent/AllTests.java
index d2ebbeb..d599370 100644
--- a/concurrent/src/test/java/tests/concurrent/AllTests.java
+++ b/concurrent/src/test/java/tests/concurrent/AllTests.java
@@ -23,16 +23,11 @@ import junit.framework.TestSuite;
* Test suite for the concurrent module
*/
public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
-
/**
* Collects all JSR166 unit tests as one suite
*/
public static Test suite ( ) {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("JSR166 Unit Tests");
+ TestSuite suite = new TestSuite("JSR166 Unit Tests");
suite.addTest(tests.api.java.util.concurrent.JSR166TestCase.suite());
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/AllTests.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/AllTests.java
index 5050fc8..aa3240f 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/AllTests.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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 org.apache.harmony.crypto.tests.javax.crypto;");
+ TestSuite suite = new TestSuite("All tests for package org.apache.harmony.crypto.tests.javax.crypto;");
// $JUnit-BEGIN$
suite.addTestSuite(BadPaddingExceptionTest.class);
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java
index 750342c..5e2414e 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/MacTest.java
@@ -1171,11 +1171,6 @@ public class MacTest extends TestCase {
public static Test suite() {
return new TestSuite(MacTest.class);
}
-
- public static void main(String args[]) {
- junit.textui.TestRunner.run(suite());
-
- }
}
/**
* Additional class for Mac constructor verification
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/AllTests.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/AllTests.java
index 906057b..68b6720 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/AllTests.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/func/AllTests.java
@@ -24,11 +24,6 @@ import junit.framework.TestSuite;
*/
public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(AllTests.suite());
- }
-
public static Test suite() {
TestSuite suite = new TestSuite("All tests for package org.apache.harmony.crypto.tests.javax.crypto.func;");
// $JUnit-BEGIN$
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/interfaces/AllTests.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/interfaces/AllTests.java
index b66a384..b47c23e 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/interfaces/AllTests.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/interfaces/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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 org.apache.harmony.crypto.tests.javax.crypto.interfaces;");
+ TestSuite suite = new TestSuite("All tests for package org.apache.harmony.crypto.tests.javax.crypto.interfaces;");
// $JUnit-BEGIN$
suite.addTestSuite(DHPrivateKeyTest.class);
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/AllTests.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/AllTests.java
index 0be596e..02e0bbb 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/AllTests.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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 org.apache.harmony.crypto.tests.javax.crypto.serialization;");
+ TestSuite suite = new TestSuite("All tests for package org.apache.harmony.crypto.tests.javax.crypto.serialization;");
// $JUnit-BEGIN$
suite.addTestSuite(BadPaddingExceptionTest.class);
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/BadPaddingExceptionTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/BadPaddingExceptionTest.java
index 2f632ae..3992d44 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/BadPaddingExceptionTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/BadPaddingExceptionTest.java
@@ -42,8 +42,4 @@ public class BadPaddingExceptionTest extends SerializationTest {
return new Object[] { new BadPaddingException(),
new BadPaddingException(null), new BadPaddingException(msgs[1]) };
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(BadPaddingExceptionTest.class);
- }
}
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/ExemptionMechanismExceptionTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/ExemptionMechanismExceptionTest.java
index 7fd8cd0..33665d0 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/ExemptionMechanismExceptionTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/ExemptionMechanismExceptionTest.java
@@ -42,8 +42,4 @@ public class ExemptionMechanismExceptionTest extends SerializationTest {
return new Object[] { new ExemptionMechanismException(),
new ExemptionMechanismException(null), new ExemptionMechanismException(msgs[1]) };
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(ExemptionMechanismExceptionTest.class);
- }
}
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/IllegalBlockSizeExceptionTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/IllegalBlockSizeExceptionTest.java
index 2cc1daa..652c0b0 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/IllegalBlockSizeExceptionTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/IllegalBlockSizeExceptionTest.java
@@ -42,8 +42,4 @@ public class IllegalBlockSizeExceptionTest extends SerializationTest {
return new Object[] { new IllegalBlockSizeException(),
new IllegalBlockSizeException(null), new IllegalBlockSizeException(msgs[1]) };
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(IllegalBlockSizeExceptionTest.class);
- }
}
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/NoSuchPaddingExceptionTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/NoSuchPaddingExceptionTest.java
index 475bd2f..12b98fb 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/NoSuchPaddingExceptionTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/NoSuchPaddingExceptionTest.java
@@ -42,8 +42,4 @@ public class NoSuchPaddingExceptionTest extends SerializationTest {
return new Object[] { new NoSuchPaddingException(),
new NoSuchPaddingException(null), new NoSuchPaddingException(msgs[1]) };
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(NoSuchPaddingExceptionTest.class);
- }
}
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/ShortBufferExceptionTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/ShortBufferExceptionTest.java
index ab696e8..c42a5cb 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/ShortBufferExceptionTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/serialization/ShortBufferExceptionTest.java
@@ -42,8 +42,4 @@ public class ShortBufferExceptionTest extends SerializationTest {
return new Object[] { new ShortBufferException(),
new ShortBufferException(null), new ShortBufferException(msgs[1]) };
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(ShortBufferExceptionTest.class);
- }
}
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/AllTests.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/AllTests.java
index d31dc54..cdd3d51 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/AllTests.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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 org.apache.harmony.crypto.tests.javax.crypto.spec;");
+ TestSuite suite = new TestSuite("All tests for package org.apache.harmony.crypto.tests.javax.crypto.spec;");
// $JUnit-BEGIN$
suite.addTestSuite(DESKeySpecTest.class);
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DESKeySpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DESKeySpecTest.java
index 9904eed..9106a87 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DESKeySpecTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DESKeySpecTest.java
@@ -324,9 +324,5 @@ public class DESKeySpecTest extends TestCase {
public static Test suite() {
return new TestSuite(DESKeySpecTest.class);
}
-
- public static void main(String args[]) {
- junit.textui.TestRunner.run(suite());
- }
}
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DESedeKeySpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DESedeKeySpecTest.java
index 5c312a4..3f8ce0a 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DESedeKeySpecTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DESedeKeySpecTest.java
@@ -226,9 +226,5 @@ public class DESedeKeySpecTest extends TestCase {
public static Test suite() {
return new TestSuite(DESedeKeySpecTest.class);
}
-
- public static void main(String args[]) {
- junit.textui.TestRunner.run(suite());
- }
}
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHGenParameterSpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHGenParameterSpecTest.java
index 7b09cb6..aef1286 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHGenParameterSpecTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHGenParameterSpecTest.java
@@ -84,9 +84,5 @@ public class DHGenParameterSpecTest extends TestCase {
public static Test suite() {
return new TestSuite(DHGenParameterSpecTest.class);
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
}
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHParameterSpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHParameterSpecTest.java
index 0c0ac3b..65d1a17 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHParameterSpecTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHParameterSpecTest.java
@@ -111,9 +111,5 @@ public class DHParameterSpecTest extends TestCase {
public static Test suite() {
return new TestSuite(DHParameterSpecTest.class);
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
}
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHPrivateKeySpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHPrivateKeySpecTest.java
index 7181623..327004a 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHPrivateKeySpecTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHPrivateKeySpecTest.java
@@ -95,9 +95,5 @@ public class DHPrivateKeySpecTest extends TestCase {
public static Test suite() {
return new TestSuite(DHPrivateKeySpecTest.class);
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
}
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHPublicKeySpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHPublicKeySpecTest.java
index 064c713..905d8cd 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHPublicKeySpecTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/DHPublicKeySpecTest.java
@@ -95,9 +95,5 @@ public class DHPublicKeySpecTest extends TestCase {
public static Test suite() {
return new TestSuite(DHPublicKeySpecTest.class);
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
}
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/IvParameterSpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/IvParameterSpecTest.java
index fda566a..1c27f68 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/IvParameterSpecTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/IvParameterSpecTest.java
@@ -160,9 +160,5 @@ public class IvParameterSpecTest extends TestCase {
public static Test suite() {
return new TestSuite(IvParameterSpecTest.class);
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
}
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/OAEPParameterSpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/OAEPParameterSpecTest.java
index 6b2c673..3fa2d72 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/OAEPParameterSpecTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/OAEPParameterSpecTest.java
@@ -194,9 +194,5 @@ public class OAEPParameterSpecTest extends TestCase {
public static Test suite() {
return new TestSuite(OAEPParameterSpecTest.class);
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
}
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PBEKeySpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PBEKeySpecTest.java
index 1cb017e..bbce868 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PBEKeySpecTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PBEKeySpecTest.java
@@ -356,9 +356,5 @@ public class PBEKeySpecTest extends TestCase {
public static Test suite() {
return new TestSuite(PBEKeySpecTest.class);
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
}
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PBEParameterSpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PBEParameterSpecTest.java
index b294995..6bca15c 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PBEParameterSpecTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PBEParameterSpecTest.java
@@ -118,9 +118,5 @@ public class PBEParameterSpecTest extends TestCase {
public static Test suite() {
return new TestSuite(PBEParameterSpecTest.class);
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
}
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PSourceTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PSourceTest.java
index 08e8acd..ac3c5e5 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PSourceTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/PSourceTest.java
@@ -155,8 +155,4 @@ public class PSourceTest extends TestCase {
public static Test suite() {
return new TestSuite(PSourceTest.class);
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
}
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/RC2ParameterSpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/RC2ParameterSpecTest.java
index cf72d23..6eb636f 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/RC2ParameterSpecTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/RC2ParameterSpecTest.java
@@ -254,9 +254,5 @@ public class RC2ParameterSpecTest extends TestCase {
public static Test suite() {
return new TestSuite(RC2ParameterSpecTest.class);
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
}
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/RC5ParameterSpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/RC5ParameterSpecTest.java
index 6182615..9b7704d 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/RC5ParameterSpecTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/RC5ParameterSpecTest.java
@@ -350,9 +350,5 @@ public class RC5ParameterSpecTest extends TestCase {
public static Test suite() {
return new TestSuite(RC5ParameterSpecTest.class);
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
}
diff --git a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/SecretKeySpecTest.java b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/SecretKeySpecTest.java
index 5eeb76f..b39bb1d 100644
--- a/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/SecretKeySpecTest.java
+++ b/crypto/src/test/java/org/apache/harmony/crypto/tests/javax/crypto/spec/SecretKeySpecTest.java
@@ -315,9 +315,5 @@ public class SecretKeySpecTest extends TestCase {
public static Test suite() {
return new TestSuite(SecretKeySpecTest.class);
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
}
diff --git a/crypto/src/test/java/tests/crypto/AllTests.java b/crypto/src/test/java/tests/crypto/AllTests.java
index 795d0a9..0b53942 100644
--- a/crypto/src/test/java/tests/crypto/AllTests.java
+++ b/crypto/src/test/java/tests/crypto/AllTests.java
@@ -23,14 +23,8 @@ import junit.framework.TestSuite;
* Test suite that includes all tests for the regex project.
*/
public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(AllTests.suite());
-//AllTests.java
- }
-
public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("All crypto test suites");
+ TestSuite suite = new TestSuite("All crypto test suites");
// $JUnit-BEGIN$
suite.addTest(org.apache.harmony.crypto.tests.javax.crypto.interfaces.AllTests.suite());
suite.addTest(org.apache.harmony.crypto.tests.javax.crypto.serialization.AllTests.suite());
diff --git a/dom/src/test/java/tests/api/org/w3c/dom/AllTests.java b/dom/src/test/java/tests/api/org/w3c/dom/AllTests.java
index 677780a..7214d4f 100644
--- a/dom/src/test/java/tests/api/org/w3c/dom/AllTests.java
+++ b/dom/src/test/java/tests/api/org/w3c/dom/AllTests.java
@@ -28,7 +28,7 @@ public class AllTests {
}*/
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite();
+ TestSuite suite = new TestSuite();
suite.addTest(AllTests_Level1.suite());
suite.addTest(AllTests_Level2.suite());
return suite;
diff --git a/dom/src/test/java/tests/dom/AllTests.java b/dom/src/test/java/tests/dom/AllTests.java
index 6a5831f..48b362b 100644
--- a/dom/src/test/java/tests/dom/AllTests.java
+++ b/dom/src/test/java/tests/dom/AllTests.java
@@ -24,7 +24,10 @@ import junit.framework.TestSuite;
public class AllTests {
public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite();
+ TestSuite suite = new TestSuite();
+ // BEGIN android-changed: this was only referenced from the xml module!
+ suite.addTest(tests.api.org.w3c.dom.AllTests.suite());
+ // END android-changed
suite.addTestSuite(JunitTestCases.class);
return suite;
}
diff --git a/icu/src/test/java/com/ibm/icu4jni/util/AllTests.java b/icu/src/test/java/com/ibm/icu4jni/util/AllTests.java
index 1b95075..92df6fc 100644
--- a/icu/src/test/java/com/ibm/icu4jni/util/AllTests.java
+++ b/icu/src/test/java/com/ibm/icu4jni/util/AllTests.java
@@ -21,7 +21,7 @@ import junit.framework.TestSuite;
public class AllTests {
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite();
+ TestSuite suite = new TestSuite();
suite.addTestSuite(com.ibm.icu4jni.util.ResourcesTest.class);
return suite;
}
diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/AllTests.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/AllTests.java
index 1094f25..91b3e1a 100644
--- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/AllTests.java
+++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/AllTests.java
@@ -25,8 +25,7 @@ import junit.framework.TestSuite;
public class AllTests {
public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite(
- "Suite for org.apache.harmony.logging.tests.java.util.logging");
+ TestSuite suite = new TestSuite("Suite for org.apache.harmony.logging.tests.java.util.logging");
// $JUnit-BEGIN$
suite.addTestSuite(ConsoleHandlerTest.class);
suite.addTestSuite(ErrorManagerTest.class);
diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/ConsoleHandlerTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/ConsoleHandlerTest.java
index 91de2a5..b2204a3 100644
--- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/ConsoleHandlerTest.java
+++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/ConsoleHandlerTest.java
@@ -17,17 +17,11 @@
package org.apache.harmony.logging.tests.java.util.logging;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargets;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.security.Permission;
-import java.util.Currency;
import java.util.Properties;
import java.util.logging.ConsoleHandler;
import java.util.logging.Filter;
@@ -48,638 +42,542 @@ import tests.util.CallVerificationStack;
/**
* Test class java.util.logging.ConsoleHandler
*/
-@TestTargetClass(ConsoleHandler.class)
public class ConsoleHandlerTest extends TestCase {
- private final static String INVALID_LEVEL = "impossible_level";
-
- private final PrintStream err = System.err;
-
- private OutputStream errSubstituteStream = null;
-
- private static String className = ConsoleHandlerTest.class.getName();
-
- /*
- * @see TestCase#setUp()
- */
- protected void setUp() throws Exception {
- super.setUp();
- errSubstituteStream = new MockOutputStream();
- System.setErr(new PrintStream(errSubstituteStream));
- LogManager.getLogManager().reset();
- }
-
- /*
- * @see TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- LogManager.getLogManager().reset();
- CallVerificationStack.getInstance().clear();
- System.setErr(err);
- }
-
- /*
- * Test the constructor with no relevant log manager properties are set.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the constructor with no relevant log manager properties are set.",
- method = "ConsoleHandler",
- args = {}
- )
- public void testConstructor_NoProperties() {
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.ConsoleHandler.level"));
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.ConsoleHandler.filter"));
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.ConsoleHandler.formatter"));
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.ConsoleHandler.encoding"));
-
- ConsoleHandler h = new ConsoleHandler();
- assertSame(h.getLevel(), Level.INFO);
- assertTrue(h.getFormatter() instanceof SimpleFormatter);
- assertNull(h.getFilter());
- assertSame(h.getEncoding(), null);
- }
-
- /*
- * Test the constructor with insufficient privilege.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the constructor with insufficient privilege.",
- method = "ConsoleHandler",
- args = {}
- )
- public void testConstructor_InsufficientPrivilege() {
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.ConsoleHandler.level"));
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.ConsoleHandler.filter"));
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.ConsoleHandler.formatter"));
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.ConsoleHandler.encoding"));
-
- SecurityManager oldMan = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
- // set a normal value
- try {
- ConsoleHandler h = new ConsoleHandler();
- assertSame(h.getLevel(), Level.INFO);
- assertTrue(h.getFormatter() instanceof SimpleFormatter);
- assertNull(h.getFilter());
- assertSame(h.getEncoding(), null);
- } finally {
- System.setSecurityManager(oldMan);
- }
- }
-
- /*
- * Test the constructor with valid relevant log manager properties are set.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the constructor with valid relevant log manager properties are set.",
- method = "ConsoleHandler",
- args = {}
- )
- public void testConstructor_ValidProperties() throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.ConsoleHandler.level", "FINE");
- p.put("java.util.logging.ConsoleHandler.filter", className
- + "$MockFilter");
- p.put("java.util.logging.ConsoleHandler.formatter", className
- + "$MockFormatter");
- p.put("java.util.logging.ConsoleHandler.encoding", "iso-8859-1");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
-
- assertEquals(LogManager.getLogManager().getProperty(
- "java.util.logging.ConsoleHandler.level"), "FINE");
- assertEquals(LogManager.getLogManager().getProperty(
- "java.util.logging.ConsoleHandler.encoding"), "iso-8859-1");
- ConsoleHandler h = new ConsoleHandler();
- assertSame(h.getLevel(), Level.parse("FINE"));
- assertTrue(h.getFormatter() instanceof MockFormatter);
- assertTrue(h.getFilter() instanceof MockFilter);
- assertEquals(h.getEncoding(), "iso-8859-1");
- }
-
- /*
- * Test the constructor with invalid relevant log manager properties are
- * set.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the constructor with invalid relevant log manager properties are set.",
- method = "ConsoleHandler",
- args = {}
- )
- public void testConstructor_InvalidProperties() throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.ConsoleHandler.level", INVALID_LEVEL);
- p.put("java.util.logging.ConsoleHandler.filter", className);
- p.put("java.util.logging.ConsoleHandler.formatter", className);
- p.put("java.util.logging.ConsoleHandler.encoding", "XXXX");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
-
- assertEquals(LogManager.getLogManager().getProperty(
- "java.util.logging.ConsoleHandler.level"), INVALID_LEVEL);
- assertEquals(LogManager.getLogManager().getProperty(
- "java.util.logging.ConsoleHandler.encoding"), "XXXX");
- ConsoleHandler h = new ConsoleHandler();
- assertSame(h.getLevel(), Level.INFO);
- assertTrue(h.getFormatter() instanceof SimpleFormatter);
- assertNull(h.getFilter());
- assertNull(h.getEncoding());
- h.publish(new LogRecord(Level.SEVERE, "test"));
- assertNull(h.getEncoding());
- }
-
- /*
- * Test close() when having sufficient privilege, and a record has been
- * written to the output stream.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies close() when having sufficient privilege, and a record has been written to the output stream.",
- method = "close",
- args = {}
- )
- public void testClose_SufficientPrivilege_NormalClose() throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.ConsoleHandler.formatter", className
- + "$MockFormatter");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
- ConsoleHandler h = new ConsoleHandler();
- h.publish(new LogRecord(Level.SEVERE,
- "testClose_SufficientPrivilege_NormalClose msg"));
- h.close();
- assertEquals("flush", CallVerificationStack.getInstance()
- .getCurrentSourceMethod());
- assertNull(CallVerificationStack.getInstance().pop());
- h.close();
- }
-
- /*
- * Test close() when having sufficient privilege, and an output stream that
- * always throws exceptions.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies close() when having sufficient privilege, and an output stream that always throws exceptions",
- method = "close",
- args = {}
- )
- public void testClose_SufficientPrivilege_Exception() throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.ConsoleHandler.formatter", className
- + "$MockFormatter");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
- ConsoleHandler h = new ConsoleHandler();
-
- h.publish(new LogRecord(Level.SEVERE,
- "testClose_SufficientPrivilege_Exception msg"));
- h.flush();
- h.close();
- }
-
- /*
- * Test close() when having sufficient privilege, and no record has been
- * written to the output stream.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks close() when having sufficient privilege, and no record has been written to the output stream",
- method = "close",
- args = {}
- )
- public void testClose_SufficientPrivilege_DirectClose() throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.ConsoleHandler.formatter", className
- + "$MockFormatter");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
- ConsoleHandler h = new ConsoleHandler();
-
- h.close();
- assertEquals("flush", CallVerificationStack.getInstance()
- .getCurrentSourceMethod());
- assertNull(CallVerificationStack.getInstance().pop());
- assertTrue(CallVerificationStack.getInstance().empty());
- }
-
- /*
- * Test close() when having insufficient privilege.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies close() when insufficient privilege is set up.",
- method = "close",
- args = {}
- )
- public void testClose_InsufficientPrivilege() throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.ConsoleHandler.formatter", className
- + "$MockFormatter");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
- ConsoleHandler h = new ConsoleHandler();
- SecurityManager oldMan = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
- try {
- h.close();
- } finally {
- System.setSecurityManager(oldMan);
- }
- }
-
- /*
- * Test publish(), use no filter, having output stream, normal log record.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies publish(), use no filter, having output stream, normal log record.",
- method = "publish",
- args = {java.util.logging.LogRecord.class}
- )
- public void testPublish_NoFilter() throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.ConsoleHandler.formatter", className
- + "$MockFormatter");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
- ConsoleHandler h = new ConsoleHandler();
-
- LogRecord r = new LogRecord(Level.INFO, "testPublish_NoFilter");
- h.setLevel(Level.INFO);
- h.publish(r);
- h.flush();
- assertEquals("MockFormatter_Head" + "testPublish_NoFilter",
- this.errSubstituteStream.toString());
-
- h.setLevel(Level.WARNING);
- h.publish(r);
- h.flush();
- assertEquals("MockFormatter_Head" + "testPublish_NoFilter",
- this.errSubstituteStream.toString());
-
- h.setLevel(Level.CONFIG);
- h.publish(r);
- h.flush();
- assertEquals("MockFormatter_Head" + "testPublish_NoFilter"
- + "testPublish_NoFilter", this.errSubstituteStream.toString());
-
- r.setLevel(Level.OFF);
- h.setLevel(Level.OFF);
- h.publish(r);
- h.flush();
- assertEquals("MockFormatter_Head" + "testPublish_NoFilter"
- + "testPublish_NoFilter", this.errSubstituteStream.toString());
- }
-
- /*
- * Test publish(), after system err is reset.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies publish(), after system err is reset.",
- method = "publish",
- args = {java.util.logging.LogRecord.class}
- )
- public void testPublish_AfterResetSystemErr() throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.ConsoleHandler.formatter", className
- + "$MockFormatter");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
- ConsoleHandler h = new ConsoleHandler();
- h.setFilter(new MockFilter());
-
- System.setErr(new PrintStream(new ByteArrayOutputStream()));
-
- LogRecord r = new LogRecord(Level.INFO, "testPublish_WithFilter");
- h.setLevel(Level.INFO);
- h.publish(r);
- assertNull(CallVerificationStack.getInstance().pop());
- assertSame(r, CallVerificationStack.getInstance().pop());
- assertEquals("", this.errSubstituteStream.toString());
- }
-
- /*
- * Test publish(), use a filter, having output stream, normal log record.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies publish(), use a filter, having output stream, normal log record.",
- method = "publish",
- args = {java.util.logging.LogRecord.class}
- )
- public void testPublish_WithFilter() throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.ConsoleHandler.formatter", className
- + "$MockFormatter");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
- ConsoleHandler h = new ConsoleHandler();
- h.setFilter(new MockFilter());
-
- LogRecord r = new LogRecord(Level.INFO, "testPublish_WithFilter");
- h.setLevel(Level.INFO);
- h.publish(r);
- assertNull(CallVerificationStack.getInstance().pop());
- assertSame(r, CallVerificationStack.getInstance().pop());
- assertEquals("", this.errSubstituteStream.toString());
-
- h.setLevel(Level.WARNING);
- h.publish(r);
- assertNull(CallVerificationStack.getInstance().pop());
- assertTrue(CallVerificationStack.getInstance().empty());
- assertEquals("", this.errSubstituteStream.toString());
-
- h.setLevel(Level.CONFIG);
- h.publish(r);
- assertNull(CallVerificationStack.getInstance().pop());
- assertSame(r, CallVerificationStack.getInstance().pop());
- assertEquals("", this.errSubstituteStream.toString());
-
- r.setLevel(Level.OFF);
- h.setLevel(Level.OFF);
- h.publish(r);
- assertNull(CallVerificationStack.getInstance().pop());
- assertEquals("", this.errSubstituteStream.toString());
- assertTrue(CallVerificationStack.getInstance().empty());
- }
-
- /*
- * Test publish(), null log record, having output stream, spec said
- * rather than throw exception, handler should call errormanager to handle
- * exception case, so NullPointerException shouldn't be thrown.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies publish(), null log record, having output stream, spec said rather than throw exception, handler should call errormanager to handle exception case, so NullPointerException shouldn't be thrown.",
- method = "publish",
- args = {java.util.logging.LogRecord.class}
- )
- public void testPublish_Null() throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.ConsoleHandler.formatter", className
- + "$MockFormatter");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
- ConsoleHandler h = new ConsoleHandler();
- h.publish(null);
- }
-
- /*
- * Test publish(), a log record with empty msg, having output stream
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies publish(), a log record with empty msg, having output stream.",
- method = "publish",
- args = {java.util.logging.LogRecord.class}
- )
- public void testPublish_EmptyMsg() throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.ConsoleHandler.formatter", className
- + "$MockFormatter");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
- ConsoleHandler h = new ConsoleHandler();
- LogRecord r = new LogRecord(Level.INFO, "");
- h.publish(r);
- h.flush();
- assertEquals("MockFormatter_Head", this.errSubstituteStream.toString());
- }
-
- /*
- * Test publish(), a log record with null msg, having output stream
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies publish(), a log record with null msg, having output stream.",
- method = "publish",
- args = {java.util.logging.LogRecord.class}
- )
- public void testPublish_NullMsg() throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.ConsoleHandler.formatter", className
- + "$MockFormatter");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
- ConsoleHandler h = new ConsoleHandler();
- LogRecord r = new LogRecord(Level.INFO, null);
- h.publish(r);
- h.flush();
- // assertEquals("MockFormatter_Head",
- // this.errSubstituteStream.toString());
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies publish method after close.",
- method = "publish",
- args = {java.util.logging.LogRecord.class}
- )
- public void testPublish_AfterClose() throws Exception {
- PrintStream backup = System.err;
- try {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- System.setErr(new PrintStream(bos));
- Properties p = new Properties();
- p.put("java.util.logging.ConsoleHandler.level", "FINE");
- p.put("java.util.logging.ConsoleHandler.formatter", className
- + "$MockFormatter");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
- ConsoleHandler h = new ConsoleHandler();
- assertSame(h.getLevel(), Level.FINE);
- LogRecord r1 = new LogRecord(Level.INFO, "testPublish_Record1");
- LogRecord r2 = new LogRecord(Level.INFO, "testPublish_Record2");
- assertTrue(h.isLoggable(r1));
- h.publish(r1);
- assertTrue(bos.toString().indexOf("testPublish_Record1") >= 0);
- h.close();
- // assertFalse(h.isLoggable(r));
- assertTrue(h.isLoggable(r2));
- h.publish(r2);
- assertTrue(bos.toString().indexOf("testPublish_Record2") >= 0);
- h.flush();
- // assertEquals("MockFormatter_Head",
- // this.errSubstituteStream.toString());
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- System.setErr(backup);
- }
- }
-
- /*
- * Test setOutputStream() under normal condition.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies setOutputStream() under normal condition.",
- method = "setOutputStream",
- args = {java.io.OutputStream.class}
- )
- public void testSetOutputStream_Normal() {
- MockStreamHandler h = new MockStreamHandler();
- h.setFormatter(new MockFormatter());
-
- LogRecord r = new LogRecord(Level.INFO, "testSetOutputStream_Normal");
- h.publish(r);
- assertNull(CallVerificationStack.getInstance().pop());
- assertSame(r, CallVerificationStack.getInstance().pop());
- assertTrue(CallVerificationStack.getInstance().empty());
- assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal",
- this.errSubstituteStream.toString());
-
- ByteArrayOutputStream aos2 = new ByteArrayOutputStream();
- h.setOutputStream(aos2);
-
- // assertEquals("close", DelegationParameterStack.getInstance()
- // .getCurrentSourceMethod());
- // assertNull(DelegationParameterStack.getInstance().pop());
- // assertEquals("flush", DelegationParameterStack.getInstance()
- // .getCurrentSourceMethod());
- // assertNull(DelegationParameterStack.getInstance().pop());
- // assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal"
- // + "MockFormatter_Tail", this.errSubstituteStream.toString());
- // r = new LogRecord(Level.INFO, "testSetOutputStream_Normal2");
- // h.publish(r);
- // assertSame(r, DelegationParameterStack.getInstance().pop());
- // assertTrue(DelegationParameterStack.getInstance().empty());
- // assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal2",
- // aos2
- // .toString());
- // assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal"
- // + "MockFormatter_Tail", this.errSubstituteStream.toString());
- }
-
- /*
- * A mock filter, always return false.
- */
- public static class MockFilter implements Filter {
-
- public boolean isLoggable(LogRecord record) {
- CallVerificationStack.getInstance().push(record);
- // System.out.println("filter called...");
- return false;
- }
- }
-
- /*
- * A mock formatter.
- */
- public static class MockFormatter extends Formatter {
- public String format(LogRecord r) {
- // System.out.println("formatter called...");
- return super.formatMessage(r);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.util.logging.Formatter#getHead(java.util.logging.Handler)
- */
- public String getHead(Handler h) {
- return "MockFormatter_Head";
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.util.logging.Formatter#getTail(java.util.logging.Handler)
- */
- public String getTail(Handler h) {
- return "MockFormatter_Tail";
- }
- }
-
- /*
- * A mock output stream.
- */
- public static class MockOutputStream extends ByteArrayOutputStream {
-
- /*
- * (non-Javadoc)
- *
- * @see java.io.OutputStream#close()
- */
- public void close() throws IOException {
- CallVerificationStack.getInstance().push(null);
- super.close();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.io.OutputStream#flush()
- */
- public void flush() throws IOException {
- CallVerificationStack.getInstance().push(null);
- super.flush();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.io.OutputStream#write(int)
- */
- public void write(int oneByte) {
- // TODO Auto-generated method stub
- super.write(oneByte);
- }
- }
-
- /*
- * Used to grant all permissions except logging control.
- */
- public static class MockSecurityManager extends SecurityManager {
-
- public MockSecurityManager() {
- }
-
- public void checkPermission(Permission perm) {
- // grant all permissions except logging control
- if (perm instanceof LoggingPermission) {
- throw new SecurityException();
- }
- }
-
- public void checkPermission(Permission perm, Object context) {
- // grant all permissions except logging control
- if (perm instanceof LoggingPermission) {
- throw new SecurityException();
- }
- }
- }
-
- /*
- * A mock stream handler, expose setOutputStream.
- */
- public static class MockStreamHandler extends ConsoleHandler {
- public MockStreamHandler() {
- super();
- }
-
- public void setOutputStream(OutputStream out) {
- super.setOutputStream(out);
- }
-
- public boolean isLoggable(LogRecord r) {
- CallVerificationStack.getInstance().push(r);
- return super.isLoggable(r);
- }
- }
+ private final static String INVALID_LEVEL = "impossible_level";
+
+ private final PrintStream err = System.err;
+
+ private OutputStream errSubstituteStream = null;
+
+ private static String className = ConsoleHandlerTest.class.getName();
+
+ /*
+ * @see TestCase#setUp()
+ */
+ protected void setUp() throws Exception {
+ super.setUp();
+ errSubstituteStream = new MockOutputStream();
+ System.setErr(new PrintStream(errSubstituteStream));
+ LogManager.getLogManager().reset();
+ }
+
+ /*
+ * @see TestCase#tearDown()
+ */
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ LogManager.getLogManager().reset();
+ CallVerificationStack.getInstance().clear();
+ System.setErr(err);
+ }
+
+ /*
+ * Test the constructor with no relevant log manager properties are set.
+ */
+ public void testConstructor_NoProperties() {
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.ConsoleHandler.level"));
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.ConsoleHandler.filter"));
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.ConsoleHandler.formatter"));
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.ConsoleHandler.encoding"));
+
+ ConsoleHandler h = new ConsoleHandler();
+ assertSame(h.getLevel(), Level.INFO);
+ assertTrue(h.getFormatter() instanceof SimpleFormatter);
+ assertNull(h.getFilter());
+ assertSame(h.getEncoding(), null);
+ }
+
+ /*
+ * Test the constructor with insufficient privilege.
+ */
+ public void testConstructor_InsufficientPrivilege() {
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.ConsoleHandler.level"));
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.ConsoleHandler.filter"));
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.ConsoleHandler.formatter"));
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.ConsoleHandler.encoding"));
+
+ SecurityManager oldMan = System.getSecurityManager();
+ System.setSecurityManager(new MockSecurityManager());
+ // set a normal value
+ try {
+ ConsoleHandler h = new ConsoleHandler();
+ assertSame(h.getLevel(), Level.INFO);
+ assertTrue(h.getFormatter() instanceof SimpleFormatter);
+ assertNull(h.getFilter());
+ assertSame(h.getEncoding(), null);
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ }
+
+ /*
+ * Test the constructor with valid relevant log manager properties are set.
+ */
+ public void testConstructor_ValidProperties() throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.ConsoleHandler.level", "FINE");
+ p.put("java.util.logging.ConsoleHandler.filter", className
+ + "$MockFilter");
+ p.put("java.util.logging.ConsoleHandler.formatter", className
+ + "$MockFormatter");
+ p.put("java.util.logging.ConsoleHandler.encoding", "iso-8859-1");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+
+ assertEquals(LogManager.getLogManager().getProperty(
+ "java.util.logging.ConsoleHandler.level"), "FINE");
+ assertEquals(LogManager.getLogManager().getProperty(
+ "java.util.logging.ConsoleHandler.encoding"), "iso-8859-1");
+ ConsoleHandler h = new ConsoleHandler();
+ assertSame(h.getLevel(), Level.parse("FINE"));
+ assertTrue(h.getFormatter() instanceof MockFormatter);
+ assertTrue(h.getFilter() instanceof MockFilter);
+ assertEquals(h.getEncoding(), "iso-8859-1");
+ }
+
+ /*
+ * Test the constructor with invalid relevant log manager properties are
+ * set.
+ */
+ public void testConstructor_InvalidProperties() throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.ConsoleHandler.level", INVALID_LEVEL);
+ p.put("java.util.logging.ConsoleHandler.filter", className);
+ p.put("java.util.logging.ConsoleHandler.formatter", className);
+ p.put("java.util.logging.ConsoleHandler.encoding", "XXXX");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+
+ assertEquals(LogManager.getLogManager().getProperty(
+ "java.util.logging.ConsoleHandler.level"), INVALID_LEVEL);
+ assertEquals(LogManager.getLogManager().getProperty(
+ "java.util.logging.ConsoleHandler.encoding"), "XXXX");
+ ConsoleHandler h = new ConsoleHandler();
+ assertSame(h.getLevel(), Level.INFO);
+ assertTrue(h.getFormatter() instanceof SimpleFormatter);
+ assertNull(h.getFilter());
+ assertNull(h.getEncoding());
+ h.publish(new LogRecord(Level.SEVERE, "test"));
+ assertNull(h.getEncoding());
+ }
+
+ /*
+ * Test close() when having sufficient privilege, and a record has been
+ * written to the output stream.
+ */
+ public void testClose_SufficientPrivilege_NormalClose() throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.ConsoleHandler.formatter", className
+ + "$MockFormatter");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+ ConsoleHandler h = new ConsoleHandler();
+ h.publish(new LogRecord(Level.SEVERE,
+ "testClose_SufficientPrivilege_NormalClose msg"));
+ h.close();
+ assertEquals("flush", CallVerificationStack.getInstance()
+ .getCurrentSourceMethod());
+ assertNull(CallVerificationStack.getInstance().pop());
+ h.close();
+ }
+
+ /*
+ * Test close() when having sufficient privilege, and an output stream that
+ * always throws exceptions.
+ */
+ public void testClose_SufficientPrivilege_Exception() throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.ConsoleHandler.formatter", className
+ + "$MockFormatter");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+ ConsoleHandler h = new ConsoleHandler();
+
+ h.publish(new LogRecord(Level.SEVERE,
+ "testClose_SufficientPrivilege_Exception msg"));
+ h.flush();
+ h.close();
+ }
+
+ /*
+ * Test close() when having sufficient privilege, and no record has been
+ * written to the output stream.
+ */
+ public void testClose_SufficientPrivilege_DirectClose() throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.ConsoleHandler.formatter", className
+ + "$MockFormatter");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+ ConsoleHandler h = new ConsoleHandler();
+
+ h.close();
+ assertEquals("flush", CallVerificationStack.getInstance()
+ .getCurrentSourceMethod());
+ assertNull(CallVerificationStack.getInstance().pop());
+ assertTrue(CallVerificationStack.getInstance().empty());
+ }
+
+ /*
+ * Test close() when having insufficient privilege.
+ */
+ public void testClose_InsufficientPrivilege() throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.ConsoleHandler.formatter", className
+ + "$MockFormatter");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+ ConsoleHandler h = new ConsoleHandler();
+ SecurityManager oldMan = System.getSecurityManager();
+ System.setSecurityManager(new MockSecurityManager());
+ try {
+ h.close();
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ }
+
+ /*
+ * Test publish(), use no filter, having output stream, normal log record.
+ */
+ public void testPublish_NoFilter() throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.ConsoleHandler.formatter", className
+ + "$MockFormatter");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+ ConsoleHandler h = new ConsoleHandler();
+
+ LogRecord r = new LogRecord(Level.INFO, "testPublish_NoFilter");
+ h.setLevel(Level.INFO);
+ h.publish(r);
+ h.flush();
+ assertEquals("MockFormatter_Head" + "testPublish_NoFilter",
+ this.errSubstituteStream.toString());
+
+ h.setLevel(Level.WARNING);
+ h.publish(r);
+ h.flush();
+ assertEquals("MockFormatter_Head" + "testPublish_NoFilter",
+ this.errSubstituteStream.toString());
+
+ h.setLevel(Level.CONFIG);
+ h.publish(r);
+ h.flush();
+ assertEquals("MockFormatter_Head" + "testPublish_NoFilter"
+ + "testPublish_NoFilter", this.errSubstituteStream.toString());
+
+ r.setLevel(Level.OFF);
+ h.setLevel(Level.OFF);
+ h.publish(r);
+ h.flush();
+ assertEquals("MockFormatter_Head" + "testPublish_NoFilter"
+ + "testPublish_NoFilter", this.errSubstituteStream.toString());
+ }
+
+ /*
+ * Test publish(), after system err is reset.
+ */
+ public void testPublish_AfterResetSystemErr() throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.ConsoleHandler.formatter", className
+ + "$MockFormatter");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+ ConsoleHandler h = new ConsoleHandler();
+ h.setFilter(new MockFilter());
+
+ System.setErr(new PrintStream(new ByteArrayOutputStream()));
+
+ LogRecord r = new LogRecord(Level.INFO, "testPublish_WithFilter");
+ h.setLevel(Level.INFO);
+ h.publish(r);
+ assertNull(CallVerificationStack.getInstance().pop());
+ assertSame(r, CallVerificationStack.getInstance().pop());
+ assertEquals("", this.errSubstituteStream.toString());
+ }
+
+ /*
+ * Test publish(), use a filter, having output stream, normal log record.
+ */
+ public void testPublish_WithFilter() throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.ConsoleHandler.formatter", className
+ + "$MockFormatter");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+ ConsoleHandler h = new ConsoleHandler();
+ h.setFilter(new MockFilter());
+
+ LogRecord r = new LogRecord(Level.INFO, "testPublish_WithFilter");
+ h.setLevel(Level.INFO);
+ h.publish(r);
+ assertNull(CallVerificationStack.getInstance().pop());
+ assertSame(r, CallVerificationStack.getInstance().pop());
+ assertEquals("", this.errSubstituteStream.toString());
+
+ h.setLevel(Level.WARNING);
+ h.publish(r);
+ assertNull(CallVerificationStack.getInstance().pop());
+ assertTrue(CallVerificationStack.getInstance().empty());
+ assertEquals("", this.errSubstituteStream.toString());
+
+ h.setLevel(Level.CONFIG);
+ h.publish(r);
+ assertNull(CallVerificationStack.getInstance().pop());
+ assertSame(r, CallVerificationStack.getInstance().pop());
+ assertEquals("", this.errSubstituteStream.toString());
+
+ r.setLevel(Level.OFF);
+ h.setLevel(Level.OFF);
+ h.publish(r);
+ assertNull(CallVerificationStack.getInstance().pop());
+ assertEquals("", this.errSubstituteStream.toString());
+ assertTrue(CallVerificationStack.getInstance().empty());
+ }
+
+ /*
+ * Test publish(), null log record, having output stream, spec said
+ * rather than throw exception, handler should call errormanager to handle
+ * exception case, so NullPointerException shouldn't be thrown.
+ */
+ public void testPublish_Null() throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.ConsoleHandler.formatter", className
+ + "$MockFormatter");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+ ConsoleHandler h = new ConsoleHandler();
+ h.publish(null);
+ }
+
+ /*
+ * Test publish(), a log record with empty msg, having output stream
+ */
+ public void testPublish_EmptyMsg() throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.ConsoleHandler.formatter", className
+ + "$MockFormatter");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+ ConsoleHandler h = new ConsoleHandler();
+ LogRecord r = new LogRecord(Level.INFO, "");
+ h.publish(r);
+ h.flush();
+ assertEquals("MockFormatter_Head", this.errSubstituteStream.toString());
+ }
+
+ /*
+ * Test publish(), a log record with null msg, having output stream
+ */
+ public void testPublish_NullMsg() throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.ConsoleHandler.formatter", className
+ + "$MockFormatter");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+ ConsoleHandler h = new ConsoleHandler();
+ LogRecord r = new LogRecord(Level.INFO, null);
+ h.publish(r);
+ h.flush();
+ // assertEquals("MockFormatter_Head",
+ // this.errSubstituteStream.toString());
+ }
+
+ public void testPublish_AfterClose() throws Exception {
+ PrintStream backup = System.err;
+ try {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ System.setErr(new PrintStream(bos));
+ Properties p = new Properties();
+ p.put("java.util.logging.ConsoleHandler.level", "FINE");
+ p.put("java.util.logging.ConsoleHandler.formatter", className
+ + "$MockFormatter");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+ ConsoleHandler h = new ConsoleHandler();
+ assertSame(h.getLevel(), Level.FINE);
+ LogRecord r1 = new LogRecord(Level.INFO, "testPublish_Record1");
+ LogRecord r2 = new LogRecord(Level.INFO, "testPublish_Record2");
+ assertTrue(h.isLoggable(r1));
+ h.publish(r1);
+ assertTrue(bos.toString().indexOf("testPublish_Record1") >= 0);
+ h.close();
+ // assertFalse(h.isLoggable(r));
+ assertTrue(h.isLoggable(r2));
+ h.publish(r2);
+ assertTrue(bos.toString().indexOf("testPublish_Record2") >= 0);
+ h.flush();
+ // assertEquals("MockFormatter_Head",
+ // this.errSubstituteStream.toString());
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+ System.setErr(backup);
+ }
+ }
+
+ /*
+ * Test setOutputStream() under normal condition.
+ */
+ public void testSetOutputStream_Normal() {
+ MockStreamHandler h = new MockStreamHandler();
+ h.setFormatter(new MockFormatter());
+
+ LogRecord r = new LogRecord(Level.INFO, "testSetOutputStream_Normal");
+ h.publish(r);
+ assertNull(CallVerificationStack.getInstance().pop());
+ assertSame(r, CallVerificationStack.getInstance().pop());
+ assertTrue(CallVerificationStack.getInstance().empty());
+ assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal",
+ this.errSubstituteStream.toString());
+
+ ByteArrayOutputStream aos2 = new ByteArrayOutputStream();
+ h.setOutputStream(aos2);
+
+ // assertEquals("close", DelegationParameterStack.getInstance()
+ // .getCurrentSourceMethod());
+ // assertNull(DelegationParameterStack.getInstance().pop());
+ // assertEquals("flush", DelegationParameterStack.getInstance()
+ // .getCurrentSourceMethod());
+ // assertNull(DelegationParameterStack.getInstance().pop());
+ // assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal"
+ // + "MockFormatter_Tail", this.errSubstituteStream.toString());
+ // r = new LogRecord(Level.INFO, "testSetOutputStream_Normal2");
+ // h.publish(r);
+ // assertSame(r, DelegationParameterStack.getInstance().pop());
+ // assertTrue(DelegationParameterStack.getInstance().empty());
+ // assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal2",
+ // aos2
+ // .toString());
+ // assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal"
+ // + "MockFormatter_Tail", this.errSubstituteStream.toString());
+ }
+
+ /*
+ * A mock filter, always return false.
+ */
+ public static class MockFilter implements Filter {
+
+ public boolean isLoggable(LogRecord record) {
+ CallVerificationStack.getInstance().push(record);
+ // System.out.println("filter called...");
+ return false;
+ }
+ }
+
+ /*
+ * A mock formatter.
+ */
+ public static class MockFormatter extends Formatter {
+ public String format(LogRecord r) {
+ // System.out.println("formatter called...");
+ return super.formatMessage(r);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.util.logging.Formatter#getHead(java.util.logging.Handler)
+ */
+ public String getHead(Handler h) {
+ return "MockFormatter_Head";
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.util.logging.Formatter#getTail(java.util.logging.Handler)
+ */
+ public String getTail(Handler h) {
+ return "MockFormatter_Tail";
+ }
+ }
+
+ /*
+ * A mock output stream.
+ */
+ public static class MockOutputStream extends ByteArrayOutputStream {
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.OutputStream#close()
+ */
+ public void close() throws IOException {
+ CallVerificationStack.getInstance().push(null);
+ super.close();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.OutputStream#flush()
+ */
+ public void flush() throws IOException {
+ CallVerificationStack.getInstance().push(null);
+ super.flush();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.OutputStream#write(int)
+ */
+ public void write(int oneByte) {
+ // TODO Auto-generated method stub
+ super.write(oneByte);
+ }
+ }
+
+ /*
+ * Used to grant all permissions except logging control.
+ */
+ public static class MockSecurityManager extends SecurityManager {
+
+ public MockSecurityManager() {
+ }
+
+ public void checkPermission(Permission perm) {
+ // grant all permissions except logging control
+ if (perm instanceof LoggingPermission) {
+ throw new SecurityException();
+ }
+ }
+
+ public void checkPermission(Permission perm, Object context) {
+ // grant all permissions except logging control
+ if (perm instanceof LoggingPermission) {
+ throw new SecurityException();
+ }
+ }
+ }
+
+ /*
+ * A mock stream handler, expose setOutputStream.
+ */
+ public static class MockStreamHandler extends ConsoleHandler {
+ public MockStreamHandler() {
+ super();
+ }
+
+ public void setOutputStream(OutputStream out) {
+ super.setOutputStream(out);
+ }
+
+ public boolean isLoggable(LogRecord r) {
+ CallVerificationStack.getInstance().push(r);
+ return super.isLoggable(r);
+ }
+ }
}
diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FilterTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FilterTest.java
index d7ce843..1d105e0 100644
--- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FilterTest.java
+++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/FilterTest.java
@@ -15,26 +15,8 @@
* limitations under the License.
*/
-//TODO :
-/*
- * 1. Don't forget to write tests for org.apache.harmony.logging.internal.nls/Messages.java this file is in logging/src/main/java folder
- * 2. inrteface filter / LoggingMXBean tests machen
- * 3. XMLFormatter.java should be finish for Monday (not a lot to do) but as I beginn want to finish.
- * 3. In my case
- * I didn't use the PARTIAL_OK, so I believe that 98% of COMPLETE are PARTIAL_OK
- * COMPLETE = Tests finish and should be working. If error check the test before to make a ticket.
- * PARTIAL = Tests finish, but need special reviewing
- * TODO = A test to do (or not). Mostly a test to complete
- * 4. For questions christian.wiederseiner
- */
-
package org.apache.harmony.logging.tests.java.util.logging;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
import java.util.logging.Filter;
import java.util.logging.LogRecord;
@@ -44,26 +26,19 @@ import junit.framework.TestCase;
* This testcase verifies the signature of the interface Filter.
*
*/
-@TestTargetClass(Filter.class)
public class FilterTest extends TestCase {
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies interface.",
- method = "isLoggable",
- args = {java.util.logging.LogRecord.class}
- )
- public void testFilter() {
- MockFilter f = new MockFilter();
- assertFalse(f.isLoggable(null));
- }
-
- /*
- * This inner class implements the interface Filter to verify the signature.
- */
- private class MockFilter implements Filter {
-
- public boolean isLoggable(LogRecord record) {
- return false;
- }
- }
+ public void testFilter() {
+ MockFilter f = new MockFilter();
+ f.isLoggable(null);
+ }
+
+ /*
+ * This inner class implements the interface Filter to verify the signature.
+ */
+ private class MockFilter implements Filter {
+
+ public boolean isLoggable(LogRecord record) {
+ return false;
+ }
+ }
}
diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/HandlerTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/HandlerTest.java
index 5868b1f..2f13f2d 100644
--- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/HandlerTest.java
+++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/HandlerTest.java
@@ -17,16 +17,10 @@
package org.apache.harmony.logging.tests.java.util.logging;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.Permission;
-import java.util.EmptyStackException;
import java.util.Properties;
import java.util.logging.ErrorManager;
import java.util.logging.Filter;
@@ -46,730 +40,551 @@ import tests.util.CallVerificationStack;
* Test suite for the class java.util.logging.Handler.
*
*/
-@TestTargetClass(Handler.class)
public class HandlerTest extends TestCase {
- private static String className = HandlerTest.class.getName();
-
- /*
- * @see TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- super.tearDown();
+ private static String className = HandlerTest.class.getName();
+
+ /*
+ * @see TestCase#setUp()
+ */
+ protected void setUp() throws Exception {
+ super.setUp();
+ }
+
+ /*
+ * @see TestCase#tearDown()
+ */
+ protected void tearDown() throws Exception {
+ super.tearDown();
CallVerificationStack.getInstance().clear();
- }
-
- /*
- * Test the constructor.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "Handler",
- args = {}
- )
- public void testConstructor() {
- MockHandler h = new MockHandler();
- assertSame(h.getLevel(), Level.ALL);
- assertNull(h.getFormatter());
- assertNull(h.getFilter());
- assertNull(h.getEncoding());
- assertTrue(h.getErrorManager() instanceof ErrorManager);
- }
-
- /*
- * Test the constructor, with properties set
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "Handler",
- args = {}
- )
- public void testConstructor_Properties() throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.MockHandler.level", "FINE");
- p.put("java.util.logging.MockHandler.filter", className
- + "$MockFilter");
- p.put("java.util.logging.Handler.formatter", className
- + "$MockFormatter");
- p.put("java.util.logging.MockHandler.encoding", "utf-8");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
-
- assertEquals(LogManager.getLogManager().getProperty(
- "java.util.logging.MockHandler.level"), "FINE");
- assertEquals(LogManager.getLogManager().getProperty(
- "java.util.logging.MockHandler.encoding"), "utf-8");
- MockHandler h = new MockHandler();
- assertSame(h.getLevel(), Level.ALL);
- assertNull(h.getFormatter());
- assertNull(h.getFilter());
- assertNull(h.getEncoding());
- assertTrue(h.getErrorManager() instanceof ErrorManager);
- LogManager.getLogManager().reset();
- }
-
- /*
- * Test getEncoding & setEncoding methods with supported encoding.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify exceptions.",
- method = "getEncoding",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify exceptions.",
- method = "setEncoding",
- args = {java.lang.String.class}
- )
- })
- public void testGetSetEncoding_Normal() throws Exception {
- MockHandler h = new MockHandler();
- h.setEncoding("iso-8859-1");
- assertEquals("iso-8859-1", h.getEncoding());
- }
-
- /*
- * Test getEncoding & setEncoding methods with null.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies null as a parameter.",
- method = "getEncoding",
- args = {}
- )
- public void testGetSetEncoding_Null() throws Exception {
- MockHandler h = new MockHandler();
- h.setEncoding(null);
- assertNull(h.getEncoding());
- }
-
- /*
- * Test getEncoding & setEncoding methods with unsupported encoding.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies UnsupportedEncodingException.",
- method = "setEncoding",
- args = {java.lang.String.class}
- )
- public void testGetSetEncoding_Unsupported() {
- MockHandler h = new MockHandler();
- try {
- h.setEncoding("impossible");
- fail("Should throw UnsupportedEncodingException!");
- } catch (UnsupportedEncodingException e) {
- }
- assertNull(h.getEncoding());
- }
-
- /*
- * Test setEncoding with insufficient privilege.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify UnsupportedEncodingException.",
- method = "setEncoding",
- args = {java.lang.String.class}
- )
- public void testSetEncoding_InsufficientPrivilege() throws Exception {
- MockHandler h = new MockHandler();
- SecurityManager oldMan = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
- // set a normal value
- try {
- h.setEncoding("iso-8859-1");
- fail("Should throw SecurityException!");
- } catch (SecurityException e) {
- } finally {
- System.setSecurityManager(oldMan);
- }
- assertNull(h.getEncoding());
- System.setSecurityManager(new MockSecurityManager());
- // set an invalid value
- try {
-
- h.setEncoding("impossible");
- fail("Should throw SecurityException!");
- } catch (SecurityException e) {
- } finally {
- System.setSecurityManager(oldMan);
- }
- assertNull(h.getEncoding());
- }
-
- /*
- * Test getErrorManager & setErrorManager methods with non-null value.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "setErrorManager",
- args = {java.util.logging.ErrorManager.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getErrorManager",
- args = {}
- )
- })
- public void testGetSetErrorManager_Normal() throws Exception {
- MockHandler h = new MockHandler();
- ErrorManager man = new ErrorManager();
- h.setErrorManager(man);
- assertSame(man, h.getErrorManager());
- }
-
- /*
- * Test getErrorManager & setErrorManager methods with null.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies null as a parameter.",
- method = "getErrorManager",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies null as a parameter.",
- method = "setErrorManager",
- args = {java.util.logging.ErrorManager.class}
- )
- })
- public void testGetSetErrorManager_Null() throws Exception {
- MockHandler h = new MockHandler();
- // test set null
- try {
- h.setErrorManager(null);
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- }
-
- // test reset null
- try {
- h.setErrorManager(new ErrorManager());
- h.setErrorManager(null);
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- }
- }
-
- /*
- * Test getErrorManager with insufficient privilege.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies SecurityException.",
- method = "getErrorManager",
- args = {}
- )
- public void testGetErrorManager_InsufficientPrivilege() throws Exception {
- MockHandler h = new MockHandler();
- SecurityManager oldMan = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
-
- try {
- h.getErrorManager();
- fail("Should throw SecurityException!");
- } catch (SecurityException e) {
- } finally {
- System.setSecurityManager(oldMan);
- }
- }
-
- /*
- * Test setErrorManager with insufficient privilege.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies setErrorManager with insufficient privilege.",
- method = "setErrorManager",
- args = {java.util.logging.ErrorManager.class}
- )
- public void testSetErrorManager_InsufficientPrivilege() throws Exception {
- MockHandler h = new MockHandler();
- SecurityManager oldMan = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
-
- // set null
- try {
-
- h.setErrorManager(null);
- fail("Should throw SecurityException!");
- } catch (SecurityException e) {
- } finally {
- System.setSecurityManager(oldMan);
- }
- // set a normal value
- System.setSecurityManager(new MockSecurityManager());
- try {
-
- h.setErrorManager(new ErrorManager());
- fail("Should throw SecurityException!");
- } catch (SecurityException e) {
- } finally {
- System.setSecurityManager(oldMan);
- }
- }
-
- /*
- * Test getFilter & setFilter methods with non-null value.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify SecurityException.",
- method = "setFilter",
- args = {java.util.logging.Filter.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify SecurityException.",
- method = "getFilter",
- args = {}
- )
- })
- public void testGetSetFilter_Normal() throws Exception {
- MockHandler h = new MockHandler();
- Filter f = new MockFilter();
- h.setFilter(f);
- assertSame(f, h.getFilter());
- }
-
- /*
- * Test getFilter & setFilter methods with null.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies null as a parameter.",
- method = "getFilter",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies null as a parameter.",
- method = "setFilter",
- args = {java.util.logging.Filter.class}
- )
- })
- public void testGetSetFilter_Null() throws Exception {
- MockHandler h = new MockHandler();
- // test set null
- h.setFilter(null);
-
- // test reset null
- h.setFilter(new MockFilter());
- h.setFilter(null);
- }
-
- /*
- * Test setFilter with insufficient privilege.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies SecurityException.",
- method = "setFilter",
- args = {java.util.logging.Filter.class}
- )
- public void testSetFilter_InsufficientPrivilege() throws Exception {
- MockHandler h = new MockHandler();
- SecurityManager oldMan = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
-
- // set null
- try {
-
- h.setFilter(null);
- fail("Should throw SecurityException!");
- } catch (SecurityException e) {
- } finally {
- System.setSecurityManager(oldMan);
- }
- // set a normal value
- System.setSecurityManager(new MockSecurityManager());
- try {
-
- h.setFilter(new MockFilter());
- fail("Should throw SecurityException!");
- } catch (SecurityException e) {
- } finally {
- System.setSecurityManager(oldMan);
- }
- }
-
- /*
- * Test getFormatter & setFormatter methods with non-null value.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify SecurityException.",
- method = "getFormatter",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify SecurityException.",
- method = "setFormatter",
- args = {java.util.logging.Formatter.class}
- )
- })
- public void testGetSetFormatter_Normal() throws Exception {
- MockHandler h = new MockHandler();
- Formatter f = new SimpleFormatter();
- h.setFormatter(f);
- assertSame(f, h.getFormatter());
- }
-
- /*
- * Test getFormatter & setFormatter methods with null.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies null as a parameter.",
- method = "getFormatter",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies null as a parameter.",
- method = "setFormatter",
- args = {java.util.logging.Formatter.class}
- )
- })
- public void testGetSetFormatter_Null() throws Exception {
- MockHandler h = new MockHandler();
- // test set null
- try {
- h.setFormatter(null);
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- }
-
- // test reset null
- try {
- h.setFormatter(new SimpleFormatter());
- h.setFormatter(null);
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- }
- }
-
- /*
- * Test setFormatter with insufficient privilege.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies SecurityException.",
- method = "getFormatter",
- args = {}
- )
- public void testSetFormatter_InsufficientPrivilege() throws Exception {
- MockHandler h = new MockHandler();
- SecurityManager oldMan = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
-
- // set null
- try {
-
- h.setFormatter(null);
- fail("Should throw SecurityException!");
- } catch (SecurityException e) {
- } finally {
- System.setSecurityManager(oldMan);
- }
- // set a normal value
- System.setSecurityManager(new MockSecurityManager());
- try {
-
- h.setFormatter(new SimpleFormatter());
- fail("Should throw SecurityException!");
- } catch (SecurityException e) {
- } finally {
- System.setSecurityManager(oldMan);
- }
- }
-
- /*
- * Test getLevel & setLevel methods with non-null value.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify SecurityException.",
- method = "getLevel",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't verify SecurityException.",
- method = "setLevel",
- args = {java.util.logging.Level.class}
- )
- })
- public void testGetSetLevel_Normal() throws Exception {
- MockHandler h = new MockHandler();
- Level f = Level.CONFIG;
- h.setLevel(f);
- assertSame(f, h.getLevel());
- }
-
- /*
- * Test getLevel & setLevel methods with null.
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies getLevel & setLevel methods with null.",
- method = "getLevel",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies getLevel & setLevel methods with null.",
- method = "setLevel",
- args = {java.util.logging.Level.class}
- )
- })
- public void testGetSetLevel_Null() throws Exception {
- MockHandler h = new MockHandler();
- // test set null
- try {
- h.setLevel(null);
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- }
-
- // test reset null
- try {
- h.setLevel(Level.CONFIG);
- h.setLevel(null);
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- }
- }
-
- /*
- * Test setLevel with insufficient privilege.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies NullPointerException, SecurityException.",
- method = "setLevel",
- args = {java.util.logging.Level.class}
- )
- public void testSetLevel_InsufficientPrivilege() throws Exception {
- MockHandler h = new MockHandler();
- SecurityManager oldMan = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
-
- // set null
- try {
-
- h.setLevel(null);
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- } finally {
- System.setSecurityManager(oldMan);
- }
- // set a normal value
- System.setSecurityManager(new MockSecurityManager());
- try {
-
- h.setLevel(Level.CONFIG);
- fail("Should throw SecurityException!");
- } catch (SecurityException e) {
- } finally {
- System.setSecurityManager(oldMan);
- }
- }
-
- /*
- * Use no filter
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "isLoggable",
- args = {java.util.logging.LogRecord.class}
- )
- public void testIsLoggable_NoFilter() {
- MockHandler h = new MockHandler();
- LogRecord r = new LogRecord(Level.CONFIG, null);
- assertTrue(h.isLoggable(r));
-
- h.setLevel(Level.CONFIG);
- assertTrue(h.isLoggable(r));
-
- h.setLevel(Level.SEVERE);
- assertFalse(h.isLoggable(r));
-
- r.setLevel(Level.OFF);
- h.setLevel(Level.OFF);
- assertFalse(h.isLoggable(r));
- }
-
- /*
- * Use a filter
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies isLoggable method with filter.",
- method = "isLoggable",
- args = {java.util.logging.LogRecord.class}
- )
- public void testIsLoggable_WithFilter() {
- MockHandler h = new MockHandler();
- LogRecord r = new LogRecord(Level.CONFIG, null);
- LogRecord r1 = new LogRecord(Level.CONFIG, null);
- LogRecord r2 = new LogRecord(Level.CONFIG, null);
-
- h.setFilter(new MockFilter());
- assertFalse(h.isLoggable(r));
- assertSame(r,CallVerificationStack.getInstance().pop());
-
- h.setLevel(Level.CONFIG);
- assertFalse(h.isLoggable(r1));
- assertSame(r1, CallVerificationStack.getInstance().pop());
-
- h.setLevel(Level.SEVERE);
- assertFalse(h.isLoggable(r2));
-
- try{
- CallVerificationStack.getInstance().pop();
- }catch(EmptyStackException e){
- //normal
- }
- }
-
- /**
- * @tests java.util.logging.Handler#isLoggable(LogRecord)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies null as a parameter.",
- method = "isLoggable",
- args = {java.util.logging.LogRecord.class}
- )
- public void testIsLoggable_Null() {
- MockHandler h = new MockHandler();
- try {
- h.isLoggable(null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /*
- * Test whether the error manager is actually called with expected
- * parameters.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "reportError",
- args = {java.lang.String.class, java.lang.Exception.class, int.class}
- )
- public void testReportError() {
- MockHandler h = new MockHandler();
- h.setErrorManager(new MockErrorManager());
- SecurityManager oldMan = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
-
- try {
- Exception ex = new Exception("test exception");
- // with non-null parameters
- h.reportError("test msg", ex, -1);
- assertEquals(-1, CallVerificationStack.getInstance().popInt());
- assertSame(ex, CallVerificationStack.getInstance().pop());
- assertEquals("test msg", CallVerificationStack.getInstance().pop());
- // with null parameters
- h.reportError(null, null, 0);
- assertEquals(0, CallVerificationStack.getInstance().popInt());
- assertSame(null, CallVerificationStack.getInstance().pop());
- assertNull(CallVerificationStack.getInstance().pop());
- } catch (SecurityException e) {
- fail("Should not throw SecurityException!");
- } finally {
- System.setSecurityManager(oldMan);
- }
- }
-
- /*
- * Used to enable the testing of Handler because Handler is an abstract
- * class.
- */
- public static class MockHandler extends Handler {
-
- public void close() {
- }
-
- public void flush() {
- }
-
- public void publish(LogRecord record) {
- }
-
- public void reportError(String msg, Exception ex, int code) {
- super.reportError(msg, ex, code);
- }
- }
-
- /*
- * Used to grant all permissions except logging control.
- */
- public static class MockSecurityManager extends SecurityManager {
-
- public MockSecurityManager() {
- }
-
- public void checkPermission(Permission perm) {
- // grant all permissions except logging control
- if (perm instanceof LoggingPermission) {
- throw new SecurityException();
- }
- }
-
- public void checkPermission(Permission perm, Object context) {
- // grant all permissions except logging control
- if (perm instanceof LoggingPermission) {
- throw new SecurityException();
- }
- }
- }
-
- /*
- * A mock filter, always return false.
- */
- public static class MockFilter implements Filter {
-
- public boolean isLoggable(LogRecord record) {
- CallVerificationStack.getInstance().push(record);
- return false;
- }
- }
-
- /*
- * A mock error manager, used to validate the expected method is called with
- * the expected parameters.
- */
- public static class MockErrorManager extends ErrorManager {
-
- public void error(String msg, Exception ex, int errorCode) {
- CallVerificationStack.getInstance().push(msg);
- CallVerificationStack.getInstance().push(ex);
- CallVerificationStack.getInstance().push(errorCode);
- }
- }
+ }
+
+ /**
+ * Constructor for HandlerTest.
+ *
+ * @param arg0
+ */
+ public HandlerTest(String arg0) {
+ super(arg0);
+ }
+
+ /*
+ * Test the constructor.
+ */
+ public void testConstructor() {
+ MockHandler h = new MockHandler();
+ assertSame(h.getLevel(), Level.ALL);
+ assertNull(h.getFormatter());
+ assertNull(h.getFilter());
+ assertNull(h.getEncoding());
+ assertTrue(h.getErrorManager() instanceof ErrorManager);
+ }
+
+ /*
+ * Test the constructor, with properties set
+ */
+ public void testConstructor_Properties() throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.MockHandler.level", "FINE");
+ p
+ .put("java.util.logging.MockHandler.filter", className
+ + "$MockFilter");
+ p.put("java.util.logging.Handler.formatter", className
+ + "$MockFormatter");
+ p.put("java.util.logging.MockHandler.encoding", "utf-8");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+
+ assertEquals(LogManager.getLogManager().getProperty(
+ "java.util.logging.MockHandler.level"), "FINE");
+ assertEquals(LogManager.getLogManager().getProperty(
+ "java.util.logging.MockHandler.encoding"), "utf-8");
+ MockHandler h = new MockHandler();
+ assertSame(h.getLevel(), Level.ALL);
+ assertNull(h.getFormatter());
+ assertNull(h.getFilter());
+ assertNull(h.getEncoding());
+ assertTrue(h.getErrorManager() instanceof ErrorManager);
+ LogManager.getLogManager().reset();
+ }
+
+ /*
+ * Abstract method, no test needed.
+ */
+ public void testClose() {
+ MockHandler h = new MockHandler();
+ h.close();
+ }
+
+ /*
+ * Abstract method, no test needed.
+ */
+ public void testFlush() {
+ MockHandler h = new MockHandler();
+ h.flush();
+ }
+
+ /*
+ * Abstract method, no test needed.
+ */
+ public void testPublish() {
+ MockHandler h = new MockHandler();
+ h.publish(null);
+ }
+
+ /*
+ * Test getEncoding & setEncoding methods with supported encoding.
+ */
+ public void testGetSetEncoding_Normal() throws Exception {
+ MockHandler h = new MockHandler();
+ h.setEncoding("iso-8859-1");
+ assertEquals("iso-8859-1", h.getEncoding());
+ }
+
+ /*
+ * Test getEncoding & setEncoding methods with null.
+ */
+ public void testGetSetEncoding_Null() throws Exception {
+ MockHandler h = new MockHandler();
+ h.setEncoding(null);
+ assertNull(h.getEncoding());
+ }
+
+ /*
+ * Test getEncoding & setEncoding methods with unsupported encoding.
+ */
+ public void testGetSetEncoding_Unsupported() {
+ MockHandler h = new MockHandler();
+ try {
+ h.setEncoding("impossible");
+ fail("Should throw UnsupportedEncodingException!");
+ } catch (UnsupportedEncodingException e) {
+ }
+ assertNull(h.getEncoding());
+ }
+
+ /*
+ * Test setEncoding with insufficient privilege.
+ */
+ public void testSetEncoding_InsufficientPrivilege() throws Exception {
+ MockHandler h = new MockHandler();
+ SecurityManager oldMan = System.getSecurityManager();
+ System.setSecurityManager(new MockSecurityManager());
+ // set a normal value
+ try {
+ h.setEncoding("iso-8859-1");
+ fail("Should throw SecurityException!");
+ } catch (SecurityException e) {
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ assertNull(h.getEncoding());
+ System.setSecurityManager(new MockSecurityManager());
+ // set an invalid value
+ try {
+
+ h.setEncoding("impossible");
+ fail("Should throw SecurityException!");
+ } catch (SecurityException e) {
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ assertNull(h.getEncoding());
+ }
+
+ /*
+ * Test getErrorManager & setErrorManager methods with non-null value.
+ */
+ public void testGetSetErrorManager_Normal() throws Exception {
+ MockHandler h = new MockHandler();
+ ErrorManager man = new ErrorManager();
+ h.setErrorManager(man);
+ assertSame(man, h.getErrorManager());
+ }
+
+ /*
+ * Test getErrorManager & setErrorManager methods with null.
+ */
+ public void testGetSetErrorManager_Null() throws Exception {
+ MockHandler h = new MockHandler();
+ // test set null
+ try {
+ h.setErrorManager(null);
+ fail("Should throw NullPointerException!");
+ } catch (NullPointerException e) {
+ }
+
+ // test reset null
+ try {
+ h.setErrorManager(new ErrorManager());
+ h.setErrorManager(null);
+ fail("Should throw NullPointerException!");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /*
+ * Test getErrorManager with insufficient privilege.
+ */
+ public void testGetErrorManager_InsufficientPrivilege() throws Exception {
+ MockHandler h = new MockHandler();
+ SecurityManager oldMan = System.getSecurityManager();
+ System.setSecurityManager(new MockSecurityManager());
+
+ try {
+ h.getErrorManager();
+ fail("Should throw SecurityException!");
+ } catch (SecurityException e) {
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ }
+
+ /*
+ * Test setErrorManager with insufficient privilege.
+ */
+ public void testSetErrorManager_InsufficientPrivilege() throws Exception {
+ MockHandler h = new MockHandler();
+ SecurityManager oldMan = System.getSecurityManager();
+ System.setSecurityManager(new MockSecurityManager());
+
+ // set null
+ try {
+
+ h.setErrorManager(null);
+ fail("Should throw SecurityException!");
+ } catch (SecurityException e) {
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ // set a normal value
+ System.setSecurityManager(new MockSecurityManager());
+ try {
+
+ h.setErrorManager(new ErrorManager());
+ fail("Should throw SecurityException!");
+ } catch (SecurityException e) {
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ }
+
+ /*
+ * Test getFilter & setFilter methods with non-null value.
+ */
+ public void testGetSetFilter_Normal() throws Exception {
+ MockHandler h = new MockHandler();
+ Filter f = new MockFilter();
+ h.setFilter(f);
+ assertSame(f, h.getFilter());
+ }
+
+ /*
+ * Test getFilter & setFilter methods with null.
+ */
+ public void testGetSetFilter_Null() throws Exception {
+ MockHandler h = new MockHandler();
+ // test set null
+ h.setFilter(null);
+
+ // test reset null
+ h.setFilter(new MockFilter());
+ h.setFilter(null);
+ }
+
+ /*
+ * Test setFilter with insufficient privilege.
+ */
+ public void testSetFilter_InsufficientPrivilege() throws Exception {
+ MockHandler h = new MockHandler();
+ SecurityManager oldMan = System.getSecurityManager();
+ System.setSecurityManager(new MockSecurityManager());
+
+ // set null
+ try {
+
+ h.setFilter(null);
+ fail("Should throw SecurityException!");
+ } catch (SecurityException e) {
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ // set a normal value
+ System.setSecurityManager(new MockSecurityManager());
+ try {
+
+ h.setFilter(new MockFilter());
+ fail("Should throw SecurityException!");
+ } catch (SecurityException e) {
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ }
+
+ /*
+ * Test getFormatter & setFormatter methods with non-null value.
+ */
+ public void testGetSetFormatter_Normal() throws Exception {
+ MockHandler h = new MockHandler();
+ Formatter f = new SimpleFormatter();
+ h.setFormatter(f);
+ assertSame(f, h.getFormatter());
+ }
+
+ /*
+ * Test getFormatter & setFormatter methods with null.
+ */
+ public void testGetSetFormatter_Null() throws Exception {
+ MockHandler h = new MockHandler();
+ // test set null
+ try {
+ h.setFormatter(null);
+ fail("Should throw NullPointerException!");
+ } catch (NullPointerException e) {
+ }
+
+ // test reset null
+ try {
+ h.setFormatter(new SimpleFormatter());
+ h.setFormatter(null);
+ fail("Should throw NullPointerException!");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /*
+ * Test setFormatter with insufficient privilege.
+ */
+ public void testSetFormatter_InsufficientPrivilege() throws Exception {
+ MockHandler h = new MockHandler();
+ SecurityManager oldMan = System.getSecurityManager();
+ System.setSecurityManager(new MockSecurityManager());
+
+ // set null
+ try {
+
+ h.setFormatter(null);
+ fail("Should throw SecurityException!");
+ } catch (SecurityException e) {
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ // set a normal value
+ System.setSecurityManager(new MockSecurityManager());
+ try {
+
+ h.setFormatter(new SimpleFormatter());
+ fail("Should throw SecurityException!");
+ } catch (SecurityException e) {
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ }
+
+ /*
+ * Test getLevel & setLevel methods with non-null value.
+ */
+ public void testGetSetLevel_Normal() throws Exception {
+ MockHandler h = new MockHandler();
+ Level f = Level.CONFIG;
+ h.setLevel(f);
+ assertSame(f, h.getLevel());
+ }
+
+ /*
+ * Test getLevel & setLevel methods with null.
+ */
+ public void testGetSetLevel_Null() throws Exception {
+ MockHandler h = new MockHandler();
+ // test set null
+ try {
+ h.setLevel(null);
+ fail("Should throw NullPointerException!");
+ } catch (NullPointerException e) {
+ }
+
+ // test reset null
+ try {
+ h.setLevel(Level.CONFIG);
+ h.setLevel(null);
+ fail("Should throw NullPointerException!");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ /*
+ * Test setLevel with insufficient privilege.
+ */
+ public void testSetLevel_InsufficientPrivilege() throws Exception {
+ MockHandler h = new MockHandler();
+ SecurityManager oldMan = System.getSecurityManager();
+ System.setSecurityManager(new MockSecurityManager());
+
+ // set null
+ try {
+
+ h.setLevel(null);
+ fail("Should throw NullPointerException!");
+ } catch (NullPointerException e) {
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ // set a normal value
+ System.setSecurityManager(new MockSecurityManager());
+ try {
+
+ h.setLevel(Level.CONFIG);
+ fail("Should throw SecurityException!");
+ } catch (SecurityException e) {
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ }
+
+ /*
+ * Use no filter
+ */
+ public void testIsLoggable_NoFilter() {
+ MockHandler h = new MockHandler();
+ LogRecord r = new LogRecord(Level.CONFIG, null);
+ assertTrue(h.isLoggable(r));
+
+ h.setLevel(Level.CONFIG);
+ assertTrue(h.isLoggable(r));
+
+ h.setLevel(Level.SEVERE);
+ assertFalse(h.isLoggable(r));
+
+ r.setLevel(Level.OFF);
+ h.setLevel(Level.OFF);
+ assertFalse(h.isLoggable(r));
+ }
+
+ /*
+ * Use a filter
+ */
+ public void testIsLoggable_WithFilter() {
+ MockHandler h = new MockHandler();
+ LogRecord r = new LogRecord(Level.CONFIG, null);
+ h.setFilter(new MockFilter());
+ assertFalse(h.isLoggable(r));
+
+ h.setLevel(Level.CONFIG);
+ assertFalse(h.isLoggable(r));
+ assertSame(r, CallVerificationStack.getInstance().pop());
+
+ h.setLevel(Level.SEVERE);
+ assertFalse(h.isLoggable(r));
+ assertSame(r, CallVerificationStack.getInstance().pop());
+ }
+
+ /**
+ * @tests java.util.logging.Handler#isLoggable(LogRecord)
+ */
+ public void testIsLoggable_Null() {
+ MockHandler h = new MockHandler();
+ try {
+ h.isLoggable(null);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Test whether the error manager is actually called with expected
+ * parameters.
+ */
+ public void testReportError() {
+ MockHandler h = new MockHandler();
+ h.setErrorManager(new MockErrorManager());
+ SecurityManager oldMan = System.getSecurityManager();
+ System.setSecurityManager(new MockSecurityManager());
+
+ try {
+ Exception ex = new Exception("test exception");
+ // with non-null parameters
+ h.reportError("test msg", ex, -1);
+ assertEquals(-1, CallVerificationStack.getInstance().popInt());
+ assertSame(ex, CallVerificationStack.getInstance().pop());
+ assertEquals("test msg", CallVerificationStack.getInstance().pop());
+ // with null parameters
+ h.reportError(null, null, 0);
+ assertEquals(0, CallVerificationStack.getInstance().popInt());
+ assertSame(null, CallVerificationStack.getInstance().pop());
+ assertNull(CallVerificationStack.getInstance().pop());
+ } catch (SecurityException e) {
+ fail("Should not throw SecurityException!");
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ }
+
+ /*
+ * Used to enable the testing of Handler because Handler is an abstract
+ * class.
+ */
+ public static class MockHandler extends Handler {
+
+ public void close() {
+ }
+
+ public void flush() {
+ }
+
+ public void publish(LogRecord record) {
+ }
+
+ public void reportError(String msg, Exception ex, int code) {
+ super.reportError(msg, ex, code);
+ }
+ }
+
+ /*
+ * Used to grant all permissions except logging control.
+ */
+ public static class MockSecurityManager extends SecurityManager {
+
+ public MockSecurityManager() {
+ }
+
+ public void checkPermission(Permission perm) {
+ // grant all permissions except logging control
+ if (perm instanceof LoggingPermission) {
+ throw new SecurityException();
+ }
+ }
+
+ public void checkPermission(Permission perm, Object context) {
+ // grant all permissions except logging control
+ if (perm instanceof LoggingPermission) {
+ throw new SecurityException();
+ }
+ }
+ }
+
+ /*
+ * A mock filter, always return false.
+ */
+ public static class MockFilter implements Filter {
+
+ public boolean isLoggable(LogRecord record) {
+ CallVerificationStack.getInstance().push(record);
+ return false;
+ }
+ }
+
+ /*
+ * A mock error manager, used to validate the expected method is called with
+ * the expected parameters.
+ */
+ public static class MockErrorManager extends ErrorManager {
+
+ public void error(String msg, Exception ex, int errorCode) {
+ CallVerificationStack.getInstance().push(msg);
+ CallVerificationStack.getInstance().push(ex);
+ CallVerificationStack.getInstance().push(errorCode);
+ }
+ }
public static class NullOutputStream extends OutputStream{
@Override
diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LevelTestResource.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LevelTestResource.java
index 9b41a9d..5e06b70 100644
--- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LevelTestResource.java
+++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LevelTestResource.java
@@ -17,12 +17,8 @@
package org.apache.harmony.logging.tests.java.util.logging;
-import dalvik.annotation.TestTargetClass;
-
import java.util.ListResourceBundle;
-import java.util.logging.Level;
-//@TestTargetClass = No test needed, just test class helper
public class LevelTestResource extends ListResourceBundle {
public Object[][] getContents() {
return contents;
diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggingPermissionTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggingPermissionTest.java
index 9507bbd..aa8f7fa 100644
--- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggingPermissionTest.java
+++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/LoggingPermissionTest.java
@@ -17,29 +17,17 @@
package org.apache.harmony.logging.tests.java.util.logging;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
import java.util.logging.LoggingPermission;
import junit.framework.TestCase;
import org.apache.harmony.testframework.serialization.SerializationTest;
-@TestTargetClass(LoggingPermission.class)
public class LoggingPermissionTest extends TestCase {
/**
* @tests serialization/deserialization compatibility.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(new LoggingPermission("control", ""));
}
@@ -47,55 +35,43 @@ public class LoggingPermissionTest extends TestCase {
/**
* @tests serialization/deserialization compatibility with RI.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
public void testSerializationCompatibility() throws Exception {
SerializationTest.verifyGolden(this, new LoggingPermission("control",
""));
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "LoggingPermission",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void testLoggingPermission() {
- try {
- new LoggingPermission(null, null);
- fail("should throw IllegalArgumentException");
- } catch (NullPointerException e) {
- }
- try {
- new LoggingPermission("", null);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- }
- try {
- new LoggingPermission("bad name", null);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- }
- try {
- new LoggingPermission("Control", null);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- }
- try {
- new LoggingPermission("control",
- "bad action");
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- }
-
+ public void testLoggingPermission() {
+ try {
+ new LoggingPermission(null, null);
+ fail("should throw IllegalArgumentException");
+ } catch (NullPointerException e) {
+ }
+ try {
+ new LoggingPermission("", null);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ new LoggingPermission("bad name", null);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ new LoggingPermission("Control", null);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ }
+ try {
+ new LoggingPermission("control",
+ "bad action");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ }
+
new LoggingPermission("control", "");
-
+
new LoggingPermission("control", null);
- }
+ }
}
diff --git a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/StreamHandlerTest.java b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/StreamHandlerTest.java
index 72270e5..76380e6 100644
--- a/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/StreamHandlerTest.java
+++ b/logging/src/test/java/org/apache/harmony/logging/tests/java/util/logging/StreamHandlerTest.java
@@ -17,8 +17,6 @@
package org.apache.harmony.logging.tests.java.util.logging;
-import dalvik.annotation.*;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
@@ -39,7 +37,6 @@ import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.LoggingPermission;
import java.util.logging.SimpleFormatter;
-import java.util.logging.SocketHandler;
import java.util.logging.StreamHandler;
import junit.framework.TestCase;
@@ -51,1274 +48,1035 @@ import tests.util.CallVerificationStack;
/**
* Test the class StreamHandler.
*/
-@TestTargetClass(StreamHandler.class)
public class StreamHandlerTest extends TestCase {
- private final static String INVALID_LEVEL = "impossible_level";
+ private final static String INVALID_LEVEL = "impossible_level";
private final PrintStream err = System.err;
private OutputStream errSubstituteStream = null;
- private static String className = StreamHandlerTest.class.getName();
+ private static String className = StreamHandlerTest.class.getName();
- private static CharsetEncoder encoder;
+ private static CharsetEncoder encoder;
- static {
- encoder = Charset.forName("iso-8859-1").newEncoder();
- encoder.onMalformedInput(CodingErrorAction.REPLACE);
- encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
- }
+ static {
+ encoder = Charset.forName("iso-8859-1").newEncoder();
+ encoder.onMalformedInput(CodingErrorAction.REPLACE);
+ encoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
+ }
- /*
- * @see TestCase#setUp()
- */
- protected void setUp() throws Exception {
- super.setUp();
+ /*
+ * @see TestCase#setUp()
+ */
+ protected void setUp() throws Exception {
+ super.setUp();
errSubstituteStream = new NullOutputStream();
System.setErr(new PrintStream(errSubstituteStream));
- }
-
- /*
- * @see TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- LogManager.getLogManager().reset();
- CallVerificationStack.getInstance().clear();
+ }
+
+ /*
+ * @see TestCase#tearDown()
+ */
+ protected void tearDown() throws Exception {
+ LogManager.getLogManager().reset();
+ CallVerificationStack.getInstance().clear();
System.setErr(err);
super.tearDown();
- }
-
- /*
- * Test the constructor with no parameter, and no relevant log manager
- * properties are set.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the constructor with no parameter, and no relevant log manager properties are set.",
- method = "StreamHandler",
- args = {}
- )
- public void testConstructor_NoParameter_NoProperties() {
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.level"));
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.filter"));
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.formatter"));
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.encoding"));
-
- StreamHandler h = new StreamHandler();
- assertSame(Level.INFO, h.getLevel());
- assertTrue(h.getFormatter() instanceof SimpleFormatter);
- assertNull(h.getFilter());
- assertNull(h.getEncoding());
- }
-
- /*
- * Test the constructor with insufficient privilege.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the constructor with insufficient privilege.",
- method = "StreamHandler",
- args = {java.io.OutputStream.class, java.util.logging.Formatter.class}
- )
- public void testConstructor_NoParameter_InsufficientPrivilege() {
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.level"));
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.filter"));
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.formatter"));
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.encoding"));
-
- SecurityManager oldMan = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
- // set a normal value
- try {
- StreamHandler h = new StreamHandler();
- assertSame(Level.INFO, h.getLevel());
- assertTrue(h.getFormatter() instanceof SimpleFormatter);
- assertNull(h.getFilter());
- assertNull(h.getEncoding());
- } finally {
- System.setSecurityManager(oldMan);
- }
- }
-
- /*
- * Test the constructor with no parameter, and valid relevant log manager
- * properties are set.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the constructor with no parameter, and valid relevant log manager properties are set.",
- method = "StreamHandler",
- args = {}
- )
- public void testConstructor_NoParameter_ValidProperties() throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.StreamHandler.level", "FINE");
- p.put("java.util.logging.StreamHandler.filter", className
- + "$MockFilter");
- p.put("java.util.logging.StreamHandler.formatter", className
- + "$MockFormatter");
- p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
-
- assertEquals("FINE", LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.level"));
- assertEquals("iso-8859-1", LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.encoding"));
- StreamHandler h = new StreamHandler();
- assertSame(h.getLevel(), Level.parse("FINE"));
- assertTrue(h.getFormatter() instanceof MockFormatter);
- assertTrue(h.getFilter() instanceof MockFilter);
- assertEquals("iso-8859-1", h.getEncoding());
- }
-
- /*
- * Test the constructor with no parameter, and invalid relevant log manager
- * properties are set.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the constructor with no parameter, and invalid relevant log manager properties are set.",
- method = "StreamHandler",
- args = {}
- )
- public void testConstructor_NoParameter_InvalidProperties()
- throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.StreamHandler.level", INVALID_LEVEL);
- p.put("java.util.logging.StreamHandler.filter", className + "");
- p.put("java.util.logging.StreamHandler.formatter", className + "");
- p.put("java.util.logging.StreamHandler.encoding", "XXXX");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
-
- assertEquals(INVALID_LEVEL, LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.level"));
- assertEquals("XXXX", LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.encoding"));
- StreamHandler h = new StreamHandler();
- assertSame(Level.INFO, h.getLevel());
- assertTrue(h.getFormatter() instanceof SimpleFormatter);
- assertNull(h.getFilter());
- assertNull(h.getEncoding());
- h.publish(new LogRecord(Level.SEVERE, "test"));
- assertTrue(CallVerificationStack.getInstance().empty());
- assertNull(h.getEncoding());
- }
-
- /*
- * Test the constructor with normal parameter values, and no relevant log
- * manager properties are set.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the constructor with normal parameter values, and no relevant log manager properties are set.",
- method = "StreamHandler",
- args = {java.io.OutputStream.class, java.util.logging.Formatter.class}
- )
- public void testConstructor_HasParameters_NoProperties() {
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.level"));
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.filter"));
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.formatter"));
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.encoding"));
-
- StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
- new MockFormatter2());
- assertSame(Level.INFO, h.getLevel());
- assertTrue(h.getFormatter() instanceof MockFormatter2);
- assertNull(h.getFilter());
- assertNull(h.getEncoding());
- }
-
- /*
- * Test the constructor with insufficient privilege.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the constructor with insufficient privilege.",
- method = "StreamHandler",
- args = {java.io.OutputStream.class, java.util.logging.Formatter.class}
- )
- public void testConstructor_HasParameter_InsufficientPrivilege() {
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.level"));
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.filter"));
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.formatter"));
- assertNull(LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.encoding"));
-
- SecurityManager oldMan = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
- // set a normal value
- try {
- StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
- new MockFormatter2());
- assertSame(Level.INFO, h.getLevel());
- assertTrue(h.getFormatter() instanceof MockFormatter2);
- assertNull(h.getFilter());
- assertNull(h.getEncoding());
- } finally {
- System.setSecurityManager(oldMan);
- }
- }
-
- /*
- * Test the constructor with normal parameter values, and valid relevant log
- * manager properties are set.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the constructor with normal parameter values, and valid relevant log manager properties are set.",
- method = "StreamHandler",
- args = {java.io.OutputStream.class, java.util.logging.Formatter.class}
- )
- public void testConstructor_HasParameters_ValidProperties()
- throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.StreamHandler.level", "FINE");
- p.put("java.util.logging.StreamHandler.filter", className
- + "$MockFilter");
- p.put("java.util.logging.StreamHandler.formatter", className
- + "$MockFormatter");
- p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
-
- assertEquals("FINE", LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.level"));
- assertEquals("iso-8859-1", LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.encoding"));
- StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
- new MockFormatter2());
- assertSame(h.getLevel(), Level.parse("FINE"));
- assertTrue(h.getFormatter() instanceof MockFormatter2);
- assertTrue(h.getFilter() instanceof MockFilter);
- assertEquals("iso-8859-1", h.getEncoding());
- }
-
- /*
- * Test the constructor with normal parameter, and invalid relevant log
- * manager properties are set.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the constructor with normal parameter, and invalid relevant log manager properties are set.",
- method = "StreamHandler",
- args = {java.io.OutputStream.class, java.util.logging.Formatter.class}
- )
- public void testConstructor_HasParameters_InvalidProperties()
- throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.StreamHandler.level", INVALID_LEVEL);
- p.put("java.util.logging.StreamHandler.filter", className + "");
- p.put("java.util.logging.StreamHandler.formatter", className + "");
- p.put("java.util.logging.StreamHandler.encoding", "XXXX");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
-
- assertEquals(INVALID_LEVEL, LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.level"));
- assertEquals("XXXX", LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.encoding"));
- StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
- new MockFormatter2());
- assertSame(Level.INFO, h.getLevel());
- assertTrue(h.getFormatter() instanceof MockFormatter2);
- assertNull(h.getFilter());
- assertNull(h.getEncoding());
- }
-
- /*
- * Test the constructor with null formatter, and invalid relevant log manager
- * properties are set.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the constructor with null formatter, and invalid relevant log manager properties are set.",
- method = "StreamHandler",
- args = {java.io.OutputStream.class, java.util.logging.Formatter.class}
- )
- public void testConstructor_HasParameters_ValidPropertiesNullStream()
- throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.StreamHandler.level", "FINE");
- p.put("java.util.logging.StreamHandler.filter", className
- + "$MockFilter");
- p.put("java.util.logging.StreamHandler.formatter", className
- + "$MockFormatter");
- p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
-
- assertEquals("FINE", LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.level"));
- assertEquals("iso-8859-1", LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.encoding"));
- try {
- new StreamHandler(new ByteArrayOutputStream(), null);
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /*
- * Test the constructor with null output stream, and invalid relevant log
- * manager properties are set.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies the constructor with null output stream, and invalid relevant log manager properties are set.",
- method = "StreamHandler",
- args = {java.io.OutputStream.class, java.util.logging.Formatter.class}
- )
- public void testConstructor_HasParameters_ValidPropertiesNullFormatter()
- throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.StreamHandler.level", "FINE");
- p.put("java.util.logging.StreamHandler.filter", className
- + "$MockFilter");
- p.put("java.util.logging.StreamHandler.formatter", className
- + "$MockFormatter");
- p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
-
- assertEquals("FINE", LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.level"));
- assertEquals("iso-8859-1", LogManager.getLogManager().getProperty(
- "java.util.logging.StreamHandler.encoding"));
- try {
- new StreamHandler(null, new MockFormatter2());
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /*
- * Test close() when having sufficient privilege, and a record has been
- * written to the output stream.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies close() when having sufficient privilege, and a record has been written to the output stream.",
- method = "close",
- args = {}
- )
- public void testClose_SufficientPrivilege_NormalClose() {
- ByteArrayOutputStream aos = new MockOutputStream();
- StreamHandler h = new StreamHandler(aos, new MockFormatter());
- h.publish(new LogRecord(Level.SEVERE,
- "testClose_SufficientPrivilege_NormalClose msg"));
- h.close();
- assertEquals("close", CallVerificationStack.getInstance()
- .getCurrentSourceMethod());
- assertNull(CallVerificationStack.getInstance().pop());
- assertEquals("flush", CallVerificationStack.getInstance()
- .getCurrentSourceMethod());
- CallVerificationStack.getInstance().clear();
- assertTrue(aos.toString().endsWith("MockFormatter_Tail"));
- h.close();
- }
-
- /*
- * Test close() when having sufficient privilege, and an output stream that
- * always throws exceptions.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies close() when having sufficient privilege, and an output stream that always throws exceptions.",
- method = "close",
- args = {}
- )
- public void testClose_SufficientPrivilege_Exception() {
- ByteArrayOutputStream aos = new MockExceptionOutputStream();
- StreamHandler h = new StreamHandler(aos, new MockFormatter());
- h.publish(new LogRecord(Level.SEVERE,
- "testClose_SufficientPrivilege_Exception msg"));
- h.flush();
- h.close();
- }
-
- /*
- * Test close() when having sufficient privilege, and no record has been
- * written to the output stream.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies close() method when having sufficient privilege, and no record has been written to the output stream.",
- method = "close",
- args = {}
- )
- public void testClose_SufficientPrivilege_DirectClose() {
- ByteArrayOutputStream aos = new MockOutputStream();
- StreamHandler h = new StreamHandler(aos, new MockFormatter());
- h.close();
- assertEquals("close", CallVerificationStack.getInstance()
- .getCurrentSourceMethod());
- assertNull(CallVerificationStack.getInstance().pop());
- assertEquals("flush", CallVerificationStack.getInstance()
- .getCurrentSourceMethod());
- CallVerificationStack.getInstance().clear();
- assertEquals("MockFormatter_HeadMockFormatter_Tail", aos.toString());
- }
-
- /*
- * Test close() when having insufficient privilege.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies SecurityException.",
- method = "close",
- args = {}
- )
- public void testClose_InsufficientPrivilege() {
- StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
- new MockFormatter());
-
- SecurityManager oldMan = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
- try {
- h.close();
- fail("Should throw SecurityException!");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldMan);
- }
- }
-
- /*
- * Test close() when having no output stream.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies close() method when having no output stream.",
- method = "close",
- args = {}
- )
- public void testClose_NoOutputStream() {
- StreamHandler h = new StreamHandler();
- h.close();
- }
-
- /*
- * Test flush().
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies flush() method.",
- method = "flush",
- args = {}
- )
- public void testFlush_Normal() {
- ByteArrayOutputStream aos = new MockOutputStream();
- StreamHandler h = new StreamHandler(aos, new MockFormatter());
- h.flush();
- assertEquals("flush", CallVerificationStack.getInstance().getCurrentSourceMethod());
- assertNull(CallVerificationStack.getInstance().pop());
- CallVerificationStack.getInstance().clear();
- }
-
- /*
- * Test flush() when having no output stream.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies flush() when having no output stream.",
- method = "flush",
- args = {}
- )
- public void testFlush_NoOutputStream() {
- StreamHandler h = new StreamHandler();
- h.flush();
- }
-
- /*
- * Test isLoggable(), use no filter, having no output stream
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isLoggable(), use no filter, having no output stream.",
- method = "isLoggable",
- args = {java.util.logging.LogRecord.class}
- )
- public void testIsLoggable_NoOutputStream() {
- StreamHandler h = new StreamHandler();
- LogRecord r = new LogRecord(Level.INFO, null);
- assertFalse(h.isLoggable(r));
-
- h.setLevel(Level.WARNING);
- assertFalse(h.isLoggable(r));
-
- h.setLevel(Level.CONFIG);
- assertFalse(h.isLoggable(r));
-
- r.setLevel(Level.OFF);
- h.setLevel(Level.OFF);
- assertFalse(h.isLoggable(r));
- }
-
- /*
- * Test isLoggable(), use no filter, having output stream
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isLoggable(), use no filter, having output stream.",
- method = "isLoggable",
- args = {java.util.logging.LogRecord.class}
- )
- public void testIsLoggable_NoFilter() {
- StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
- new SimpleFormatter());
- LogRecord r = new LogRecord(Level.INFO, null);
- assertTrue(h.isLoggable(r));
-
- h.setLevel(Level.WARNING);
- assertFalse(h.isLoggable(r));
-
- h.setLevel(Level.CONFIG);
- assertTrue(h.isLoggable(r));
-
- r.setLevel(Level.OFF);
- h.setLevel(Level.OFF);
- assertFalse(h.isLoggable(r));
- }
-
- /*
- * Test isLoggable(), use a filter, having output stream
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isLoggable(), use a filter, having output stream.",
- method = "isLoggable",
- args = {java.util.logging.LogRecord.class}
- )
- public void testIsLoggable_WithFilter() {
- StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
- new SimpleFormatter());
- LogRecord r = new LogRecord(Level.INFO, null);
- h.setFilter(new MockFilter());
- assertFalse(h.isLoggable(r));
- assertSame(r, CallVerificationStack.getInstance().pop());
-
- h.setLevel(Level.CONFIG);
- assertFalse(h.isLoggable(r));
- assertSame(r, CallVerificationStack.getInstance().pop());
-
- h.setLevel(Level.WARNING);
- assertFalse(h.isLoggable(r)); //level to high, data will not reach the filter
- assertTrue(CallVerificationStack.getInstance().empty());
- }
-
- /*
- * Test isLoggable(), null log record, having output stream. Handler should
- * call ErrorManager to handle exceptional case
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isLoggable(), null log record, having output stream. Handler should call ErrorManager to handle exceptional case.",
- method = "isLoggable",
- args = {java.util.logging.LogRecord.class}
- )
- public void testIsLoggable_Null() {
- StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
- new SimpleFormatter());
- assertFalse(h.isLoggable(null));
- }
-
- /*
- * Test isLoggable(), null log record, without output stream
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies isLoggable(), null log record, without output stream.",
- method = "isLoggable",
- args = {java.util.logging.LogRecord.class}
- )
- public void testIsLoggable_Null_NoOutputStream() {
- StreamHandler h = new StreamHandler();
- assertFalse(h.isLoggable(null));
- }
-
- /*
- * Test publish(), use no filter, having output stream, normal log record.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies publish(), use no filter, having output stream, normal log record.",
- method = "publish",
- args = {java.util.logging.LogRecord.class}
- )
- public void testPublish_NoOutputStream() {
- StreamHandler h = new StreamHandler();
- LogRecord r = new LogRecord(Level.INFO, "testPublish_NoOutputStream");
- h.publish(r);
-
- h.setLevel(Level.WARNING);
- h.publish(r);
-
- h.setLevel(Level.CONFIG);
- h.publish(r);
-
- r.setLevel(Level.OFF);
- h.setLevel(Level.OFF);
- h.publish(r);
- }
-
- /*
- * Test publish(), use no filter, having output stream, normal log record.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies publish(), use no filter, having output stream, normal log record.",
- method = "publish",
- args = {java.util.logging.LogRecord.class}
- )
- public void testPublish_NoFilter() {
- ByteArrayOutputStream aos = new ByteArrayOutputStream();
- StreamHandler h = new StreamHandler(aos, new MockFormatter());
-
- LogRecord r = new LogRecord(Level.INFO, "testPublish_NoFilter");
- h.setLevel(Level.INFO);
- h.publish(r);
- h.flush();
- assertEquals("MockFormatter_Head" + "testPublish_NoFilter", aos
- .toString());
-
- h.setLevel(Level.WARNING);
- h.publish(r);
- h.flush();
- assertEquals("MockFormatter_Head" + "testPublish_NoFilter", aos
- .toString());
-
- h.setLevel(Level.CONFIG);
- h.publish(r);
- h.flush();
- assertEquals("MockFormatter_Head" + "testPublish_NoFilter"
- + "testPublish_NoFilter", aos.toString());
-
- r.setLevel(Level.OFF);
- h.setLevel(Level.OFF);
- h.publish(r);
- h.flush();
- assertEquals("MockFormatter_Head" + "testPublish_NoFilter"
- + "testPublish_NoFilter", aos.toString());
- }
-
- /*
- * Test publish(), use a filter, having output stream, normal log record.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies publish(), use a filter, having output stream, normal log record.",
- method = "publish",
- args = {java.util.logging.LogRecord.class}
- )
- public void testPublish_WithFilter() {
- ByteArrayOutputStream aos = new ByteArrayOutputStream();
- StreamHandler h = new StreamHandler(aos, new MockFormatter());
- h.setFilter(new MockFilter());
-
- LogRecord r = new LogRecord(Level.INFO, "testPublish_WithFilter");
- h.setLevel(Level.INFO);
- h.publish(r);
- h.flush();
- assertEquals("", aos.toString());
- assertSame(r, CallVerificationStack.getInstance().pop());
-
- h.setLevel(Level.WARNING);
- h.publish(r);
- h.flush();
- assertEquals("", aos.toString());
- assertTrue(CallVerificationStack.getInstance().empty());
-
- h.setLevel(Level.CONFIG);
- h.publish(r);
- h.flush();
- assertEquals("", aos.toString());
- assertSame(r, CallVerificationStack.getInstance().pop());
-
- r.setLevel(Level.OFF);
- h.setLevel(Level.OFF);
- h.publish(r);
- h.flush();
- assertEquals("", aos.toString());
- assertTrue(CallVerificationStack.getInstance().empty());
- }
-
- /*
- * Test publish(), null log record, handler should call ErrorManager to
- * handle exceptional case
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies publish(), null log record, handler should call ErrorManager to handle exceptional case.",
- method = "publish",
- args = {java.util.logging.LogRecord.class}
- )
- public void testPublish_Null() {
- StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
- new SimpleFormatter());
- h.publish(null);
- }
-
- /*
- * Test publish(), null log record, without output stream
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies publish(), null log record, without output stream.",
- method = "publish",
- args = {java.util.logging.LogRecord.class}
- )
- public void testPublish_Null_NoOutputStream() {
- StreamHandler h = new StreamHandler();
- h.publish(null);
- // regression test for Harmony-1279
- MockFilter filter = new MockFilter();
- h.setLevel(Level.FINER);
- h.setFilter(filter);
- LogRecord record = new LogRecord(Level.FINE, "abc");
- h.publish(record);
- // verify that filter.isLoggable is not called, because there's no
- // associated output stream.
- assertTrue(CallVerificationStack.getInstance().empty());
- }
-
- /*
- * Test publish(), a log record with empty msg, having output stream
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies publish(), a log record with empty msg, having output stream.",
- method = "publish",
- args = {java.util.logging.LogRecord.class}
- )
- public void testPublish_EmptyMsg() {
- ByteArrayOutputStream aos = new ByteArrayOutputStream();
- StreamHandler h = new StreamHandler(aos, new MockFormatter());
- LogRecord r = new LogRecord(Level.INFO, "");
- h.publish(r);
- h.flush();
- assertEquals("MockFormatter_Head", aos.toString());
- }
-
- /*
- * Test publish(), a log record with null msg, having output stream
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies publish(), a log record with null msg, having output stream.",
- method = "publish",
- args = {java.util.logging.LogRecord.class}
- )
- public void testPublish_NullMsg() {
- ByteArrayOutputStream aos = new ByteArrayOutputStream();
- StreamHandler h = new StreamHandler(aos, new MockFormatter());
- LogRecord r = new LogRecord(Level.INFO, null);
- h.publish(r);
- h.flush();
- assertEquals("MockFormatter_Head", aos.toString());
- }
-
- /*
- * Test publish(), after close.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies publish(), after close.",
- method = "publish",
- args = {java.util.logging.LogRecord.class}
- )
- public void testPublish_AfterClose() throws Exception {
- Properties p = new Properties();
- p.put("java.util.logging.StreamHandler.level", "FINE");
- LogManager.getLogManager().readConfiguration(
- EnvironmentHelper.PropertiesToInputStream(p));
-
- ByteArrayOutputStream aos = new ByteArrayOutputStream();
- StreamHandler h = new StreamHandler(aos, new MockFormatter());
- assertSame(h.getLevel(), Level.FINE);
- LogRecord r = new LogRecord(Level.INFO, "testPublish_NoFormatter");
- assertTrue(h.isLoggable(r));
- h.close();
- assertFalse(h.isLoggable(r));
- h.publish(r);
- h.flush();
- assertEquals("MockFormatter_HeadMockFormatter_Tail", aos.toString());
- }
-
- /*
- * Test setEncoding() method with supported encoding.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies setEncoding() method with supported encoding.",
- method = "setEncoding",
- args = {java.lang.String.class}
- )
- public void testSetEncoding_Normal() throws Exception {
- ByteArrayOutputStream aos = new ByteArrayOutputStream();
- StreamHandler h = new StreamHandler(aos, new MockFormatter());
- h.setEncoding("iso-8859-1");
- assertEquals("iso-8859-1", h.getEncoding());
- LogRecord r = new LogRecord(Level.INFO, "\u6881\u884D\u8F69");
- h.publish(r);
- h.flush();
-
- byte[] bytes = encoder.encode(
- CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69"))
- .array();
- assertTrue(Arrays.equals(bytes, aos.toByteArray()));
- }
-
- /*
- * Test setEncoding() method with supported encoding, after a log record
- * has been written.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies setEncoding() method with supported encoding, after a log record has been written.",
- method = "setEncoding",
- args = {java.lang.String.class}
- )
- public void testSetEncoding_AfterPublish() throws Exception {
- ByteArrayOutputStream aos = new ByteArrayOutputStream();
- StreamHandler h = new StreamHandler(aos, new MockFormatter());
- h.setEncoding("iso-8859-1");
- assertEquals("iso-8859-1", h.getEncoding());
- LogRecord r = new LogRecord(Level.INFO, "\u6881\u884D\u8F69");
- h.publish(r);
- h.flush();
- assertTrue(Arrays.equals(aos.toByteArray(), encoder.encode(
- CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69"))
- .array()));
-
- h.setEncoding("iso8859-1");
- assertEquals("iso8859-1", h.getEncoding());
- r = new LogRecord(Level.INFO, "\u6881\u884D\u8F69");
- h.publish(r);
- h.flush();
- assertFalse(Arrays.equals(aos.toByteArray(), encoder.encode(
- CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69"
- + "testSetEncoding_Normal2")).array()));
- byte[] b0 = aos.toByteArray();
- byte[] b1 = encoder.encode(
- CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69"))
- .array();
- byte[] b2 = encoder.encode(CharBuffer.wrap("\u6881\u884D\u8F69"))
- .array();
- byte[] b3 = new byte[b1.length + b2.length];
- System.arraycopy(b1, 0, b3, 0, b1.length);
- System.arraycopy(b2, 0, b3, b1.length, b2.length);
- assertTrue(Arrays.equals(b0, b3));
- }
-
- /*
- * Test setEncoding() methods with null.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies setEncoding() methods with null.",
- method = "setEncoding",
- args = {java.lang.String.class}
- )
- public void testSetEncoding_Null() throws Exception {
- StreamHandler h = new StreamHandler();
- h.setEncoding(null);
- assertNull(h.getEncoding());
- }
-
- /*
- * Test setEncoding() methods with unsupported encoding.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies setEncoding() methods with unsupported encoding.",
- method = "setEncoding",
- args = {java.lang.String.class}
- )
- public void testSetEncoding_Unsupported() {
- StreamHandler h = new StreamHandler();
- try {
- h.setEncoding("impossible");
- fail("Should throw UnsupportedEncodingException!");
- } catch (UnsupportedEncodingException e) {
- // expected
- }
- assertNull(h.getEncoding());
- }
-
- /*
- * Test setEncoding() with insufficient privilege.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies setEncoding() method with insufficient privilege.",
- method = "setEncoding",
- args = {java.lang.String.class}
- )
- public void testSetEncoding_InsufficientPrivilege() throws Exception {
- StreamHandler h = new StreamHandler();
- SecurityManager oldMan = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
- // set a normal value
- try {
- h.setEncoding("iso-8859-1");
- fail("Should throw SecurityException!");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldMan);
- }
- assertNull(h.getEncoding());
- System.setSecurityManager(new MockSecurityManager());
- // set an invalid value
- try {
-
- h.setEncoding("impossible");
- fail("Should throw SecurityException!");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldMan);
- }
- assertNull(h.getEncoding());
- }
-
- /*
- * Test setEncoding() methods will flush a stream before setting.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies that setEncoding() method will flush a stream before setting.",
- method = "setEncoding",
- args = {java.lang.String.class}
- )
- public void testSetEncoding_FlushBeforeSetting() throws Exception {
- ByteArrayOutputStream aos = new ByteArrayOutputStream();
- StreamHandler h = new StreamHandler(aos, new MockFormatter());
- LogRecord r = new LogRecord(Level.INFO, "abcd");
- h.publish(r);
- assertFalse(aos.toString().indexOf("abcd") > 0);
- h.setEncoding("iso-8859-1");
- assertTrue(aos.toString().indexOf("abcd") > 0);
- }
-
- /*
- * Test setOutputStream() with null.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies setOutputStream() method with null.",
- method = "setOutputStream",
- args = {java.io.OutputStream.class}
- )
- public void testSetOutputStream_null() {
- MockStreamHandler h = new MockStreamHandler(
- new ByteArrayOutputStream(), new SimpleFormatter());
- try {
- h.setOutputStream(null);
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /*
- * Test setOutputStream() under normal condition.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies setOutputStream() method under normal condition.",
- method = "setOutputStream",
- args = {java.io.OutputStream.class}
- )
- public void testSetOutputStream_Normal() {
- ByteArrayOutputStream aos = new ByteArrayOutputStream();
- MockStreamHandler h = new MockStreamHandler(aos, new MockFormatter());
-
- LogRecord r = new LogRecord(Level.INFO, "testSetOutputStream_Normal");
- h.publish(r);
- assertSame(r, CallVerificationStack.getInstance().pop());
- assertTrue(CallVerificationStack.getInstance().empty());
- h.flush();
- assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal", aos
- .toString());
-
- ByteArrayOutputStream aos2 = new ByteArrayOutputStream();
- h.setOutputStream(aos2);
- assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal"
- + "MockFormatter_Tail", aos.toString());
- r = new LogRecord(Level.INFO, "testSetOutputStream_Normal2");
- h.publish(r);
- assertSame(r, CallVerificationStack.getInstance().pop());
- assertTrue(CallVerificationStack.getInstance().empty());
- h.flush();
- assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal2", aos2
- .toString());
- assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal"
- + "MockFormatter_Tail", aos.toString());
- }
-
- /*
- * Test setOutputStream() after close.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies setOutputStream() method after close.",
- method = "setOutputStream",
- args = {java.io.OutputStream.class}
- )
- public void testSetOutputStream_AfterClose() {
- ByteArrayOutputStream aos = new ByteArrayOutputStream();
- MockStreamHandler h = new MockStreamHandler(aos, new MockFormatter());
-
- LogRecord r = new LogRecord(Level.INFO, "testSetOutputStream_Normal");
- h.publish(r);
- assertSame(r, CallVerificationStack.getInstance().pop());
- assertTrue(CallVerificationStack.getInstance().empty());
- h.flush();
- assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal", aos
- .toString());
- h.close();
-
- ByteArrayOutputStream aos2 = new ByteArrayOutputStream();
- h.setOutputStream(aos2);
- assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal"
- + "MockFormatter_Tail", aos.toString());
- r = new LogRecord(Level.INFO, "testSetOutputStream_Normal2");
- h.publish(r);
- assertSame(r, CallVerificationStack.getInstance().pop());
- assertTrue(CallVerificationStack.getInstance().empty());
- h.flush();
- assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal2", aos2
- .toString());
- assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal"
- + "MockFormatter_Tail", aos.toString());
- }
-
- /*
- * Test setOutputStream() when having insufficient privilege.
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies setOutputStream() method when having insufficient privilege.",
- method = "setOutputStream",
- args = {java.io.OutputStream.class}
- )
- public void testSetOutputStream_InsufficientPrivilege() {
- MockStreamHandler h = new MockStreamHandler();
- SecurityManager oldMan = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
-
- try {
- h.setOutputStream(new ByteArrayOutputStream());
- fail("Should throw SecurityException!");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldMan);
- }
-
- h = new MockStreamHandler();
- System.setSecurityManager(new MockSecurityManager());
- try {
- h.setOutputStream(null);
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- // expected
- } finally {
- System.setSecurityManager(oldMan);
- }
- }
-
- /*
- * A mock stream handler, expose setOutputStream.
- */
- public static class MockStreamHandler extends StreamHandler {
- public MockStreamHandler() {
- super();
- }
-
- public MockStreamHandler(OutputStream out, Formatter formatter) {
- super(out, formatter);
- }
-
- public void setOutputStream(OutputStream out) {
- super.setOutputStream(out);
- }
-
- public boolean isLoggable(LogRecord r) {
- CallVerificationStack.getInstance().push(r);
- return super.isLoggable(r);
- }
- }
-
- /*
- * A mock filter, always return false.
- */
- public static class MockFilter implements Filter {
-
- public boolean isLoggable(LogRecord record) {
- CallVerificationStack.getInstance().push(record);
- return false;
- }
- }
-
- /*
- * A mock formatter.
- */
- public static class MockFormatter extends java.util.logging.Formatter {
- public String format(LogRecord r) {
- // System.out.println("formatter called...");
- return super.formatMessage(r);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.util.logging.Formatter#getHead(java.util.logging.Handler)
- */
- public String getHead(Handler h) {
- return "MockFormatter_Head";
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.util.logging.Formatter#getTail(java.util.logging.Handler)
- */
- public String getTail(Handler h) {
- return "MockFormatter_Tail";
- }
- }
-
- /*
- * Another mock formatter.
- */
- public static class MockFormatter2 extends java.util.logging.Formatter {
- public String format(LogRecord r) {
- // System.out.println("formatter2 called...");
- return r.getMessage();
- }
- }
-
- /*
- * A mock output stream.
- */
- public static class MockOutputStream extends ByteArrayOutputStream {
-
- /*
- * (non-Javadoc)
- *
- * @see java.io.OutputStream#close()
- */
- public void close() throws IOException {
- CallVerificationStack.getInstance().push(null);
- super.close();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.io.OutputStream#flush()
- */
- public void flush() throws IOException {
- CallVerificationStack.getInstance().push(null);
- super.flush();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.io.OutputStream#write(int)
- */
- public void write(int oneByte) {
- super.write(oneByte);
- }
- }
-
- /*
- * A mock output stream that always throw exception.
- */
- public static class MockExceptionOutputStream extends ByteArrayOutputStream {
-
- /*
- * (non-Javadoc)
- *
- * @see java.io.OutputStream#close()
- */
- public void close() throws IOException {
- throw new IOException();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.io.OutputStream#flush()
- */
- public void flush() throws IOException {
- throw new IOException();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.io.OutputStream#write(byte[], int, int)
- */
- public synchronized void write(byte[] buffer, int offset, int count) {
- throw new NullPointerException();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.io.OutputStream#write(int)
- */
- public synchronized void write(int oneByte) {
- throw new NullPointerException();
- }
- }
-
- /*
- * Used to grant all permissions except logging control.
- */
- public static class MockSecurityManager extends SecurityManager {
-
- public MockSecurityManager() {
- }
-
- public void checkPermission(Permission perm) {
- // grant all permissions except logging control
- if (perm instanceof LoggingPermission) {
- throw new SecurityException();
- }
- }
-
- public void checkPermission(Permission perm, Object context) {
- // grant all permissions except logging control
- if (perm instanceof LoggingPermission) {
- throw new SecurityException();
- }
- }
- }
+ }
+
+ /*
+ * Test the constructor with no parameter, and no relevant log manager
+ * properties are set.
+ */
+ public void testConstructor_NoParameter_NoProperties() {
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.level"));
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.filter"));
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.formatter"));
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.encoding"));
+
+ StreamHandler h = new StreamHandler();
+ assertSame(Level.INFO, h.getLevel());
+ assertTrue(h.getFormatter() instanceof SimpleFormatter);
+ assertNull(h.getFilter());
+ assertNull(h.getEncoding());
+ }
+
+ /*
+ * Test the constructor with insufficient privilege.
+ */
+ public void testConstructor_NoParameter_InsufficientPrivilege() {
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.level"));
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.filter"));
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.formatter"));
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.encoding"));
+
+ SecurityManager oldMan = System.getSecurityManager();
+ System.setSecurityManager(new MockSecurityManager());
+ // set a normal value
+ try {
+ StreamHandler h = new StreamHandler();
+ assertSame(Level.INFO, h.getLevel());
+ assertTrue(h.getFormatter() instanceof SimpleFormatter);
+ assertNull(h.getFilter());
+ assertNull(h.getEncoding());
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ }
+
+ /*
+ * Test the constructor with no parameter, and valid relevant log manager
+ * properties are set.
+ */
+ public void testConstructor_NoParameter_ValidProperties() throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.StreamHandler.level", "FINE");
+ p.put("java.util.logging.StreamHandler.filter", className
+ + "$MockFilter");
+ p.put("java.util.logging.StreamHandler.formatter", className
+ + "$MockFormatter");
+ p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+
+ assertEquals("FINE", LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.level"));
+ assertEquals("iso-8859-1", LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.encoding"));
+ StreamHandler h = new StreamHandler();
+ assertSame(h.getLevel(), Level.parse("FINE"));
+ assertTrue(h.getFormatter() instanceof MockFormatter);
+ assertTrue(h.getFilter() instanceof MockFilter);
+ assertEquals("iso-8859-1", h.getEncoding());
+ }
+
+ /*
+ * Test the constructor with no parameter, and invalid relevant log manager
+ * properties are set.
+ */
+ public void testConstructor_NoParameter_InvalidProperties()
+ throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.StreamHandler.level", INVALID_LEVEL);
+ p.put("java.util.logging.StreamHandler.filter", className + "");
+ p.put("java.util.logging.StreamHandler.formatter", className + "");
+ p.put("java.util.logging.StreamHandler.encoding", "XXXX");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+
+ assertEquals(INVALID_LEVEL, LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.level"));
+ assertEquals("XXXX", LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.encoding"));
+ StreamHandler h = new StreamHandler();
+ assertSame(Level.INFO, h.getLevel());
+ assertTrue(h.getFormatter() instanceof SimpleFormatter);
+ assertNull(h.getFilter());
+ assertNull(h.getEncoding());
+ h.publish(new LogRecord(Level.SEVERE, "test"));
+ assertTrue(CallVerificationStack.getInstance().empty());
+ assertNull(h.getEncoding());
+ }
+
+ /*
+ * Test the constructor with normal parameter values, and no relevant log
+ * manager properties are set.
+ */
+ public void testConstructor_HasParameters_NoProperties() {
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.level"));
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.filter"));
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.formatter"));
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.encoding"));
+
+ StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
+ new MockFormatter2());
+ assertSame(Level.INFO, h.getLevel());
+ assertTrue(h.getFormatter() instanceof MockFormatter2);
+ assertNull(h.getFilter());
+ assertNull(h.getEncoding());
+ }
+
+ /*
+ * Test the constructor with insufficient privilege.
+ */
+ public void testConstructor_HasParameter_InsufficientPrivilege() {
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.level"));
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.filter"));
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.formatter"));
+ assertNull(LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.encoding"));
+
+ SecurityManager oldMan = System.getSecurityManager();
+ System.setSecurityManager(new MockSecurityManager());
+ // set a normal value
+ try {
+ StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
+ new MockFormatter2());
+ assertSame(Level.INFO, h.getLevel());
+ assertTrue(h.getFormatter() instanceof MockFormatter2);
+ assertNull(h.getFilter());
+ assertNull(h.getEncoding());
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ }
+
+ /*
+ * Test the constructor with normal parameter values, and valid relevant log
+ * manager properties are set.
+ */
+ public void testConstructor_HasParameters_ValidProperties()
+ throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.StreamHandler.level", "FINE");
+ p.put("java.util.logging.StreamHandler.filter", className
+ + "$MockFilter");
+ p.put("java.util.logging.StreamHandler.formatter", className
+ + "$MockFormatter");
+ p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+
+ assertEquals("FINE", LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.level"));
+ assertEquals("iso-8859-1", LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.encoding"));
+ StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
+ new MockFormatter2());
+ assertSame(h.getLevel(), Level.parse("FINE"));
+ assertTrue(h.getFormatter() instanceof MockFormatter2);
+ assertTrue(h.getFilter() instanceof MockFilter);
+ assertEquals("iso-8859-1", h.getEncoding());
+ }
+
+ /*
+ * Test the constructor with normal parameter, and invalid relevant log
+ * manager properties are set.
+ */
+ public void testConstructor_HasParameters_InvalidProperties()
+ throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.StreamHandler.level", INVALID_LEVEL);
+ p.put("java.util.logging.StreamHandler.filter", className + "");
+ p.put("java.util.logging.StreamHandler.formatter", className + "");
+ p.put("java.util.logging.StreamHandler.encoding", "XXXX");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+
+ assertEquals(INVALID_LEVEL, LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.level"));
+ assertEquals("XXXX", LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.encoding"));
+ StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
+ new MockFormatter2());
+ assertSame(Level.INFO, h.getLevel());
+ assertTrue(h.getFormatter() instanceof MockFormatter2);
+ assertNull(h.getFilter());
+ assertNull(h.getEncoding());
+ }
+
+ /*
+ * Test the constructor with null formatter, and invalid relevant log manager
+ * properties are set.
+ */
+ public void testConstructor_HasParameters_ValidPropertiesNullStream()
+ throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.StreamHandler.level", "FINE");
+ p.put("java.util.logging.StreamHandler.filter", className
+ + "$MockFilter");
+ p.put("java.util.logging.StreamHandler.formatter", className
+ + "$MockFormatter");
+ p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+
+ assertEquals("FINE", LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.level"));
+ assertEquals("iso-8859-1", LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.encoding"));
+ try {
+ new StreamHandler(new ByteArrayOutputStream(), null);
+ fail("Should throw NullPointerException!");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Test the constructor with null output stream, and invalid relevant log
+ * manager properties are set.
+ */
+ public void testConstructor_HasParameters_ValidPropertiesNullFormatter()
+ throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.StreamHandler.level", "FINE");
+ p.put("java.util.logging.StreamHandler.filter", className
+ + "$MockFilter");
+ p.put("java.util.logging.StreamHandler.formatter", className
+ + "$MockFormatter");
+ p.put("java.util.logging.StreamHandler.encoding", "iso-8859-1");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+
+ assertEquals("FINE", LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.level"));
+ assertEquals("iso-8859-1", LogManager.getLogManager().getProperty(
+ "java.util.logging.StreamHandler.encoding"));
+ try {
+ new StreamHandler(null, new MockFormatter2());
+ fail("Should throw NullPointerException!");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Test close() when having sufficient privilege, and a record has been
+ * written to the output stream.
+ */
+ public void testClose_SufficientPrivilege_NormalClose() {
+ ByteArrayOutputStream aos = new MockOutputStream();
+ StreamHandler h = new StreamHandler(aos, new MockFormatter());
+ h.publish(new LogRecord(Level.SEVERE,
+ "testClose_SufficientPrivilege_NormalClose msg"));
+ h.close();
+ assertEquals("close", CallVerificationStack.getInstance()
+ .getCurrentSourceMethod());
+ assertNull(CallVerificationStack.getInstance().pop());
+ assertEquals("flush", CallVerificationStack.getInstance()
+ .getCurrentSourceMethod());
+ CallVerificationStack.getInstance().clear();
+ assertTrue(aos.toString().endsWith("MockFormatter_Tail"));
+ h.close();
+ }
+
+ /*
+ * Test close() when having sufficient privilege, and an output stream that
+ * always throws exceptions.
+ */
+ public void testClose_SufficientPrivilege_Exception() {
+ ByteArrayOutputStream aos = new MockExceptionOutputStream();
+ StreamHandler h = new StreamHandler(aos, new MockFormatter());
+ h.publish(new LogRecord(Level.SEVERE,
+ "testClose_SufficientPrivilege_Exception msg"));
+ h.flush();
+ h.close();
+ }
+
+ /*
+ * Test close() when having sufficient privilege, and no record has been
+ * written to the output stream.
+ */
+ public void testClose_SufficientPrivilege_DirectClose() {
+ ByteArrayOutputStream aos = new MockOutputStream();
+ StreamHandler h = new StreamHandler(aos, new MockFormatter());
+ h.close();
+ assertEquals("close", CallVerificationStack.getInstance()
+ .getCurrentSourceMethod());
+ assertNull(CallVerificationStack.getInstance().pop());
+ assertEquals("flush", CallVerificationStack.getInstance()
+ .getCurrentSourceMethod());
+ CallVerificationStack.getInstance().clear();
+ assertEquals("MockFormatter_HeadMockFormatter_Tail", aos.toString()
+ );
+ }
+
+ /*
+ * Test close() when having insufficient privilege.
+ */
+ public void testClose_InsufficientPrivilege() {
+ SecurityManager oldMan = System.getSecurityManager();
+ System.setSecurityManager(new MockSecurityManager());
+ try {
+ StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
+ new MockFormatter());
+ h.close();
+ fail("Should throw SecurityException!");
+ } catch (SecurityException e) {
+ // expected
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ }
+
+ /*
+ * Test close() when having no output stream.
+ */
+ public void testClose_NoOutputStream() {
+ StreamHandler h = new StreamHandler();
+ h.close();
+ }
+
+ /*
+ * Test flush().
+ */
+ public void testFlush_Normal() {
+ ByteArrayOutputStream aos = new MockOutputStream();
+ StreamHandler h = new StreamHandler(aos, new MockFormatter());
+ h.flush();
+ assertEquals("flush", CallVerificationStack.getInstance()
+ .getCurrentSourceMethod());
+ assertNull(CallVerificationStack.getInstance().pop());
+ CallVerificationStack.getInstance().clear();
+ }
+
+ /*
+ * Test flush() when having no output stream.
+ */
+ public void testFlush_NoOutputStream() {
+ StreamHandler h = new StreamHandler();
+ h.flush();
+ }
+
+ /*
+ * Test isLoggable(), use no filter, having output stream
+ */
+ public void testIsLoggable_NoOutputStream() {
+ StreamHandler h = new StreamHandler();
+ LogRecord r = new LogRecord(Level.INFO, null);
+ assertFalse(h.isLoggable(r));
+
+ h.setLevel(Level.WARNING);
+ assertFalse(h.isLoggable(r));
+
+ h.setLevel(Level.CONFIG);
+ assertFalse(h.isLoggable(r));
+
+ r.setLevel(Level.OFF);
+ h.setLevel(Level.OFF);
+ assertFalse(h.isLoggable(r));
+ }
+
+ /*
+ * Test isLoggable(), use no filter, having output stream
+ */
+ public void testIsLoggable_NoFilter() {
+ StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
+ new SimpleFormatter());
+ LogRecord r = new LogRecord(Level.INFO, null);
+ assertTrue(h.isLoggable(r));
+
+ h.setLevel(Level.WARNING);
+ assertFalse(h.isLoggable(r));
+
+ h.setLevel(Level.CONFIG);
+ assertTrue(h.isLoggable(r));
+
+ r.setLevel(Level.OFF);
+ h.setLevel(Level.OFF);
+ assertFalse(h.isLoggable(r));
+ }
+
+ /*
+ * Test isLoggable(), use a filter, having output stream
+ */
+ public void testIsLoggable_WithFilter() {
+ StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
+ new SimpleFormatter());
+ LogRecord r = new LogRecord(Level.INFO, null);
+ h.setFilter(new MockFilter());
+ assertFalse(h.isLoggable(r));
+ assertSame(r, CallVerificationStack.getInstance().pop());
+
+ h.setLevel(Level.CONFIG);
+ assertFalse(h.isLoggable(r));
+ assertSame(r, CallVerificationStack.getInstance().pop());
+
+ h.setLevel(Level.WARNING);
+ assertFalse(h.isLoggable(r));
+ assertTrue(CallVerificationStack.getInstance().empty());
+ }
+
+ /*
+ * Test isLoggable(), null log record, having output stream. Handler should
+ * call ErrorManager to handle exceptional case
+ */
+ public void testIsLoggable_Null() {
+ StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
+ new SimpleFormatter());
+ assertFalse(h.isLoggable(null));
+ }
+
+ /*
+ * Test isLoggable(), null log record, without output stream
+ */
+ public void testIsLoggable_Null_NoOutputStream() {
+ StreamHandler h = new StreamHandler();
+ assertFalse(h.isLoggable(null));
+ }
+
+ /*
+ * Test publish(), use no filter, having output stream, normal log record.
+ */
+ public void testPublish_NoOutputStream() {
+ StreamHandler h = new StreamHandler();
+ LogRecord r = new LogRecord(Level.INFO, "testPublish_NoOutputStream");
+ h.publish(r);
+
+ h.setLevel(Level.WARNING);
+ h.publish(r);
+
+ h.setLevel(Level.CONFIG);
+ h.publish(r);
+
+ r.setLevel(Level.OFF);
+ h.setLevel(Level.OFF);
+ h.publish(r);
+ }
+
+ /*
+ * Test publish(), use no filter, having output stream, normal log record.
+ */
+ public void testPublish_NoFilter() {
+ ByteArrayOutputStream aos = new ByteArrayOutputStream();
+ StreamHandler h = new StreamHandler(aos, new MockFormatter());
+
+ LogRecord r = new LogRecord(Level.INFO, "testPublish_NoFilter");
+ h.setLevel(Level.INFO);
+ h.publish(r);
+ h.flush();
+ assertEquals("MockFormatter_Head" + "testPublish_NoFilter", aos
+ .toString());
+
+ h.setLevel(Level.WARNING);
+ h.publish(r);
+ h.flush();
+ assertEquals("MockFormatter_Head" + "testPublish_NoFilter", aos
+ .toString());
+
+ h.setLevel(Level.CONFIG);
+ h.publish(r);
+ h.flush();
+ assertEquals("MockFormatter_Head" + "testPublish_NoFilter"
+ + "testPublish_NoFilter", aos.toString());
+
+ r.setLevel(Level.OFF);
+ h.setLevel(Level.OFF);
+ h.publish(r);
+ h.flush();
+ assertEquals("MockFormatter_Head" + "testPublish_NoFilter"
+ + "testPublish_NoFilter", aos.toString());
+ }
+
+ /*
+ * Test publish(), use a filter, having output stream, normal log record.
+ */
+ public void testPublish_WithFilter() {
+ ByteArrayOutputStream aos = new ByteArrayOutputStream();
+ StreamHandler h = new StreamHandler(aos, new MockFormatter());
+ h.setFilter(new MockFilter());
+
+ LogRecord r = new LogRecord(Level.INFO, "testPublish_WithFilter");
+ h.setLevel(Level.INFO);
+ h.publish(r);
+ h.flush();
+ assertEquals("", aos.toString());
+ assertSame(r, CallVerificationStack.getInstance().pop());
+
+ h.setLevel(Level.WARNING);
+ h.publish(r);
+ h.flush();
+ assertEquals("", aos.toString());
+ assertTrue(CallVerificationStack.getInstance().empty());
+
+ h.setLevel(Level.CONFIG);
+ h.publish(r);
+ h.flush();
+ assertEquals("", aos.toString());
+ assertSame(r, CallVerificationStack.getInstance().pop());
+
+ r.setLevel(Level.OFF);
+ h.setLevel(Level.OFF);
+ h.publish(r);
+ h.flush();
+ assertEquals("", aos.toString());
+ assertTrue(CallVerificationStack.getInstance().empty());
+ }
+
+ /*
+ * Test publish(), null log record, handler should call ErrorManager to
+ * handle exceptional case
+ */
+ public void testPublish_Null() {
+ StreamHandler h = new StreamHandler(new ByteArrayOutputStream(),
+ new SimpleFormatter());
+ h.publish(null);
+ }
+
+ /*
+ * Test publish(), null log record, without output stream
+ */
+ public void testPublish_Null_NoOutputStream() {
+ StreamHandler h = new StreamHandler();
+ h.publish(null);
+ // regression test for Harmony-1279
+ MockFilter filter = new MockFilter();
+ h.setLevel(Level.FINER);
+ h.setFilter(filter);
+ LogRecord record = new LogRecord(Level.FINE, "abc");
+ h.publish(record);
+ // verify that filter.isLoggable is not called, because there's no
+ // associated output stream.
+ assertTrue(CallVerificationStack.getInstance().empty());
+ }
+
+ /*
+ * Test publish(), a log record with empty msg, having output stream
+ */
+ public void testPublish_EmptyMsg() {
+ ByteArrayOutputStream aos = new ByteArrayOutputStream();
+ StreamHandler h = new StreamHandler(aos, new MockFormatter());
+ LogRecord r = new LogRecord(Level.INFO, "");
+ h.publish(r);
+ h.flush();
+ assertEquals("MockFormatter_Head", aos.toString());
+ }
+
+ /*
+ * Test publish(), a log record with null msg, having output stream
+ */
+ public void testPublish_NullMsg() {
+ ByteArrayOutputStream aos = new ByteArrayOutputStream();
+ StreamHandler h = new StreamHandler(aos, new MockFormatter());
+ LogRecord r = new LogRecord(Level.INFO, null);
+ h.publish(r);
+ h.flush();
+ assertEquals("MockFormatter_Head", aos.toString());
+ }
+
+ /*
+ * Test publish(), after close.
+ */
+ public void testPublish_AfterClose() throws Exception {
+ Properties p = new Properties();
+ p.put("java.util.logging.StreamHandler.level", "FINE");
+ LogManager.getLogManager().readConfiguration(
+ EnvironmentHelper.PropertiesToInputStream(p));
+
+ ByteArrayOutputStream aos = new ByteArrayOutputStream();
+ StreamHandler h = new StreamHandler(aos, new MockFormatter());
+ assertSame(h.getLevel(), Level.FINE);
+ LogRecord r = new LogRecord(Level.INFO, "testPublish_NoFormatter");
+ assertTrue(h.isLoggable(r));
+ h.close();
+ assertFalse(h.isLoggable(r));
+ h.publish(r);
+ h.flush();
+ assertEquals("MockFormatter_HeadMockFormatter_Tail", aos.toString());
+ }
+
+ /*
+ * Test setEncoding() method with supported encoding.
+ */
+ public void testSetEncoding_Normal() throws Exception {
+ ByteArrayOutputStream aos = new ByteArrayOutputStream();
+ StreamHandler h = new StreamHandler(aos, new MockFormatter());
+ h.setEncoding("iso-8859-1");
+ assertEquals("iso-8859-1", h.getEncoding());
+ LogRecord r = new LogRecord(Level.INFO, "\u6881\u884D\u8F69");
+ h.publish(r);
+ h.flush();
+
+ byte[] bytes = encoder.encode(
+ CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69"))
+ .array();
+ assertTrue(Arrays.equals(bytes, aos.toByteArray()));
+ }
+
+ /*
+ * Test setEncoding() method with supported encoding, after a log record
+ * has been written.
+ */
+ public void testSetEncoding_AfterPublish() throws Exception {
+ ByteArrayOutputStream aos = new ByteArrayOutputStream();
+ StreamHandler h = new StreamHandler(aos, new MockFormatter());
+ h.setEncoding("iso-8859-1");
+ assertEquals("iso-8859-1", h.getEncoding());
+ LogRecord r = new LogRecord(Level.INFO, "\u6881\u884D\u8F69");
+ h.publish(r);
+ h.flush();
+ assertTrue(Arrays.equals(aos.toByteArray(), encoder.encode(
+ CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69"))
+ .array()));
+
+ h.setEncoding("iso8859-1");
+ assertEquals("iso8859-1", h.getEncoding());
+ r = new LogRecord(Level.INFO, "\u6881\u884D\u8F69");
+ h.publish(r);
+ h.flush();
+ assertFalse(Arrays.equals(aos.toByteArray(), encoder.encode(
+ CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69"
+ + "testSetEncoding_Normal2")).array()));
+ byte[] b0 = aos.toByteArray();
+ byte[] b1 = encoder.encode(
+ CharBuffer.wrap("MockFormatter_Head" + "\u6881\u884D\u8F69"))
+ .array();
+ byte[] b2 = encoder.encode(CharBuffer.wrap("\u6881\u884D\u8F69"))
+ .array();
+ byte[] b3 = new byte[b1.length + b2.length];
+ System.arraycopy(b1, 0, b3, 0, b1.length);
+ System.arraycopy(b2, 0, b3, b1.length, b2.length);
+ assertTrue(Arrays.equals(b0, b3));
+ }
+
+ /*
+ * Test setEncoding() methods with null.
+ */
+ public void testSetEncoding_Null() throws Exception {
+ StreamHandler h = new StreamHandler();
+ h.setEncoding(null);
+ assertNull(h.getEncoding());
+ }
+
+ /*
+ * Test setEncoding() methods with unsupported encoding.
+ */
+ public void testSetEncoding_Unsupported() {
+ StreamHandler h = new StreamHandler();
+ try {
+ h.setEncoding("impossible");
+ fail("Should throw UnsupportedEncodingException!");
+ } catch (UnsupportedEncodingException e) {
+ // expected
+ }
+ assertNull(h.getEncoding());
+ }
+
+ /*
+ * Test setEncoding() with insufficient privilege.
+ */
+ public void testSetEncoding_InsufficientPrivilege() throws Exception {
+ StreamHandler h = new StreamHandler();
+ SecurityManager oldMan = System.getSecurityManager();
+ System.setSecurityManager(new MockSecurityManager());
+ // set a normal value
+ try {
+ h.setEncoding("iso-8859-1");
+ fail("Should throw SecurityException!");
+ } catch (SecurityException e) {
+ // expected
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ assertNull(h.getEncoding());
+ System.setSecurityManager(new MockSecurityManager());
+ // set an invalid value
+ try {
+
+ h.setEncoding("impossible");
+ fail("Should throw SecurityException!");
+ } catch (SecurityException e) {
+ // expected
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ assertNull(h.getEncoding());
+ }
+
+ /*
+ * Test setEncoding() methods will flush a stream before setting.
+ */
+ public void testSetEncoding_FlushBeforeSetting() throws Exception {
+ ByteArrayOutputStream aos = new ByteArrayOutputStream();
+ StreamHandler h = new StreamHandler(aos, new MockFormatter());
+ LogRecord r = new LogRecord(Level.INFO, "abcd");
+ h.publish(r);
+ assertFalse(aos.toString().indexOf("abcd") > 0);
+ h.setEncoding("iso-8859-1");
+ assertTrue(aos.toString().indexOf("abcd") > 0);
+ }
+
+ /*
+ * Test setOutputStream() with null.
+ */
+ public void testSetOutputStream_null() {
+ MockStreamHandler h = new MockStreamHandler(
+ new ByteArrayOutputStream(), new SimpleFormatter());
+ try {
+ h.setOutputStream(null);
+ fail("Should throw NullPointerException!");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Test setOutputStream() under normal condition.
+ */
+ public void testSetOutputStream_Normal() {
+ ByteArrayOutputStream aos = new ByteArrayOutputStream();
+ MockStreamHandler h = new MockStreamHandler(aos, new MockFormatter());
+
+ LogRecord r = new LogRecord(Level.INFO, "testSetOutputStream_Normal");
+ h.publish(r);
+ assertSame(r, CallVerificationStack.getInstance().pop());
+ assertTrue(CallVerificationStack.getInstance().empty());
+ h.flush();
+ assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal", aos
+ .toString());
+
+ ByteArrayOutputStream aos2 = new ByteArrayOutputStream();
+ h.setOutputStream(aos2);
+ assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal"
+ + "MockFormatter_Tail", aos.toString());
+ r = new LogRecord(Level.INFO, "testSetOutputStream_Normal2");
+ h.publish(r);
+ assertSame(r, CallVerificationStack.getInstance().pop());
+ assertTrue(CallVerificationStack.getInstance().empty());
+ h.flush();
+ assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal2", aos2
+ .toString());
+ assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal"
+ + "MockFormatter_Tail", aos.toString());
+ }
+
+ /*
+ * Test setOutputStream() after close.
+ */
+ public void testSetOutputStream_AfterClose() {
+ ByteArrayOutputStream aos = new ByteArrayOutputStream();
+ MockStreamHandler h = new MockStreamHandler(aos, new MockFormatter());
+
+ LogRecord r = new LogRecord(Level.INFO, "testSetOutputStream_Normal");
+ h.publish(r);
+ assertSame(r, CallVerificationStack.getInstance().pop());
+ assertTrue(CallVerificationStack.getInstance().empty());
+ h.flush();
+ assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal", aos
+ .toString());
+ h.close();
+
+ ByteArrayOutputStream aos2 = new ByteArrayOutputStream();
+ h.setOutputStream(aos2);
+ assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal"
+ + "MockFormatter_Tail", aos.toString());
+ r = new LogRecord(Level.INFO, "testSetOutputStream_Normal2");
+ h.publish(r);
+ assertSame(r, CallVerificationStack.getInstance().pop());
+ assertTrue(CallVerificationStack.getInstance().empty());
+ h.flush();
+ assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal2", aos2
+ .toString());
+ assertEquals("MockFormatter_Head" + "testSetOutputStream_Normal"
+ + "MockFormatter_Tail", aos.toString());
+ }
+
+ /*
+ * Test setOutputStream() when having insufficient privilege.
+ */
+ public void testSetOutputStream_InsufficientPrivilege() {
+ MockStreamHandler h = new MockStreamHandler();
+ SecurityManager oldMan = System.getSecurityManager();
+ System.setSecurityManager(new MockSecurityManager());
+
+ try {
+ h.setOutputStream(new ByteArrayOutputStream());
+ fail("Should throw SecurityException!");
+ } catch (SecurityException e) {
+ // expected
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+
+ h = new MockStreamHandler();
+ System.setSecurityManager(new MockSecurityManager());
+ try {
+ h.setOutputStream(null);
+ fail("Should throw NullPointerException!");
+ } catch (NullPointerException e) {
+ // expected
+ } finally {
+ System.setSecurityManager(oldMan);
+ }
+ }
+
+ /*
+ * A mock stream handler, expose setOutputStream.
+ */
+ public static class MockStreamHandler extends StreamHandler {
+ public MockStreamHandler() {
+ super();
+ }
+
+ public MockStreamHandler(OutputStream out, Formatter formatter) {
+ super(out, formatter);
+ }
+
+ public void setOutputStream(OutputStream out) {
+ super.setOutputStream(out);
+ }
+
+ public boolean isLoggable(LogRecord r) {
+ CallVerificationStack.getInstance().push(r);
+ return super.isLoggable(r);
+ }
+ }
+
+ /*
+ * A mock filter, always return false.
+ */
+ public static class MockFilter implements Filter {
+
+ public boolean isLoggable(LogRecord record) {
+ CallVerificationStack.getInstance().push(record);
+ return false;
+ }
+ }
+
+ /*
+ * A mock formatter.
+ */
+ public static class MockFormatter extends java.util.logging.Formatter {
+ public String format(LogRecord r) {
+ // System.out.println("formatter called...");
+ return super.formatMessage(r);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.util.logging.Formatter#getHead(java.util.logging.Handler)
+ */
+ public String getHead(Handler h) {
+ return "MockFormatter_Head";
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.util.logging.Formatter#getTail(java.util.logging.Handler)
+ */
+ public String getTail(Handler h) {
+ return "MockFormatter_Tail";
+ }
+ }
+
+ /*
+ * Another mock formatter.
+ */
+ public static class MockFormatter2 extends java.util.logging.Formatter {
+ public String format(LogRecord r) {
+ // System.out.println("formatter2 called...");
+ return r.getMessage();
+ }
+ }
+
+ /*
+ * A mock output stream.
+ */
+ public static class MockOutputStream extends ByteArrayOutputStream {
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.OutputStream#close()
+ */
+ public void close() throws IOException {
+ CallVerificationStack.getInstance().push(null);
+ super.close();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.OutputStream#flush()
+ */
+ public void flush() throws IOException {
+ CallVerificationStack.getInstance().push(null);
+ super.flush();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.OutputStream#write(int)
+ */
+ public void write(int oneByte) {
+ // TODO Auto-generated method stub
+ super.write(oneByte);
+ }
+ }
+
+ /*
+ * A mock output stream that always throw exception.
+ */
+ public static class MockExceptionOutputStream extends ByteArrayOutputStream {
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.OutputStream#close()
+ */
+ public void close() throws IOException {
+ throw new IOException();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.OutputStream#flush()
+ */
+ public void flush() throws IOException {
+ throw new IOException();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.OutputStream#write(byte[], int, int)
+ */
+ public synchronized void write(byte[] buffer, int offset, int count) {
+ throw new NullPointerException();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.OutputStream#write(int)
+ */
+ public synchronized void write(int oneByte) {
+ throw new NullPointerException();
+ }
+ }
+
+ /*
+ * Used to grant all permissions except logging control.
+ */
+ public static class MockSecurityManager extends SecurityManager {
+
+ public MockSecurityManager() {
+ }
+
+ public void checkPermission(Permission perm) {
+ // grant all permissions except logging control
+ if (perm instanceof LoggingPermission) {
+ throw new SecurityException();
+ }
+ }
+
+ public void checkPermission(Permission perm, Object context) {
+ // grant all permissions except logging control
+ if (perm instanceof LoggingPermission) {
+ throw new SecurityException();
+ }
+ }
+ }
}
diff --git a/logging/src/test/java/tests/logging/AllTests.java b/logging/src/test/java/tests/logging/AllTests.java
index c6032df..aa0cb15 100644
--- a/logging/src/test/java/tests/logging/AllTests.java
+++ b/logging/src/test/java/tests/logging/AllTests.java
@@ -24,16 +24,11 @@ import junit.framework.TestSuite;
* Test suite that includes all tests for the Logging project.
*/
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 Logging test suites");
+ TestSuite suite = new TestSuite("All Logging test suites");
// $JUnit-BEGIN$
suite.addTest(org.apache.harmony.logging.tests.java.util.logging.AllTests.suite());
// $JUnit-END$
return suite;
}
-} \ No newline at end of file
+}
diff --git a/luni-kernel/src/test/java/java/lang/reflect/AllTests.java b/luni-kernel/src/test/java/java/lang/reflect/AllTests.java
index 7cf1475..8d99672 100644
--- a/luni-kernel/src/test/java/java/lang/reflect/AllTests.java
+++ b/luni-kernel/src/test/java/java/lang/reflect/AllTests.java
@@ -21,7 +21,7 @@ import junit.framework.TestSuite;
public class AllTests {
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite();
+ TestSuite suite = new TestSuite();
suite.addTestSuite(java.lang.reflect.ConstructorTest.class);
suite.addTestSuite(java.lang.reflect.MethodTest.class);
return suite;
diff --git a/luni-kernel/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/AllTests.java b/luni-kernel/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/AllTests.java
index a59cc3e..e9cf80e 100644
--- a/luni-kernel/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/AllTests.java
+++ b/luni-kernel/src/test/java/tests/api/org/apache/harmony/kernel/dalvik/AllTests.java
@@ -21,7 +21,7 @@ import junit.framework.TestSuite;
public class AllTests {
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite();
+ TestSuite suite = new TestSuite();
suite.addTestSuite(tests.api.org.apache.harmony.kernel.dalvik.ThreadsTest.class);
return suite;
}
diff --git a/luni/src/test/java/java/io/AllTests.java b/luni/src/test/java/java/io/AllTests.java
index 5e25922..43a28e0 100644
--- a/luni/src/test/java/java/io/AllTests.java
+++ b/luni/src/test/java/java/io/AllTests.java
@@ -21,7 +21,7 @@ import junit.framework.TestSuite;
public class AllTests {
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite();
+ TestSuite suite = new TestSuite();
suite.addTestSuite(java.io.FileTest.class);
return suite;
}
diff --git a/luni/src/test/java/java/lang/AllTests.java b/luni/src/test/java/java/lang/AllTests.java
index a40ef3a..38da14a 100644
--- a/luni/src/test/java/java/lang/AllTests.java
+++ b/luni/src/test/java/java/lang/AllTests.java
@@ -21,7 +21,7 @@ import junit.framework.TestSuite;
public class AllTests {
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite();
+ TestSuite suite = new TestSuite();
suite.addTestSuite(java.lang.FloatTest.class);
suite.addTestSuite(java.lang.ProcessBuilderTest.class);
return suite;
diff --git a/luni/src/test/java/java/net/AllTests.java b/luni/src/test/java/java/net/AllTests.java
index 3731af4..664d755 100644
--- a/luni/src/test/java/java/net/AllTests.java
+++ b/luni/src/test/java/java/net/AllTests.java
@@ -21,7 +21,7 @@ import junit.framework.TestSuite;
public class AllTests {
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite();
+ TestSuite suite = new TestSuite();
suite.addTestSuite(java.net.SocketTest.class);
suite.addTestSuite(java.net.URLConnectionTest.class);
return suite;
diff --git a/luni/src/test/java/java/nio/charset/AllTests.java b/luni/src/test/java/java/nio/charset/AllTests.java
index 6f45162..67957d4 100644
--- a/luni/src/test/java/java/nio/charset/AllTests.java
+++ b/luni/src/test/java/java/nio/charset/AllTests.java
@@ -21,7 +21,7 @@ import junit.framework.TestSuite;
public class AllTests {
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite();
+ TestSuite suite = new TestSuite();
suite.addTestSuite(java.nio.charset.CharsetDecoderTest.class);
return suite;
}
diff --git a/luni/src/test/java/java/text/AllTests.java b/luni/src/test/java/java/text/AllTests.java
index 4e96007..11598a5 100644
--- a/luni/src/test/java/java/text/AllTests.java
+++ b/luni/src/test/java/java/text/AllTests.java
@@ -21,7 +21,7 @@ import junit.framework.TestSuite;
public class AllTests {
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite();
+ TestSuite suite = new TestSuite();
suite.addTestSuite(java.text.DecimalFormatTest.class);
suite.addTestSuite(java.text.NumberFormatTest.class);
return suite;
diff --git a/luni/src/test/java/java/util/AllTests.java b/luni/src/test/java/java/util/AllTests.java
index 07fee27..3050c30 100644
--- a/luni/src/test/java/java/util/AllTests.java
+++ b/luni/src/test/java/java/util/AllTests.java
@@ -21,7 +21,7 @@ import junit.framework.TestSuite;
public class AllTests {
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite();
+ TestSuite suite = new TestSuite();
suite.addTestSuite(java.util.CalendarTest.class);
suite.addTestSuite(java.util.CurrencyTest.class);
suite.addTestSuite(java.util.DateTest.class);
diff --git a/luni/src/test/java/javax/xml/parsers/AllTests.java b/luni/src/test/java/javax/xml/parsers/AllTests.java
index 3e4a9c6..a838d3b 100644
--- a/luni/src/test/java/javax/xml/parsers/AllTests.java
+++ b/luni/src/test/java/javax/xml/parsers/AllTests.java
@@ -21,7 +21,7 @@ import junit.framework.TestSuite;
public class AllTests {
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite();
+ TestSuite suite = new TestSuite();
suite.addTestSuite(javax.xml.parsers.DocumentBuilderTest.class);
return suite;
}
diff --git a/luni/src/test/java/org/apache/harmony/luni/platform/AllTests.java b/luni/src/test/java/org/apache/harmony/luni/platform/AllTests.java
index be28d41..bfba0b5 100644
--- a/luni/src/test/java/org/apache/harmony/luni/platform/AllTests.java
+++ b/luni/src/test/java/org/apache/harmony/luni/platform/AllTests.java
@@ -27,7 +27,7 @@ public class AllTests {
}
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for org.apache.harmony.luni.platform");
+ TestSuite suite = new TestSuite("Tests for org.apache.harmony.luni.platform");
suite.addTestSuite(OSMemoryTest.class);
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
index 6b4cbd0..89faac1 100644
--- 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
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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.");
+ TestSuite suite = new TestSuite("Tests for HttpURLConnecton, HttpsURLConnection.");
// $JUnit-BEGIN$
suite.addTestSuite(HttpURLConnectionTest.class);
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
index a58850b..e03633d 100644
--- 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
@@ -25,13 +25,8 @@ import junit.framework.TestSuite;
*/
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.");
+ TestSuite suite = new TestSuite("Tests for HttpURLConnecton, HttpsURLConnection.");
// $JUnit-BEGIN$
suite.addTestSuite(HttpsURLConnectionTest.class);
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
index 778e527..e266b7c 100644
--- 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
@@ -31,7 +31,7 @@ public class AllTests
}
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.io");
+ TestSuite suite = new TestSuite("Tests for java.io");
suite.addTestSuite(BufferedReaderTest.class);
suite.addTestSuite(FilePermissionTest.class);
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
index 55e8c6f..6f0ef40 100644
--- 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
@@ -1,134 +1,592 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.ByteArrayInputStream;
import java.io.CharArrayReader;
import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PipedReader;
+import java.io.Reader;
import java.io.StringReader;
import junit.framework.TestCase;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-@TestTargetClass(BufferedReader.class)
+import tests.support.Support_StringReader;
+
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.
+ 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";
+
+ /**
+ * The spec says that BufferedReader.readLine() considers only "\r", "\n"
+ * and "\r\n" to be line separators. We must not permit additional separator
+ * characters.
+ */
+ public void test_readLine_IgnoresEbcdic85Characters() throws IOException {
+ assertLines("A\u0085B", "A\u0085B");
}
- try {
- reader.read(ch , -1, 1);
- fail("Test 2: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
+ public void test_readLine_Separators() throws IOException {
+ assertLines("A\nB\nC", "A", "B", "C");
+ assertLines("A\rB\rC", "A", "B", "C");
+ assertLines("A\r\nB\r\nC", "A", "B", "C");
+ assertLines("A\n\rB\n\rC", "A", "", "B", "", "C");
+ assertLines("A\n\nB\n\nC", "A", "", "B", "", "C");
+ assertLines("A\r\rB\r\rC", "A", "", "B", "", "C");
+ assertLines("A\n\n", "A", "");
+ assertLines("A\n\r", "A", "");
+ assertLines("A\r\r", "A", "");
+ assertLines("A\r\n", "A");
+ assertLines("A\r\n\r\n", "A", "");
}
-
- try {
- reader.read(ch , 1, -1);
- fail("Test 3: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
+
+ private void assertLines(String in, String... lines) throws IOException {
+ BufferedReader bufferedReader
+ = new BufferedReader(new Support_StringReader(in));
+ for (String line : lines) {
+ assertEquals(line, bufferedReader.readLine());
+ }
+ assertNull(bufferedReader.readLine());
}
+ /**
+ * @tests java.io.BufferedReader#BufferedReader(java.io.Reader)
+ */
+ public void test_ConstructorLjava_io_Reader() {
+ // Test for method java.io.BufferedReader(java.io.Reader)
+ assertTrue("Used in tests", true);
+ }
+
+ /**
+ * @tests java.io.BufferedReader#BufferedReader(java.io.Reader, int)
+ */
+ public void test_ConstructorLjava_io_ReaderI() {
+ // Test for method java.io.BufferedReader(java.io.Reader, int)
+ assertTrue("Used in tests", true);
+ }
+
+ /**
+ * @tests java.io.BufferedReader#close()
+ */
+ public void test_close() {
+ // Test for method void java.io.BufferedReader.close()
+ try {
+ br = new BufferedReader(new Support_StringReader(testString));
+ br.close();
+ br.read();
+ fail("Read on closed stream");
+ } catch (IOException x) {
+ return;
+ }
+ }
+
+ /**
+ * @tests java.io.BufferedReader#mark(int)
+ */
+ public void test_markI() throws IOException {
+ // Test for method void java.io.BufferedReader.mark(int)
+ char[] buf = null;
+ 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)));
+
+ 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) {
+ // Expected
+ }
+
+ 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);
+
+ 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);
+
+ in = new BufferedReader(new Support_StringReader(new String(chars)), 12);
+ in.skip(6);
+ in.mark(8);
+ in.skip(7);
+ in.reset();
+ assertTrue("Wrong chars 2", in.read() == (char) 6
+ && in.read() == (char) 7);
+
+ BufferedReader br = new BufferedReader(new StringReader("01234"), 2);
+ br.mark(3);
+ char[] carray = new char[3];
+ int result = br.read(carray);
+ assertEquals(3, result);
+ assertEquals("Assert 0:", '0', carray[0]);
+ assertEquals("Assert 1:", '1', carray[1]);
+ assertEquals("Assert 2:", '2', carray[2]);
+ assertEquals("Assert 3:", '3', br.read());
+
+ br = new BufferedReader(new StringReader("01234"), 2);
+ br.mark(3);
+ carray = new char[4];
+ result = br.read(carray);
+ assertEquals("Assert 4:", 4, result);
+ assertEquals("Assert 5:", '0', carray[0]);
+ assertEquals("Assert 6:", '1', carray[1]);
+ assertEquals("Assert 7:", '2', carray[2]);
+ assertEquals("Assert 8:", '3', carray[3]);
+ assertEquals("Assert 9:", '4', br.read());
+ assertEquals("Assert 10:", -1, br.read());
+
+ BufferedReader reader = new BufferedReader(new StringReader("01234"));
+ reader.mark(Integer.MAX_VALUE);
+ reader.read();
+ reader.close();
+ }
+
+ /**
+ * @tests java.io.BufferedReader#markSupported()
+ */
+ 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()
+ */
+ public void test_read() throws IOException {
+ // Test for method int java.io.BufferedReader.read()
+ 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);
+ }
+
+ /**
+ * @tests java.io.BufferedReader#read(char[], int, int)
+ */
+ public void test_read$CII() throws Exception{
+ char[] ca = new char[2];
+ BufferedReader toRet = new BufferedReader(new InputStreamReader(
+ new ByteArrayInputStream(new byte[0])));
+
+ /* Null buffer should throw NPE even when len == 0 */
+ try {
+ toRet.read(null, 1, 0);
+ fail("null buffer reading zero bytes should throw NPE");
+ } catch (NullPointerException e) {
+ //expected
+ }
+
+ try {
+ toRet.close();
+ } catch (IOException e) {
+ fail("unexpected 1: " + e);
+ }
+
+ try {
+ toRet.read(null, 1, 0);
+ fail("null buffer reading zero bytes on closed stream should throw IOException");
+ } catch (IOException e) {
+ //expected
+ }
+
+ /* 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
+ }
+
+ /*
+ * Closed reader should throw IOException in preference to index out of
+ * bounds
+ */
+ try {
+ // Read should throw IOException before
+ // ArrayIndexOutOfBoundException
+ toRet.read(ca, 1, 5);
+ fail("IOException should have been thrown");
+ } 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)));
+ } 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);
+ }
+
+ //regression for HARMONY-831
+ try{
+ new BufferedReader(new PipedReader(), 9).read(new char[] {}, 7, 0);
+ fail("should throw IndexOutOfBoundsException");
+ }catch(IndexOutOfBoundsException e){
+ }
+
+ // Regression for HARMONY-54
+ char[] ch = {};
+ BufferedReader reader = new BufferedReader(new CharArrayReader(ch));
try {
- reader.read(ch, 1, 3);
- fail("Test 4: IndexOutOfBoundsException expected.");
- } catch (IndexOutOfBoundsException e) {
- // Expected.
+ // Check exception thrown when the reader is open.
+ reader.read(null, 1, 0);
+ fail("Assert 0: NullPointerException expected");
+ } catch (NullPointerException e) {
+ // Expected
}
+ // Now check IOException is thrown in preference to
+ // NullPointerexception when the reader is closed.
reader.close();
try {
- reader.read(ch, 1, 1);
- fail("Test 5: IOException expected.");
+ reader.read(null, 1, 0);
+ fail("Assert 1: IOException expected");
} catch (IOException e) {
- // Expected.
+ // 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.
+ // And check that the IOException is thrown before
+ // ArrayIndexOutOfBoundException
+ reader.read(ch, 0, 42);
+ fail("Assert 2: IOException expected");
+ } catch (IOException 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();
-
+ /**
+ * @tests java.io.BufferedReader#read(char[], int, int)
+ */
+ public void test_read_$CII_Exception() throws IOException {
+ br = new BufferedReader(new Support_StringReader(testString));
+ char[] nullCharArray = null;
+ char[] charArray = testString.toCharArray();
+
+ try {
+ br.read(nullCharArray, -1, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ br.read(nullCharArray, -1, 0);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ br.read(nullCharArray, 0, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ br.read(nullCharArray, 0, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ br.read(nullCharArray, 0, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ br.read(charArray, -1, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ br.read(charArray, -1, 0);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ br.read(charArray, 0, 0);
+ br.read(charArray, 0, charArray.length);
+ br.read(charArray, charArray.length, 0);
+
+ try {
+ br.read(charArray, charArray.length + 1, 0);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ br.read(charArray, charArray.length + 1, 1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+
+ br.close();
+
+ try {
+ br.read(nullCharArray, -1, -1);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+
+ try {
+ br.read(charArray, -1, 0);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+
+ try {
+ br.read(charArray, 0, -1);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+ /**
+ * @tests java.io.BufferedReader#readLine()
+ */
+ public void test_readLine() {
+ // Test for method java.lang.String java.io.BufferedReader.readLine()
+ try {
+ br = new BufferedReader(new Support_StringReader(testString));
+ String r = br.readLine();
+ assertEquals("readLine returned incorrect string", "Test_All_Tests", r
+ );
+ } catch (java.io.IOException e) {
+ fail("Exception during readLine test");
+ }
+ }
+
+ /**
+ * @tests java.io.BufferedReader#ready()
+ */
+ public void test_ready() {
+ // Test for method boolean java.io.BufferedReader.ready()
+ try {
+ br = new BufferedReader(new Support_StringReader(testString));
+ assertTrue("ready returned false", br.ready());
+ } catch (java.io.IOException e) {
+ fail("Exception during ready test" + e.toString());
+ }
+ }
+
+ /**
+ * @tests java.io.BufferedReader#reset()
+ */
+ 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;
+
+ }
+ }
+
+ public void test_reset_IOException() throws Exception {
+ int[] expected = new int[] { '1', '2', '3', '4', '5', '6', '7', '8',
+ '9', '0', -1 };
+ br = new BufferedReader(new Support_StringReader("1234567890"), 9);
+ br.mark(9);
+ for (int i = 0; i < 11; i++) {
+ assertEquals(expected[i], br.read());
+ }
try {
- reader.mark(1);
- fail("Test 2: IOException expected.");
+ br.reset();
+ fail("should throw IOException");
} catch (IOException e) {
- // Expected.
+ // Expected
+ }
+ for (int i = 0; i < 11; i++) {
+ assertEquals(-1, br.read());
+ }
+
+ br = new BufferedReader(new Support_StringReader("1234567890"));
+ br.mark(10);
+ for (int i = 0; i < 10; i++) {
+ assertEquals(expected[i], br.read());
+ }
+ br.reset();
+ for (int i = 0; i < 11; i++) {
+ assertEquals(expected[i], br.read());
}
}
+ /**
+ * @tests java.io.BufferedReader#skip(long)
+ */
+ public void test_skipJ() {
+ // Test for method long java.io.BufferedReader.skip(long)
+ try {
+ br = new BufferedReader(new Support_StringReader(testString));
+ br.skip(500);
+ char[] buf = new char[testString.length()];
+ br.read(buf, 0, 500);
+ assertTrue("Failed to set skip properly", testString.substring(500,
+ 1000).equals(new String(buf, 0, 500)));
+ } catch (java.io.IOException e) {
+ fail("Exception during skip test");
+ }
+
+ }
+
+ /**
+ * 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 {
+ br.close();
+ } catch (Exception e) {
+ }
+ }
}
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
index a358cc5..5b5a759 100644
--- 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
@@ -1,41 +1,166 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 java.security.PermissionCollection;
import junit.framework.TestCase;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-@TestTargetClass(FilePermission.class)
+
public class FilePermissionTest extends 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");
+
+ FilePermission readInSubdir = new FilePermission("-", "read");
+
+ /**
+ * @tests java.io.FilePermission#FilePermission(java.lang.String,
+ * java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_StringLjava_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 constructor did not correspond - constructor 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()
+ */
+ public void test_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)
+ */
+ public void test_equalsLjava_lang_Object() {
+ assertTrue(
+ "Should not returned false when two instance of FilePermission is equal",
+ readAllFiles.equals(alsoReadAllFiles));
+ assertFalse(
+ "Should not 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 = "",
- method = "implies",
- args = {java.security.Permission.class}
- )
- public void test_impliesLjava_io_FilePermission() {
+ public void test_impliesLjava_security_Permission() {
+ assertFalse("Should not return true for non-subset of actions", readAllFiles
+ .implies(allInCurrent));
+ assertFalse("Should not return true for non-subset of files", allInCurrent
+ .implies(readAllFiles));
+ assertTrue("Should not return false for subset of actions", allInCurrent
+ .implies(readInCurrent));
+ assertTrue("Should not return false for subset of files", readAllFiles
+ .implies(readInCurrent));
+ assertTrue("Should not return false for subset of files and actions",
+ allInCurrent.implies(readInFile));
+ assertTrue("Should not return false for equal FilePermissions", readAllFiles
+ .implies(alsoReadAllFiles));
+ assertTrue("Should not return false for subdir self", readInSubdir.implies(readInSubdir));
+ assertTrue("Should not return false for current self", readInCurrent.implies(readInCurrent));
+ assertTrue("Should not return false for subdir", readInSubdir.implies(readInCurrent));
+
+ FilePermission fp13 = new FilePermission(File.separator, "read");
+ FilePermission fp14 = new FilePermission(File.separator + "*", "read");
+ assertFalse("/ should not imply /*", fp13.implies(fp14));
+ fp14 = new FilePermission(File.separator + "-", "read");
+ assertFalse("/ should not imply /-", fp13.implies(fp14));
+
+ FilePermission fp3 = new FilePermission("/bob/*".replace('/',
+ File.separatorChar), "read,write");
+ FilePermission fp4 = new FilePermission("/bob/".replace('/',
+ File.separatorChar), "write");
+ assertFalse("Should not return true for same dir using * and not *", fp3
+ .implies(fp4));
+ FilePermission fp5 = new FilePermission("/bob/file".replace('/',
+ File.separatorChar), "write");
+ assertTrue("Should not return 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");
+ assertFalse("Should not return true for same dir using not * and *", fp6
+ .implies(fp7));
+ assertTrue("Should not return 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("Should not return 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("Should not return false for same dir", fp10.implies(fp11));
+
+ FilePermission fp12 = new FilePermission("/*".replace('/',
+ File.separatorChar), "read,write");
+ assertFalse("Should not return true for same dir using * and dir", fp12
+ .implies(fp10));
+
// Regression for HARMONY-47
char separator = File.separatorChar;
char nonSeparator = (separator == '/') ? '\\' : '/';
@@ -46,4 +171,52 @@ public class FilePermissionTest extends TestCase {
fp1 = new FilePermission(nonSeparator + "-", "read");
assertFalse("Assert 1: non-separator worked", fp1.implies(fp2));
}
+
+ /**
+ * @tests java.io.FilePermission#newPermissionCollection()
+ */
+ public void test_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("Should not return false for subset of files", collect
+ .implies(new FilePermission("*", "write")));
+ assertTrue("Should not return false for subset of name and action", collect
+ .implies(new FilePermission(s + "tmp", "read")));
+ assertTrue("Should not return false 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()
+ */
+ public void test_hashCode() {
+ 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());
+
+ }
}
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
index 53ce506..8cae683 100644
--- 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
@@ -1,136 +1,1015 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.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 junit.framework.TestCase;
import org.apache.harmony.testframework.serialization.SerializationTest;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import tests.util.TestEnvironment;
+import tests.support.Support_Exec;
+import tests.support.Support_PlatformFile;
-@TestTargetClass(File.class)
public class FileTest extends TestCase {
+
+ private static String platformId = "JDK"
+ + System.getProperty("java.vm.version").replace('.', '-');
+
+ private static void deleteTempFolder(File dir) {
+ String files[] = dir.list();
+ if (files != null) {
+ 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();
+ }
+
+ private static String addTrailingSlash(String path) {
+ if (File.separatorChar == path.charAt(path.length() - 1)) {
+ return path;
+ }
+ return path + File.separator;
+ }
+
+ /** Location to store tests in */
+ private File tempDirectory;
- @Override protected void setUp() throws Exception {
- super.setUp();
- TestEnvironment.reset();
+ 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";
+
+ protected void setUp() throws IOException {
+ /** Setup the temporary directory */
+ tempDirectory = new File(addTrailingSlash(System.getProperty("java.io.tmpdir")) + "harmony-test-" + getClass().getSimpleName() + File.separator);
+ tempDirectory.mkdirs();
}
- @Override protected void tearDown() throws Exception {
- TestEnvironment.reset();
- super.tearDown();
+ protected void tearDown() {
+ if (tempDirectory != null) {
+ deleteTempFolder(tempDirectory);
+ tempDirectory = null;
+ }
}
/**
* @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() {
+ public void test_ConstructorLjava_io_FileLjava_lang_String0() {
+ File f = new File(tempDirectory.getPath(), "input.tst");
+ assertEquals("Created Incorrect File ", addTrailingSlash(tempDirectory.getPath()) + "input.tst", f.getPath());
+ }
+
+ public void test_ConstructorLjava_io_FileLjava_lang_String1() {
+ try {
+ new File(tempDirectory, null);
+ fail("NullPointerException Not Thrown.");
+ } catch (NullPointerException e) {
+ }
+ }
+
+ public void test_ConstructorLjava_io_FileLjava_lang_String2() throws IOException {
+ File f = new File((File)null, "input.tst");
+ assertEquals("Created Incorrect File",
+ new File("input.tst").getAbsolutePath(),
+ f.getAbsolutePath());
+ }
+
+ public void test_ConstructorLjava_io_FileLjava_lang_String3() {
+ // Regression test for HARMONY-382
+ File f = new File("/abc");
+ File d = new File((File)null, "/abc");
+ assertEquals("Test3: Created Incorrect File",
+ d.getAbsolutePath(), f.getAbsolutePath());
+ }
+
+ public void test_ConstructorLjava_io_FileLjava_lang_String4() {
// 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());
- assertFalse("Assert 1.1: path absolute ", new File("\\\\\\a\b").isAbsolute());
- assertTrue("Assert 1.1: path absolute ", new File("///a/b").isAbsolute());
-
+ if (File.separatorChar == '\\') {
+ assertTrue("Assert 1.1: path not absolute ", new File("\\\\\\a\b")
+ .isAbsolute());
+ } else {
+ assertFalse("Assert 1.1: path absolute ", new File("\\\\\\a\b")
+ .isAbsolute());
+ }
+ }
+
+ public void test_ConstructorLjava_io_FileLjava_lang_String5() {
// Test data used in a few places below
- String dirName = System.getProperty("java.io.tmpdir");
+ String dirName = tempDirectory.getPath();
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 = addTrailingSlash(dirName);
dirName += fileName;
- assertTrue("Assert 2: Created incorrect file " + f.getPath(), f
- .getPath().equals(dirName));
+ assertEquals("Assert 1: Created incorrect file ",
+ dirName, f.getPath());
// Check null argument is handled
try {
f = new File(d, null);
- fail("Assert 3: NullPointerException not thrown.");
+ fail("Assert 2: NullPointerException not thrown.");
} catch (NullPointerException e) {
// Expected.
}
-
- f = new File((File) null, fileName);
- assertEquals("Assert 4: Created incorrect file " + f.getPath(), dirName,
- f.getAbsolutePath());
-
+ }
+
+ public void test_ConstructorLjava_io_FileLjava_lang_String6() {
// 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);
+ assertEquals("Trailing slash file name is incorrect", f1, f2);
+ }
- // reset user.dir
- System.setProperty("user.dir", oldUserDir);
+ /**
+ * @tests java.io.File#File(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
+ String fileName = null;
+ try {
+ new File(fileName);
+ fail("NullPointerException Not Thrown.");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ fileName = addTrailingSlash(tempDirectory.getPath());
+ fileName += "input.tst";
+
+ File f = new File(fileName);
+ assertEquals("Created incorrect File", fileName, f.getPath());
}
-
+
/**
- * @tests java.io.File#hashCode()
+ * @tests java.io.File#File(java.lang.String, java.lang.String)
*/
- @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());
+ public void test_ConstructorLjava_lang_StringLjava_lang_String() throws IOException {
+ String dirName = null;
+ String fileName = "input.tst";
+ File f = new File(dirName, fileName);
+ assertEquals("Test 1: Created Incorrect File",
+ new File("input.tst").getAbsolutePath(),
+ f.getAbsolutePath());
- if (mfile.equals(lfile)) {
- assertTrue("Assert 0: wrong hashcode", mfile.hashCode() == lfile.hashCode());
+ dirName = tempDirectory.getPath();
+ fileName = null;
+ try {
+ f = new File(dirName, fileName);
+ fail("NullPointerException Not Thrown.");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ fileName = "input.tst";
+ f = new File(dirName, fileName);
+ assertEquals("Test 2: Created Incorrect File",
+ addTrailingSlash(tempDirectory.getPath()) + "input.tst",
+ f.getPath());
+
+ // Regression test for HARMONY-382
+ String s = null;
+ f = new File("/abc");
+ File d = new File(s, "/abc");
+ assertEquals("Test3: Created Incorrect File", d.getAbsolutePath(), f
+ .getAbsolutePath());
+ }
+
+ /**
+ * @tests java.io.File#File(java.lang.String, java.lang.String)
+ */
+ public void test_Constructor_String_String_112270() {
+ File ref1 = new File("/dir1/file1");
+
+ File file1 = new File("/", "/dir1/file1");
+ assertEquals("wrong result 1", ref1.getPath(), file1.getPath());
+ File file2 = new File("/", "//dir1/file1");
+ assertEquals("wrong result 2", ref1.getPath(), file2.getPath());
+
+ if (File.separatorChar == '\\') {
+ File file3 = new File("\\", "\\dir1\\file1");
+ assertEquals("wrong result 3", ref1.getPath(), file3.getPath());
+ File file4 = new File("\\", "\\\\dir1\\file1");
+ assertEquals("wrong result 4", ref1.getPath(), file4.getPath());
+ }
+
+ File ref2 = new File("/lib/content-types.properties");
+ File file5 = new File("/", "lib/content-types.properties");
+ assertEquals("wrong result 5", ref2.getPath(), file5.getPath());
+ }
+
+ /**
+ * @tests java.io.File#File(java.io.File, java.lang.String)
+ */
+ public void test_Constructor_File_String_112270() {
+ File ref1 = new File("/dir1/file1");
+
+ File root = new File("/");
+ File file1 = new File(root, "/dir1/file1");
+ assertEquals("wrong result 1", ref1.getPath(), file1.getPath());
+ File file2 = new File(root, "//dir1/file1");
+ assertEquals("wrong result 2", ref1.getPath(), file2.getPath());
+
+ if (File.separatorChar == '\\') {
+ File file3 = new File(root, "\\dir1\\file1");
+ assertEquals("wrong result 3", ref1.getPath(), file3.getPath());
+ File file4 = new File(root, "\\\\dir1\\file1");
+ assertEquals("wrong result 4", ref1.getPath(), file4.getPath());
+ }
+
+ File ref2 = new File("/lib/content-types.properties");
+ File file5 = new File(root, "lib/content-types.properties");
+ assertEquals("wrong result 5", ref2.getPath(), file5.getPath());
+ }
+
+ /**
+ * @tests java.io.File#File(java.net.URI)
+ */
+ public void test_ConstructorLjava_net_URI() throws URISyntaxException {
+ URI uri = null;
+ try {
+ new File(uri);
+ fail("NullPointerException Not Thrown.");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ // 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++) {
+ uri = new URI(uris[i]);
+ try {
+ new File(uri);
+ fail("Expected IllegalArgumentException for new File(" + uri
+ + ")");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ // a valid File URI
+ File f = new File(new URI("file:///pa%20th/another\u20ac/pa%25th"));
+ assertTrue("Created incorrect File " + f.getPath(), f.getPath().equals(
+ File.separator + "pa th" + File.separator + "another\u20ac" + File.separator + "pa%th"));
+ }
+
+ /**
+ * @tests java.io.File#canRead()
+ */
+ public void test_canRead() throws IOException {
+ // canRead only returns if the file exists so cannot be fully tested.
+ File f = new File(tempDirectory, platformId + "canRead.tst");
+ try {
+ FileOutputStream fos = new FileOutputStream(f);
+ fos.close();
+ assertTrue("canRead returned false", f.canRead());
+ } finally {
+ f.delete();
+ }
+ }
+
+ /**
+ * @tests java.io.File#canWrite()
+ */
+ public void test_canWrite() throws IOException {
+ // canWrite only returns if the file exists so cannot be fully tested.
+ File f = new File(tempDirectory, platformId + "canWrite.tst");
+ try {
+ FileOutputStream fos = new FileOutputStream(f);
+ fos.close();
+ assertTrue("canWrite returned false", f.canWrite());
+ } finally {
+ f.delete();
+ }
+ }
+
+ /**
+ * @tests java.io.File#compareTo(java.io.File)
+ */
+ 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 value > 0", f1
+ .compareTo(f3) > 0);
+ }
+
+ /**
+ * @tests java.io.File#createNewFile()
+ */
+ 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()
+ */
+ public void test_createNewFile() throws IOException {
+ String base = tempDirectory.getPath();
+ 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("IOException not thrown");
+ } 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("File Should Not Exist", f1.isFile());
+ f1.createNewFile();
+ assertTrue("File Should Exist.", f1.isFile());
+ assertTrue("File Should Exist.", f2.isFile());
+ String dirName = f1.getParent();
+ if (!dirName.endsWith(File.separator)) {
+ dirName += File.separator;
+ }
+ assertEquals("File Saved To Wrong Directory.",
+ dir.getPath() + File.separator, dirName);
+ assertEquals("File Saved With Incorrect Name.", "tempfile.tst",
+ f1.getName());
+
+ // Test for creating a file that already exists.
+ assertFalse("File Already Exists, createNewFile Should Return False.",
+ f2.createNewFile());
+
+ // Test create an illegal file
+ String sep = File.separator;
+ f1 = new File(sep + "..");
+ try {
+ f1.createNewFile();
+ fail("should throw IOE");
+ } catch (IOException e) {
+ // expected;
+ }
+ f1 = new File(sep + "a" + sep + ".." + sep + ".." + sep);
+ try {
+ f1.createNewFile();
+ fail("should throw IOE");
+ } catch (IOException e) {
+ // expected;
+ }
+
+ // This test is invalid. createNewFile should return false
+ // not IOE when the file exists (in this case it exists and is
+ // a directory). TODO: We should probably replace this test
+ // with some that cover this behaviour. It might even be
+ // different on unix and windows since it directly reflects
+ // the open syscall behaviour.
+ //
+ // // Test create an exist path
+ // f1 = new File(base);
+ // try {
+ // assertFalse(f1.createNewFile());
+ // fail("should throw IOE");
+ // } catch (IOException e) {
+ // // expected;
+ // }
+ }
+
+ /**
+ * @tests java.io.File#createTempFile(java.lang.String, java.lang.String)
+ */
+ public void test_createTempFileLjava_lang_StringLjava_lang_String()
+ throws IOException {
+ // Error protection against using a suffix without a "."?
+ File f1 = null;
+ File f2 = null;
+ try {
+ f1 = File.createTempFile("harmony-test-FileTest_tempFile_abc", ".tmp");
+ f2 = File.createTempFile("harmony-test-FileTest_tempFile_tf", null);
+
+ String fileLocation = addTrailingSlash(f1.getParent());
+
+ String tempDir = addTrailingSlash(System.getProperty("java.io.tmpdir"));
+
+ assertEquals(
+ "File did not save to the default temporary-file location.",
+ tempDir, fileLocation);
+
+ // 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("harmony-test-FileTest_tempFile_abc"));
+ fileName = f2.getName();
+ assertTrue("Test 2: File Created With Incorrect Prefix.", fileName
+ .startsWith("harmony-test-FileTest_tempFile_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) {
+ // Expected
+ }
+ try {
+ File f3 = File.createTempFile("a", ".tst");
+ f3.delete();
+ fail("IllegalArgumentException Not Thrown.");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ File f3 = File.createTempFile("", ".tst");
+ f3.delete();
+ fail("IllegalArgumentException Not Thrown.");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ } 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)
+ */
+ public void test_createTempFileLjava_lang_StringLjava_lang_StringLjava_io_File()
+ throws IOException {
+ 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("harmony-test-FileTest_tempFile2_tf", null, null);
+ File dir = new File(base);
+ f2 = File.createTempFile("harmony-test-FileTest_tempFile2_tf", ".tmp", dir);
+ File currentFile;
+ String fileLocation;
+ String fileName;
+ for (int i = 0; i < 2; i++) {
+ currentFile = i == 0 ? f1 : f2;
+ fileLocation = addTrailingSlash(currentFile.getParent());
+ base = addTrailingSlash(base);
+ assertEquals(
+ "File not created in the default temporary-file location.",
+ base, fileLocation);
+ fileName = currentFile.getName();
+ assertTrue("File created with incorrect suffix.", fileName
+ .endsWith(".tmp"));
+ assertTrue("File created with incorrect prefix.", fileName
+ .startsWith("harmony-test-FileTest_tempFile2_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("harmony-test-FileTest_tempFile2_tf", null, dir);
+ f3.delete();
+ fail("IOException not thrown");
+ } catch (IOException e) {
+ // Expected
+ }
+ 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) {
+ // Expected
+ }
+ try {
+ File f4 = File.createTempFile("a", null, null);
+ f4.delete();
+ fail("IllegalArgumentException not thrown.");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ File f4 = File.createTempFile("", null, null);
+ f4.delete();
+ fail("IllegalArgumentException not thrown.");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ } finally {
+ if (f1 != null) {
+ f1.delete();
+ }
+ if (f2 != null) {
+ f1.delete();
+ }
+ }
+ }
+
+ /**
+ * @tests java.io.File#delete()
+ */
+ public void test_delete() throws IOException {
+ File dir = new File(tempDirectory, platformId
+ + "filechk");
+ dir.mkdir();
+ assertTrue("Directory does not exist", dir.exists());
+ assertTrue("Directory is not directory", 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());
+ }
+
+ // GCH
+ // TODO : This test passes on Windows but fails on Linux with a
+ // java.lang.NoClassDefFoundError. Temporarily removing from the test
+ // suite while I investigate the cause.
+ // /**
+ // * @tests java.io.File#deleteOnExit()
+ // */
+ // public void test_deleteOnExit() {
+ // File f1 = new File(System.getProperty("java.io.tmpdir"), platformId
+ // + "deleteOnExit.tst");
+ // try {
+ // FileOutputStream fos = new FileOutputStream(f1);
+ // fos.close();
+ // } catch (IOException e) {
+ // fail("Unexpected IOException During Test : " + e.getMessage());
+ // }
+ // assertTrue("File Should Exist.", f1.exists());
+ //
+ // try {
+ // Support_Exec.execJava(new String[] {
+ // "tests.support.Support_DeleteOnExitTest", f1.getPath() },
+ // null, true);
+ // } catch (IOException e) {
+ // fail("Unexpected IOException During Test + " + e.getMessage());
+ // } catch (InterruptedException e) {
+ // fail("Unexpected InterruptedException During Test: " + e);
+ // }
+ //
+ // boolean gone = !f1.exists();
+ // f1.delete();
+ // assertTrue("File Should Already Be Deleted.", gone);
+ // }
+
+ /**
+ * @tests java.io.File#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() throws IOException {
+ 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));
+ }
+
+ f1 = new File(tempDirectory, "casetest.tmp");
+ f2 = new File(tempDirectory, "CaseTest.tmp");
+ new FileOutputStream(f1).close(); // create the file
+ if (f1.equals(f2)) {
+ try {
+ FileInputStream fis = new FileInputStream(f2);
+ fis.close();
+ } catch (IOException e) {
+ fail("File system is case sensitive");
+ }
} else {
- assertFalse("Assert 1: wrong hashcode", mfile.hashCode() == lfile.hashCode());
+ boolean exception = false;
+ try {
+ FileInputStream fis = new FileInputStream(f2);
+ fis.close();
+ } catch (IOException e) {
+ exception = true;
+ }
+ assertTrue("File system is case insensitive", exception);
}
+ f1.delete();
+ }
+
+ /**
+ * @tests java.io.File#exists()
+ */
+ public void test_exists() throws IOException {
+ File f = new File(tempDirectory, 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();
+ }
+
+ /**
+ * @tests java.io.File#getAbsoluteFile()
+ */
+ public void test_getAbsoluteFile() {
+ String base = addTrailingSlash(tempDirectory.getPath());
+ 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" + File.separator + File.separator + "temp.tst");
+ f2 = f.getAbsoluteFile();
+ assertEquals("Test 2: Incorrect File Returned.", 0, f2.compareTo(f
+ .getAbsoluteFile()));
+ f = new File(base + File.separator + ".." + File.separator + "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()
+ */
+ public void test_getAbsolutePath() {
+ String base = addTrailingSlash(tempDirectory.getPath());
+ File f = new File(base, "temp.tst");
+ assertEquals("Test 1: Incorrect Path Returned.",
+ base + "temp.tst", f.getAbsolutePath());
+
+ f = new File(base + "Temp" + File.separator + File.separator + File.separator + "Testing" + File.separator
+ + "temp.tst");
+ assertEquals("Test 2: Incorrect Path Returned.",
+ base + "Temp" + File.separator + "Testing" + File.separator + "temp.tst",
+ f.getAbsolutePath());
+
+ f = new File(base + "a" + File.separator + File.separator + ".." + File.separator + "temp.tst");
+ assertEquals("Test 3: Incorrect Path Returned.",
+ base + "a" + File.separator + ".." + File.separator + "temp.tst",
+ f.getAbsolutePath());
+ f.delete();
+ }
+
+ /**
+ * @tests java.io.File#getCanonicalFile()
+ */
+ public void test_getCanonicalFile() throws IOException {
+ String base = addTrailingSlash(tempDirectory.getPath());
+ 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" + File.separator + File.separator + "temp.tst");
+ f2 = f.getCanonicalFile();
+ assertEquals("Test 2: Incorrect File Returned.", 0, f2
+ .getCanonicalFile().compareTo(f.getCanonicalFile()));
+ f = new File(base + "Temp" + File.separator + File.separator + ".." + File.separator + "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 == '\\';
+ 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 + File.separator + "longdi~1" + File.separator
+ + "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();
+ }
+ }
+ }
+
+ /**
+ * @tests java.io.File#getCanonicalPath()
+ */
+ public void test_getCanonicalPath() throws IOException {
+ // Should work for Unix/Windows.
+ String dots = "..";
+ String base = tempDirectory.getCanonicalPath();
+ base = addTrailingSlash(base);
+ File f = new File(base, "temp.tst");
+ assertEquals("Test 1: Incorrect Path Returned.", base + "temp.tst", f
+ .getCanonicalPath());
+ f = new File(base + "Temp" + File.separator + dots + File.separator + "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 + File.separator + dots + File.separator + dirNumber
+ + File.separator + "temp.tst");
+ assertEquals("Test 3: Incorrect Path Returned.", base + dirNumber
+ + File.separator + "temp.tst", f.getCanonicalPath());
+ f = new File(base + dirNumber + File.separator + "Temp" + File.separator + dots + File.separator
+ + "Test" + File.separator + "temp.tst");
+ assertEquals("Test 4: Incorrect Path Returned.", base + dirNumber
+ + File.separator + "Test" + File.separator + "temp.tst", f.getCanonicalPath());
+
+ f = new File(base + "1234.567");
+ assertEquals("Test 5: Incorrect Path Returned.", base + "1234.567", f
+ .getCanonicalPath());
+
+ // Test for long file names on Windows
+ boolean onWindows = (File.separatorChar == '\\');
+ if (onWindows) {
+ File testdir = new File(base, "long-" + platformId);
+ testdir.mkdir();
+ File f1 = new File(testdir, "longfilename" + platformId + ".tst");
+ FileOutputStream fos = new FileOutputStream(f1);
+ File f2 = null, f3 = null, dir2 = null;
+ try {
+ fos.close();
+ String dirName1 = f1.getCanonicalPath();
+ File f4 = new File(testdir, "longfi~1.tst");
+ /*
+ * If the "short file name" doesn't exist, then assume that the
+ * 8.3 file name compatibility is disabled.
+ */
+ if (f4.exists()) {
+ String dirName2 = f4.getCanonicalPath();
+ assertEquals("Test 6: Incorrect Path Returned.", dirName1,
+ dirName2);
+ dir2 = new File(testdir, "longdirectory" + platformId);
+ if (!dir2.exists()) {
+ assertTrue("Could not create dir: " + dir2, dir2
+ .mkdir());
+ }
+ f2 = new File(testdir.getPath() + File.separator + "longdirectory"
+ + platformId + File.separator + "Test" + File.separator + dots
+ + File.separator + "longfilename.tst");
+ FileOutputStream fos2 = new FileOutputStream(f2);
+ fos2.close();
+ dirName1 = f2.getCanonicalPath();
+ f3 = new File(testdir.getPath() + File.separator + "longdi~1"
+ + File.separator + "Test" + File.separator + dots + File.separator
+ + "longfi~1.tst");
+ dirName2 = f3.getCanonicalPath();
+ assertEquals("Test 7: Incorrect Path Returned.", dirName1,
+ dirName2);
+ }
+ } finally {
+ f1.delete();
+ if (f2 != null) {
+ f2.delete();
+ }
+ if (dir2 != null) {
+ dir2.delete();
+ }
+ testdir.delete();
+ }
+ }
+ }
+
+ /**
+ * @tests java.io.File#getName()
+ */
+ public void test_getName() {
+ File f = new File("name.tst");
+ assertEquals("Test 1: Returned incorrect name", "name.tst", f.getName());
+
+ f = new File("");
+ assertEquals("Test 2: Returned incorrect name", "", f.getName());
+
+ f.delete();
+ }
+
+ /**
+ * @tests java.io.File#getParent()
+ */
+ public void test_getParent() {
+ File f = new File("p.tst");
+ assertNull("Incorrect path returned", f.getParent());
+ f = new File(System.getProperty("user.home"), "p.tst");
+ assertEquals("Incorrect path returned",
+ System.getProperty("user.home"), f.getParent());
+ f.delete();
+
+ File f1 = new File("/directory");
+ assertEquals("Wrong parent test 1", File.separator, f1.getParent());
+ f1 = new File("/directory/file");
+ assertEquals("Wrong parent test 2",
+ File.separator + "directory", f1.getParent());
+ 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");
+ assertEquals("Wrong parent test 1a", "d:" + File.separator, f1.getParent());
+ f1 = new File("d:/directory/file");
+ assertEquals("Wrong parent test 2a",
+ "d:" + File.separator + "directory", f1.getParent());
+ 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()
+ */
+ public void test_getParentFile() {
+ File f = new File("tempfile.tst");
+ assertNull("Incorrect path returned", f.getParentFile());
+ f = new File(tempDirectory, "tempfile1.tmp");
+ File f2 = new File(tempDirectory, "tempfile2.tmp");
+ File f3 = new File(tempDirectory, "/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 = "",
- method = "getPath",
- args = {}
- )
public void test_getPath() {
+ String base = System.getProperty("user.home");
+ String fname;
+ File f1;
+ if (!base.regionMatches((base.length() - 1), File.separator, 0, 1)) {
+ base += File.separator;
+ }
+ 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" + File.separator + File.separator + ".." + File.separator
+ + "filechk.tst");
+ assertEquals("getPath returned incorrect path(f1)",
+ fname, f1.getPath());
+ assertEquals("getPath returned incorrect path(f2)",
+ "filechk.tst", f2.getPath());
+ assertEquals("getPath returned incorrect path(f3)","c:", f3.getPath());
+ assertEquals("getPath returned incorrect path(f4)",
+ base + "a" + File.separator + ".." + File.separator + "filechk.tst",
+ f4.getPath());
+ f1.delete();
+ f2.delete();
+ f3.delete();
+ f4.delete();
+
// Regression for HARMONY-444
File file;
String separator = File.separator;
@@ -140,46 +1019,1234 @@ public class FileTest extends TestCase {
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, "");
+ f1 = new File(f1ParentName, "");
assertEquals(f1ParentName, f1.getPath());
-
+
String f2ParentName = "0";
- File f2 = new File(f2ParentName, "");
+ 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, "");
+ File parent = tempDirectory;
+ f3 = new File(parent, "");
assertEquals(parent.getPath(), f3.getPath());
+
+ // Regression for HARMONY-3869
+ File file1 = new File("", "");
+ assertEquals(File.separator, file1.getPath());
+
+ File file2 = new File(new File(""), "");
+ assertEquals(File.separator, file2.getPath());
+ }
+
+ /**
+ * @tests java.io.File#hashCode()
+ */
+ 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#isAbsolute()
+ */
+ public void test_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()));
+
+ assertTrue(new File("C:/").isAbsolute());
+ assertTrue(new File("f:/").isAbsolute());
+ assertTrue(new File("f:\\").isAbsolute());
+ assertFalse(new File("f:").isAbsolute());
+ assertFalse(new File("K:").isAbsolute());
+ assertTrue(new File("\\\\").isAbsolute());
+ assertTrue(new File("\\\\\\").isAbsolute());
+ assertTrue(new File("\\\\hello").isAbsolute());
+ assertFalse(new File("\\").isAbsolute());
+ assertFalse(new File("/").isAbsolute());
+ } else {
+ File f = new File("/test");
+ File f1 = new File("\\test");
+ assertTrue("Absolute returned false", f.isAbsolute());
+ assertFalse("Absolute returned true", f1.isAbsolute());
+ assertTrue(new File("//test").isAbsolute());
+ assertFalse(new File("test").isAbsolute());
+ assertFalse(new File("c:/").isAbsolute());
+ assertFalse(new File("c:\\").isAbsolute());
+ assertFalse(new File("c:").isAbsolute());
+ assertFalse(new File("\\").isAbsolute());
+ assertFalse(new File("\\\\").isAbsolute());
+ }
+ assertTrue("Non-Absolute returned true", !new File("../test")
+ .isAbsolute());
+ }
+
+ /**
+ * @tests java.io.File#isDirectory()
+ */
+ public void test_isDirectory() {
+ String base = addTrailingSlash(tempDirectory.getPath());
+ 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()
+ */
+ public void test_isFile() throws IOException {
+ String base = tempDirectory.getPath();
+ File f = new File(base);
+ assertFalse("Directory Returned True As Being A File.", f.isFile());
-
+ base = addTrailingSlash(base);
+ 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();
}
-
+
+ /**
+ * @tests java.io.File#isHidden()
+ */
+ public void test_isHidden() throws IOException, InterruptedException {
+ boolean onUnix = File.separatorChar == '/';
+ File f = File.createTempFile("harmony-test-FileTest_isHidden_", ".tmp");
+ // On Unix hidden files are marked with a "." at the beginning
+ // of the file name.
+ if (onUnix) {
+ File f2 = new File(".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();
+ }
+
+ /**
+ * @tests java.io.File#lastModified()
+ */
+ public void test_lastModified() throws IOException {
+ 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();
+ assertEquals("LastModified Time Incorrect",
+ 315550800000L, lastModifiedTime);
+ f.delete();
+
+ // Regression for HARMONY-2146
+ f = new File("/../");
+ assertTrue(f.lastModified() > 0);
+ }
+
+ /**
+ * @tests java.io.File#length()
+ */
+ public void test_length() throws IOException {
+ File f = new File(tempDirectory, platformId
+ + "input.tst");
+ assertEquals("File Length Should Have Returned 0.", 0, f.length());
+ FileOutputStream fos = new FileOutputStream(f);
+ fos.write(fileString.getBytes());
+ fos.close();
+ assertEquals("Incorrect file length returned",
+ fileString.length(), f.length());
+ f.delete();
+
+ // regression test for HARMONY-1497
+ f = File.createTempFile("test", "tmp");
+ f.deleteOnExit();
+ RandomAccessFile raf = new RandomAccessFile(f, "rwd");
+ raf.write(0x41);
+ assertEquals(1, f.length());
+ }
+
+ /**
+ * @tests java.io.File#list()
+ */
+ public void test_list() throws IOException {
+ String base = tempDirectory.getPath();
+ // 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());
+ } finally {
+ file.delete();
+ }
+
+ for (int i = 0; i < files.length; i++) {
+ File f = new File(dir, files[i]);
+ FileOutputStream fos = new FileOutputStream(f);
+ fos.close();
+ }
+
+ 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()
+ */
+ public void test_listFiles() throws IOException, InterruptedException {
+ String base = tempDirectory.getPath();
+ // 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 call 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());
+ } 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();
+ }
+ }
+
+ /**
+ * @tests java.io.File#listFiles(java.io.FileFilter)
+ */
+ public void test_listFilesLjava_io_FileFilter() throws IOException {
+ 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) {
+ return f.isDirectory();
+ }
+ };
+
+ 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));
+ } finally {
+ file.delete();
+ }
+
+ for (int i = 0; i < files.length; i++) {
+ File f = new File(baseDir, files[i]);
+ FileOutputStream fos = new FileOutputStream(f);
+ fos.close();
+ }
+ dir1 = new File(baseDir, "Temp1");
+ dir1.mkdir();
+
+ // Creating a filter that catches files.
+ FileFilter fileFilter = new FileFilter() {
+ public boolean accept(File f) {
+ return f.isFile();
+ }
+ };
+
+ // 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);
+ assertEquals("Incorrect Number Of Files Returned.",
+ files.length, 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);
+
+ 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)
+ */
+ public void test_listFilesLjava_io_FilenameFilter() throws IOException {
+ 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) {
+ return fileName.endsWith(".tst");
+ }
+ };
+
+ 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));
+ } finally {
+ file.delete();
+ }
+
+ for (int i = 0; i < files.length; i++) {
+ File f = new File(dir, files[i]);
+ FileOutputStream fos = new FileOutputStream(f);
+ fos.close();
+ }
+
+ // 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)
+ */
+ public void test_listLjava_io_FilenameFilter() throws IOException {
+ String base = tempDirectory.getPath();
+ // 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);
+
+ for (int i = 0; i < files.length; i++) {
+ File f = new File(dir, files[i]);
+ FileOutputStream fos = new FileOutputStream(f);
+ fos.close();
+ }
+
+ flist = dir.list(filter);
+
+ assertEquals("Incorrect list returned", flist.length,
+ files.length - 1);
+
+ // 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()
+ */
+ public void test_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(File.separator));
+ } else if (onWindows) {
+ // Need better test for Windows
+ assertTrue("Incorrect Number Of Root Directories.",
+ roots.length > 0);
+ }
+ }
+
+ /**
+ * @tests java.io.File#mkdir()
+ */
+ public void test_mkdir() throws IOException {
+ String base = tempDirectory.getPath();
+ // 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());
+ assertTrue("mkdir worked but exists check failed", dir.exists());
+ dir.deleteOnExit();
+
+ String longDirName = "abcdefghijklmnopqrstuvwx";// 24 chars
+ String newbase = new String(dir + File.separator);
+ 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());
+ assertTrue("mkdir worked but exists check failed", 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());
+ assertTrue("mkdir " + dir.getCanonicalPath().length()
+ + " worked but exists check failed", dir.exists());
+ dir.deleteOnExit();
+ }
+ dir = new File(sb2.toString());
+ // 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());
+ assertTrue("mkdir " + dir.getCanonicalPath().length()
+ + " worked but exists check failed", dir.exists());
+ dir.deleteOnExit();
+ }
+
+ // Regression test for HARMONY-3656
+ String[] ss = { "dir\u3400", "abc", "abc@123", "!@#$%^&",
+ "~\u4E00!\u4E8C@\u4E09$", "\u56DB\u4E94\u516D",
+ "\u4E03\u516B\u4E5D" };
+ for (int i = 0; i < ss.length; i++) {
+ dir = new File(newbase, ss[i]);
+ assertTrue("mkdir " + dir.getCanonicalPath() + " failed",
+ dir.mkdir());
+ assertTrue("mkdir " + dir.getCanonicalPath()
+ + " worked but exists check failed",
+ dir.exists());
+ dir.deleteOnExit();
+ }
+ }
+
+ /**
+ * @tests java.io.File#mkdir()
+ *
+ * HARMONY-6041
+ */
+ public void test_mkdir_special_unicode() throws IOException {
+ File specialDir = new File(this.tempDirectory,"\u5C73");
+ int i = 0;
+ while (specialDir.exists()) {
+ specialDir = new File("\u5C73" + i);
+ ++i;
+ }
+ assertFalse(specialDir.exists());
+ assertTrue(specialDir.mkdir());
+ assertTrue(specialDir.exists());
+ }
+
+ /**
+ * @tests java.io.File#mkdirs()
+ */
+ public void test_mkdirs() {
+ String userHome = addTrailingSlash(tempDirectory.getPath());
+ File f = new File(userHome + "mdtest" + platformId + File.separator + "mdtest2",
+ "p.tst");
+ File g = new File(userHome + "mdtest" + platformId + File.separator + "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)
+ */
+ public void test_renameToLjava_io_File() throws IOException {
+ String base = tempDirectory.getPath();
+ 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
+
+ assertTrue("Test 1: File Rename Failed", f.renameTo(rfile));
+ assertTrue("Test 2: File Rename Failed.", rfile.exists());
+ assertEquals("Test 3: Size Of File Changed.",
+ lengthOfFile, rfile.length());
+
+ fos = new FileOutputStream(rfile);
+ fos.close();
+
+ f2.delete(); // in case it already exists
+ assertTrue("Test 4: File Rename Failed", rfile.renameTo(f2));
+ assertTrue("Test 5: File Rename Failed.", f2.exists());
+ } finally {
+ f.delete();
+ rfile.delete();
+ f2.delete();
+ dir.delete();
+ }
+ }
+
+ /**
+ * @tests java.io.File#setLastModified(long)
+ */
+ public void test_setLastModifiedJ() throws IOException {
+ File f1 = null;
+ try {
+ f1 = new File(Support_PlatformFile.getNewPlatformFile(
+ "harmony-test-FileTest_setLastModified", ".tmp"));
+ f1.createNewFile();
+ long orgTime = f1.lastModified();
+ // Subtracting 100 000 milliseconds from the orgTime of File f1
+ f1.setLastModified(orgTime - 100000);
+ long lastModified = f1.lastModified();
+ assertEquals("Test 1: LastModifed time incorrect",
+ orgTime - 100000, lastModified);
+ // Subtracting 10 000 000 milliseconds from the orgTime of File f1
+ f1.setLastModified(orgTime - 10000000);
+ lastModified = f1.lastModified();
+ assertEquals("Test 2: LastModifed time incorrect",
+ orgTime - 10000000, lastModified);
+ // Adding 100 000 milliseconds to the orgTime of File f1
+ f1.setLastModified(orgTime + 100000);
+ lastModified = f1.lastModified();
+ assertEquals("Test 3: LastModifed time incorrect",
+ orgTime + 100000, lastModified);
+ // Adding 10 000 000 milliseconds from the orgTime of File f1
+ f1.setLastModified(orgTime + 10000000);
+ lastModified = f1.lastModified();
+ assertEquals("Test 4: LastModifed time incorrect",
+ orgTime + 10000000, lastModified);
+ // Trying to set time to an exact number
+ f1.setLastModified(315550800000L);
+ lastModified = f1.lastModified();
+ assertEquals("Test 5: LastModified time incorrect",
+ 315550800000L, lastModified);
+ 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
+ if (result) {
+ assertEquals("Test 6: LastModified time incorrect",
+ 4354837199000L, next);
+ }
+ }
+ // Trying to set time to a negative number
+ try {
+ f1.setLastModified(-25);
+ fail("IllegalArgumentException Not Thrown.");
+ } catch (IllegalArgumentException e) {
+ }
+ } finally {
+ if (f1 != null) {
+ f1.delete();
+ }
+ }
+ }
+
+ /**
+ * @tests java.io.File#setReadOnly()
+ */
+ public void test_setReadOnly() throws IOException, InterruptedException {
+ File f1 = null;
+ File f2 = null;
+ try {
+ f1 = File.createTempFile("harmony-test-FileTest_setReadOnly", ".tmp");
+ f2 = File.createTempFile("harmony-test-FileTest_setReadOnly", ".tmp");
+ // Assert is flawed because canWrite does not work.
+ // assertTrue("File f1 Is Set To ReadOnly." , f1.canWrite());
+ f1.setReadOnly();
+ // Assert is flawed because canWrite does not work.
+ // assertTrue("File f1 Is Not Set To ReadOnly." , !f1.canWrite());
+ try {
+ // Attempt to write to a file that is setReadOnly.
+ new FileOutputStream(f1);
+ fail("IOException not thrown.");
+ } catch (IOException e) {
+ // Expected
+ }
+ Runtime r = Runtime.getRuntime();
+ Process p;
+ boolean onUnix = File.separatorChar == '/';
+ if (onUnix) {
+ p = r.exec("chmod +w " + f1.getAbsolutePath());
+ } else {
+ p = r.exec("attrib -r \"" + f1.getAbsolutePath() + "\"");
+ }
+ p.waitFor();
+ // Assert is flawed because canWrite does not work.
+ // assertTrue("File f1 Is Set To ReadOnly." , f1.canWrite());
+ FileOutputStream fos = new FileOutputStream(f1);
+ fos.write(fileString.getBytes());
+ fos.close();
+ assertTrue("File Was Not Able To Be Written To.",
+ f1.length() == fileString.length());
+ assertTrue("File f1 Did Not Delete", f1.delete());
+
+ // Assert is flawed because canWrite does not work.
+ // assertTrue("File f2 Is Set To ReadOnly." , f2.canWrite());
+ 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("IOException not thrown.");
+ } catch (IOException e) {
+ // Expected
+ }
+ r = Runtime.getRuntime();
+ if (onUnix) {
+ p = r.exec("chmod +w " + f2.getAbsolutePath());
+ } else {
+ p = r.exec("attrib -r \"" + f2.getAbsolutePath() + "\"");
+ }
+ p.waitFor();
+ assertTrue("File f2 Is Set To ReadOnly.", f2.canWrite());
+ fos = new FileOutputStream(f2);
+ fos.write(fileString.getBytes());
+ fos.close();
+ f2.setReadOnly();
+ assertTrue("File f2 Did Not Delete", f2.delete());
+ // Similarly, trying to delete a read-only directory should succeed
+ f2 = new File(tempDirectory, "deltestdir");
+ f2.mkdir();
+ f2.setReadOnly();
+ assertTrue("Directory f2 Did Not Delete", f2.delete());
+ assertTrue("Directory f2 Did Not Delete", !f2.exists());
+ } finally {
+ if (f1 != null) {
+ f1.delete();
+ }
+ if (f2 != null) {
+ f2.delete();
+ }
+ }
+ }
+
+ /**
+ * @tests java.io.File#toString()
+ */
+ public void test_toString() {
+ String fileName = System.getProperty("user.home") + File.separator + "input.tst";
+ File f = new File(fileName);
+ assertEquals("Incorrect string returned", fileName, f.toString());
+
+ if (File.separatorChar == '\\') {
+ String result = new File("c:\\").toString();
+ assertEquals("Removed backslash", "c:\\", result);
+ }
+ }
+
+ /**
+ * @tests java.io.File#toURI()
+ */
+ public void test_toURI() throws URISyntaxException {
+ // Need a directory that exists
+ File dir = tempDirectory;
+
+ // 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();
+ assertEquals("Test 1A: Incorrect URI Returned.", dir.getAbsoluteFile(), new File(uri));
+ assertEquals("Test 1B: Incorrect URI Returned.",
+ new URI("file", null, newURIPath, null, null), uri);
+
+ // 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();
+ assertEquals("Test 2A: Incorrect URI Returned.",
+ f.getAbsoluteFile(), new File(uri));
+ assertEquals("Test 2B: Incorrect URI Returned.",
+ new URI("file", null, newURIPath, null, null), uri);
+
+ // 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("/"));
+ }
+
+ /**
+ * @tests java.io.File#toURL()
+ */
+ public void test_toURL() throws MalformedURLException {
+ // Need a directory that exists
+ File dir = tempDirectory;
+
+ // 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.",
+ dir.toURL().toString(), newDirURL);
+
+ // 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.",
+ f.toURL().toString(), newURL);
+
+ // Regression test for HARMONY-3207
+ dir = new File(""); // current directory
+ newDirURL = dir.toURL().toString();
+ assertTrue("Test current dir: URL does not end with slash.", newDirURL
+ .endsWith("/"));
+ }
+
+ /**
+ * @tests java.io.File#toURI()
+ */
+ public void test_toURI2() throws URISyntaxException {
+ File f = new File(tempDirectory, "a/b/c/../d/e/./f");
+
+ String path = f.getAbsolutePath();
+ path = path.replace(File.separatorChar, '/');
+ if (!path.startsWith("/")) {
+ path = "/" + path;
+ }
+
+ URI uri1 = new URI("file", null, path, null);
+ URI uri2 = f.toURI();
+ assertEquals("uris not equal", uri1, uri2);
+ }
+
+ /**
+ * @tests java.io.File#toURL()
+ */
+ public void test_toURL2() throws MalformedURLException {
+ File f = new File(tempDirectory, "a/b/c/../d/e/./f");
+
+ String path = f.getAbsolutePath();
+ path = path.replace(File.separatorChar, '/');
+ if (!path.startsWith("/")) {
+ path = "/" + path;
+ }
+
+ URL url1 = new URL("file", "", path);
+ URL url2 = f.toURL();
+ assertEquals("urls not equal", url1, url2);
+ }
+
+ /**
+ * @tests java.io.File#deleteOnExit()
+ */
+ /* BEGIN android-removed: we don't have Support_Exec.execJava.
+ public void test_deleteOnExit() throws IOException, InterruptedException {
+ File dir = new File("dir4filetest");
+ dir.mkdir();
+ assertTrue(dir.exists());
+ File subDir = new File("dir4filetest/subdir");
+ subDir.mkdir();
+ assertTrue(subDir.exists());
+
+ Support_Exec.execJava(new String[] {
+ "tests.support.Support_DeleteOnExitTest",
+ dir.getAbsolutePath(), subDir.getAbsolutePath() },
+ new String[] {}, false);
+ assertFalse(dir.exists());
+ assertFalse(subDir.exists());
+ }
+ */
+
+ /**
+ * @tests serilization
+ */
+ 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());
+ }
+
+ // Regression test for HARMONY-4493
+ public void test_list_withUnicodeFileName() throws Exception {
+ File rootDir = new File("P");
+ if (!rootDir.exists()) {
+ rootDir.mkdir();
+ rootDir.deleteOnExit();
+ }
+
+ String dirName = new String("src\u3400");
+ File dir = new File(rootDir, dirName);
+ if (!dir.exists()) {
+ dir.mkdir();
+ dir.deleteOnExit();
+ }
+ boolean exist = false;
+ String[] fileNames = rootDir.list();
+ for (String fileName : fileNames) {
+ if (dirName.equals(fileName)) {
+ exist = true;
+ break;
+ }
+ }
+ assertTrue(exist);
+ }
+
/**
* @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);
@@ -188,15 +2255,8 @@ public class FileTest extends TestCase {
/**
* @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
index 08c8627..642c8dd 100644
--- 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
@@ -1,82 +1,537 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.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 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");
+
+ 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;
+ }
+
+ @Override
+ public int available() {
+ return count;
+ }
+
+ @Override
+ public int read() {
+ if (count == 0) {
+ return -1;
+ }
+ count--;
+ return bytes[bytes.length - count];
+ }
+
+ @Override
+ 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 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";
+
+ private InputStream fis;
+
+ private InputStream in;
+
+ private InputStreamReader is;
+
+ private InputStreamReader reader;
+
+ private final String source = "This is a test message with Unicode character. \u4e2d\u56fd is China's name in Chinese";
+
+ /*
+ * @see TestCase#setUp()
+ */
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ 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);
+ }
+
+ /*
+ * @see TestCase#tearDown()
+ */
+ @Override
+ protected void tearDown() throws Exception {
+ try {
+ in.close();
+ is.close();
+ fis.close();
+ } catch (IOException e) {
+ // Ignored
+ }
+
+ super.tearDown();
+ }
+
+ /**
+ * @tests java.io.InputStreamReader#close()
+ */
+ public void test_close() throws IOException {
+ is.close();
+ try {
+ is.read();
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // Expected
+ }
+
+ reader.close();
+ try {
+ reader.ready();
+ fail("Should throw IOException");
+ } catch (IOException e) {
+ // Expected
+ }
+
+ // Should be a no-op
+ reader.close();
+
+ // Tests after reader closed
+ in = new BufferedInputStream(
+ this
+ .getClass()
+ .getClassLoader()
+ .getResourceAsStream(
+ "org/apache/harmony/luni/tests/java/io/testfile-utf8.txt"));
+ reader = new InputStreamReader(in, "utf-8");
in.close();
- String result = in.getEncoding();
- assertNull(result);
+ try {
+ int count = reader.read(new char[1]);
+ fail("count:" + count);
+ } catch (IOException e) {
+ // Expected
+ }
+ try {
+ reader.read();
+ fail();
+ } catch (IOException e) {
+ // Expected
+ }
+
+ assertFalse(reader.ready());
+ Charset cs = Charset.forName("utf-8");
+ assertEquals(cs, Charset.forName(reader.getEncoding()));
+ }
+
+ /**
+ * @tests java.io.InputStreamReader#InputStreamReader(java.io.InputStream)
+ */
+ public void test_ConstructorLjava_io_InputStream() throws IOException {
+ try {
+ reader = new InputStreamReader(null);
+ fail();
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ InputStreamReader reader2 = new InputStreamReader(in);
+ reader2.close();
+ }
+
+ /**
+ * @tests java.io.InputStreamReader#InputStreamReader(java.io.InputStream,
+ * java.lang.String)
+ */
+ public void test_ConstructorLjava_io_InputStreamLjava_lang_String()
+ throws IOException {
+ is = new InputStreamReader(fis, "8859_1");
+
+ try {
+ is = new InputStreamReader(fis, "Bogus");
+ fail("Failed to throw Unsupported Encoding exception");
+ } catch (UnsupportedEncodingException e) {
+ // Expected
+ }
+
+ try {
+ reader = new InputStreamReader(null, "utf-8");
+ fail();
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ reader = new InputStreamReader(in, (String) null);
+ fail();
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ reader = new InputStreamReader(in, "");
+ fail();
+ } catch (UnsupportedEncodingException e) {
+ // Expected
+ }
+ try {
+ reader = new InputStreamReader(in, "badname");
+ fail();
+ } catch (UnsupportedEncodingException e) {
+ // Expected
+ }
+ 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();
}
- @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");
+ /**
+ * @tests java.io.InputStreamReader(java.io.InputStream,
+ * java.nio.charset.Charset)
+ */
+ public void test_ConstructorLjava_io_InputStreamLjava_nio_charset_Charset()
+ throws IOException {
+ Charset cs = Charset.forName("utf-8");
+ try {
+ reader = new InputStreamReader(null, cs);
+ fail();
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ reader = new InputStreamReader(in, (Charset) null);
+ fail();
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ InputStreamReader reader2 = new InputStreamReader(in, cs);
+ assertEquals(Charset.forName(reader2.getEncoding()), cs);
+ reader2.close();
+ }
+
+ /**
+ * @tests java.io.InputStreamReader(java.io.InputStream,
+ * java.nio.charset.CharsetDecoder)
+ */
+ public void test_ConstructorLjava_io_InputStreamLjava_nio_charset_CharsetDecoder()
+ throws IOException {
+ CharsetDecoder decoder = Charset.forName("utf-8").newDecoder();
+ try {
+ reader = new InputStreamReader(null, decoder);
+ fail();
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ reader = new InputStreamReader(in, (CharsetDecoder) null);
+ fail();
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ InputStreamReader reader2 = new InputStreamReader(in, decoder);
+ assertEquals(Charset.forName(reader2.getEncoding()), decoder.charset());
+ reader2.close();
+ }
+
+ /**
+ * @tests java.io.InputStreamReader#getEncoding()
+ */
+ public void test_getEncoding() throws IOException {
+ InputStreamReader isr = new InputStreamReader(fis, "8859_1");
+ assertEquals("Returned incorrect encoding when setting 8859_1",
+ "ISO8859_1", isr.getEncoding());
+
+ isr = new InputStreamReader(fis, "ISO-8859-1");
+ assertEquals("Returned incorrect encoding when setting ISO-8859-1",
+ "ISO8859_1", isr.getEncoding());
+
+ byte b[] = new byte[5];
+ isr = new InputStreamReader(new ByteArrayInputStream(b), "UTF-16BE");
+ isr.close();
+ assertNull(isr.getEncoding());
+
+ try {
+ isr = new InputStreamReader(System.in, "UTF-16BE");
+ } catch (UnsupportedEncodingException e) {
+ // Ignored
+ }
+ assertEquals("UnicodeBigUnmarked", isr.getEncoding());
+ }
+
+ /**
+ * @tests java.io.InputStreamReader#read()
+ */
+ public void test_read() 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());
+
+ 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');
+
+ // Regression for HARMONY-166
+ InputStream in;
+
+ 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());
+
+ /*
+ * Temporarily commented out due to lack of ISO2022 support in ICU4J 3.8
+ * 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());
+ */
+ }
+
+ /*
+ * Class under test for int read() Regression for Harmony-411
+ */
+ public void test_read_1() 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 intact
+ 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());
+ }
+
+ public void test_read_specialCharset() throws IOException {
+ reader.close();
+ in = this.getClass().getClassLoader().getResourceAsStream(
+ "org/apache/harmony/luni/tests/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(
+ "org/apache/harmony/luni/tests/java/io/testfile.txt");
+ try {
+ reader = new InputStreamReader(in, "gb18030");
} catch (UnsupportedEncodingException e) {
- // ok
+ System.out
+ .println("GB18030 is not supported, abort test InputStreamReaderTest.testSpecialCharsetReading().");
+ }
+ while ((c = reader.read()) != -1) {
+ sb.append((char) c);
+ }
+ assertEquals(source, sb.toString());
+ }
+
+ /**
+ * @tests java.io.InputStreamReader#read(char[], int, int)
+ */
+ public void test_read$CII() throws IOException {
+ 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]);
+ }
+
+ // Test successive reads
+ 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);
+ assertFalse(-1 == bytesRead);
+ bytesRead = isr.read(buf, 0, buf.length);
+ assertFalse(-1 == bytesRead);
+
+ bis = new ByteArrayInputStream(source.getBytes("UTF-8"));
+ isr = new InputStreamReader(in, "UTF-8");
+ char[] chars = new char[source.length()];
+ assertEquals(source.length() - 3, isr.read(chars, 0, chars.length - 3));
+ assertEquals(3, isr.read(chars, 0, 10));
+ }
+
+ /*
+ * Class under test for int read(char[], int, int)
+ */
+ public void test_read$CII_1() throws IOException {
+ try {
+ // Throws IndexOutOfBoundsException before NullPointerException
+ reader.read(null, -1, 1);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ // Throws NullPointerException before IndexOutOfBoundsException
+ reader.read(null, 0, -1);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
}
- String result = in.getEncoding();
- assertEquals("UnicodeBigUnmarked", result);
+ try {
+ reader.read(null, 0, 1);
+ fail();
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ reader.read(new char[3], -1, 1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ try {
+ reader.read(new char[3], 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ try {
+ reader.read(new char[3], 1, 3);
+ fail();
+ } catch (IndexOutOfBoundsException 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()));
}
+ /**
+ * @tests java.io.InputStreamReader#ready()
+ */
+ public void test_ready() throws IOException {
+ assertTrue("Ready test failed", is.ready());
+ is.read();
+ assertTrue("More chars, but not ready", is.ready());
+
+ assertTrue(reader.ready());
+ reader.read(new char[source.length()]);
+ assertFalse(reader.ready());
+ }
}
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
index 5710dd3..f2eea47 100644
--- 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
@@ -1,309 +1,1179 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
+import java.io.Externalizable;
+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.InvalidClassException;
+import java.io.InvalidObjectException;
+import java.io.NotActiveException;
+import java.io.ObjectInput;
import java.io.ObjectInputStream;
+import java.io.ObjectInputValidation;
+import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
-import java.io.ObjectStreamException;
-import java.io.OptionalDataException;
+import java.io.OutputStream;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
import java.io.Serializable;
+import java.io.SerializablePermission;
import java.io.StreamCorruptedException;
-import java.util.ArrayList;
+import java.lang.reflect.Proxy;
+import java.security.Permission;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Vector;
import junit.framework.TestCase;
import org.apache.harmony.testframework.serialization.SerializationTest;
+import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
-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 {
+@SuppressWarnings("serial")
+public class ObjectInputStreamTest extends TestCase implements
+ Serializable {
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());
+ 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;
+ }
}
- @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();
+ public static class A1 implements Serializable {
+
+ private 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();
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readObject()
+ */
+ 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#ObjectInputStream(java.io.InputStream)
+ */
+ public void test_ConstructorLjava_io_InputStream() throws IOException {
+ oos.writeDouble(Double.MAX_VALUE);
+ oos.close();
ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ ois.close();
+ oos.close();
+
try {
- ois.readUnshared();
- ois.readObject();
- fail("Test 1: ObjectStreamException expected.");
- } catch (ObjectStreamException e) {
- // Expected.
+ ois = new ObjectInputStream(new ByteArrayInputStream(new byte[90]));
+ fail("StreamCorruptedException expected");
+ } catch (StreamCorruptedException e) {
+ // Expected
}
-
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#ObjectInputStream(java.io.InputStream)
+ */
+ public void test_ConstructorLjava_io_InputStream_subtest0() throws IOException {
+ SecurityManager sm = System.getSecurityManager();
+ System.setSecurityManager(new SecurityManager() {
+ Permission golden = new SerializablePermission("enableSubclassImplementation");
+
+ @Override
+ public void checkPermission(Permission p) {
+ if (golden.equals(p)) {
+ throw new SecurityException();
+ }
+ }
+ });
+
try {
- ois.readUnshared();
- fail("Test 2: OptionalDataException expected.");
- } catch (OptionalDataException e) {
- // Expected.
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ObjectOutputStream obout = new ObjectOutputStream(out);
+ obout.write(0);
+ obout.close();
+
+ InputStream in = new ByteArrayInputStream(out.toByteArray());
+
+ // should not cause SecurityException
+ new ObjectInputStream(in);
+ in.reset();
+
+ // should not cause SecurityException
+ new ObjectInputStream(in) {};
+ in.reset();
+
+ try {
+ new ObjectInputStream(in) {
+ @Override
+ public Object readUnshared() throws IOException, ClassNotFoundException {
+ return null;
+ }
+ };
+ fail("should throw SecurityException 1");
+ } catch (SecurityException e) {
+ // Expected
+ }
+
+ in.reset();
+ try {
+ new ObjectInputStream(in) {
+ @Override
+ public GetField readFields() throws IOException,
+ ClassNotFoundException, NotActiveException {
+ return null;
+ }
+ };
+ fail("should throw SecurityException 2");
+ } catch (SecurityException e) {
+ // Expected
+ }
+ } finally {
+ System.setSecurityManager(sm);
+ }
+ }
+
+ /**
+ * @tests {@link java.io.ObjectInputStream#resolveProxyClass(String[])}
+ */
+ public void test_resolveProxyClass() throws IOException,
+ ClassNotFoundException {
+ oos.writeBytes("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ MockObjectInputStream mockIn = new MockObjectInputStream(
+ new ByteArrayInputStream(bao.toByteArray()));
+ Class[] clazzs = { java.io.ObjectInputStream.class,
+ java.io.Reader.class };
+ for (int i = 0; i < clazzs.length; i++) {
+ Class clazz = clazzs[i];
+ Class[] interfaceNames = clazz.getInterfaces();
+ String[] interfaces = new String[interfaceNames.length];
+ int index = 0;
+ for (Class c : interfaceNames) {
+ interfaces[index] = c.getName();
+ index++;
+ }
+ Class<?> s = mockIn.resolveProxyClass(interfaces);
+
+ if (Proxy.isProxyClass(s)) {
+ Class[] implementedInterfaces = s.getInterfaces();
+ for (index = 0; index < implementedInterfaces.length; index++) {
+ assertEquals(interfaceNames[index],
+ implementedInterfaces[index]);
+ }
+ } else {
+ fail("Should return a proxy class that implements the interfaces named in a proxy class descriptor");
+ }
}
+ mockIn.close();
+ }
+
+ class MockObjectInputStream extends ObjectInputStream {
+
+ public MockObjectInputStream(InputStream input)
+ throws StreamCorruptedException, IOException {
+ super(input);
+ }
+
+ @Override
+ public Class<?> resolveProxyClass(String[] interfaceNames) throws IOException, ClassNotFoundException {
+ return super.resolveProxyClass(interfaceNames);
+ }
+
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#available()
+ */
+ public void test_available() throws IOException {
+ oos.writeBytes("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertEquals("Read incorrect bytes", 10, ois.available());
ois.close();
- }
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#close()
+ */
+ public void test_close() throws IOException {
+ oos.writeBytes("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ ois.close();
+ }
/**
- * @tests java.io.ObjectInputStream#readUnshared()
+ * @tests java.io.ObjectInputStream#defaultReadObject()
*/
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks StreamCorruptedException.",
- method = "readUnshared",
- args = {}
- )
- public void test_readUnshared_2() throws IOException, ClassNotFoundException {
+ public void test_defaultReadObject() throws Exception {
+ // SM. This method may as well be private, as if called directly it
+ // throws an exception.
+ String s = "HelloWorld";
+ oos.writeObject(s);
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.defaultReadObject();
+ fail("NotActiveException expected");
+ } catch (NotActiveException e) {
+ // Desired behavior
+ } finally {
+ ois.close();
}
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#read()
+ */
+ public void test_read() throws IOException {
+ 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#readUnshared()
+ * @tests java.io.ObjectInputStream#read(byte[], int, int)
*/
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Checks IOException.",
- method = "readUnshared",
- args = {}
- )
- public void test_readUnshared_3() throws IOException, ClassNotFoundException {
- bao.write(testString.getBytes());
+ public void test_read$BII() throws IOException {
+ byte[] buf = new byte[10];
+ oos.writeBytes("HelloWorld");
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, "UTF-8"));
+ }
- 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;
+ /**
+ * @tests java.io.ObjectInputStream#readBoolean()
+ */
+ public void test_readBoolean() throws IOException {
+ oos.writeBoolean(true);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertTrue("Read incorrect boolean value", ois.readBoolean());
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.
+ * @tests java.io.ObjectInputStream#readByte()
*/
- @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();
+ public void test_readByte() throws IOException {
+ oos.writeByte(127);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertEquals("Read incorrect byte value", 127, ois.readByte());
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()}
+ * @tests java.io.ObjectInputStream#readChar()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization.",
- method = "!SerializationSelf",
- args = {}
- )
- public void test_readNewLongString() throws Exception {
- LongString longString = new LongString();
- SerializationTest.verifySelf(longString);
+ public void test_readChar() throws IOException {
+ oos.writeChar('T');
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertEquals("Read incorrect char value", 'T', ois.readChar());
+ ois.close();
}
-
- 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');
+
+ /**
+ * @tests java.io.ObjectInputStream#readDouble()
+ */
+ public void test_readDouble() throws IOException {
+ oos.writeDouble(Double.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertTrue("Read incorrect double value",
+ ois.readDouble() == Double.MAX_VALUE);
+ ois.close();
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readFields()
+ */
+ public void test_readFields() throws Exception {
+
+ 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#readFloat()
+ */
+ public void test_readFloat() throws IOException {
+ oos.writeFloat(Float.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertTrue("Read incorrect float value",
+ ois.readFloat() == Float.MAX_VALUE);
+ ois.close();
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readFully(byte[])
+ */
+ public void test_readFully$B() throws IOException {
+ byte[] buf = new byte[10];
+ oos.writeBytes("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ ois.readFully(buf);
+ ois.close();
+ assertEquals("Read incorrect bytes", "HelloWorld", new String(buf, 0,
+ 10, "UTF-8"));
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readFully(byte[], int, int)
+ */
+ public void test_readFully$BII() throws IOException {
+ byte[] buf = new byte[10];
+ oos.writeBytes("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ ois.readFully(buf, 0, 10);
+ ois.close();
+ assertEquals("Read incorrect bytes", "HelloWorld", new String(buf, 0,
+ 10, "UTF-8"));
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readInt()
+ */
+ public void test_readInt() throws IOException {
+ oos.writeInt(Integer.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertTrue("Read incorrect int value",
+ ois.readInt() == Integer.MAX_VALUE);
+ ois.close();
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readLine()
+ */
+ @SuppressWarnings("deprecation")
+ public void test_readLine() throws IOException {
+ oos.writeBytes("HelloWorld\nSecondLine");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ ois.readLine();
+ assertEquals("Read incorrect string value", "SecondLine", ois
+ .readLine());
+ ois.close();
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readLong()
+ */
+ public void test_readLong() throws IOException {
+ oos.writeLong(Long.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertTrue("Read incorrect long value",
+ ois.readLong() == Long.MAX_VALUE);
+ ois.close();
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readObject()
+ */
+ public void test_readObject() throws Exception {
+ String s = "HelloWorld";
+ 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("UTF-8");
+ byte[] aName = A.class.getName().getBytes("UTF-8");
+
+ 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());
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readObjectOverride()
+ */
+ public void test_readObjectOverride() throws Exception {
+ // Regression for HARMONY-846
+ assertNull(new ObjectInputStream() {
+
+ @Override
+ public Object readObjectOverride() throws IOException,
+ ClassNotFoundException {
+ return super.readObjectOverride();
}
- lString = builder.toString();
+
+ }.readObjectOverride());
+ }
+
+ 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;
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readObject()
+ */
+ public void test_readObjectCorrupt() throws IOException, ClassNotFoundException {
+ byte[] bytes = { 00, 00, 00, 0x64, 0x43, 0x48, (byte) 0xFD, 0x71, 00,
+ 00, 0x0B, (byte) 0xB8, 0x4D, 0x65 };
+ ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
+ try {
+ ObjectInputStream in = new ObjectInputStream(bin);
+ in.readObject();
+ fail("Unexpected read of corrupted stream");
+ } catch (StreamCorruptedException e) {
+ // Expected
}
-
- @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;
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readShort()
+ */
+ public void test_readShort() throws IOException {
+ oos.writeShort(Short.MAX_VALUE);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertTrue("Read incorrect short value",
+ ois.readShort() == Short.MAX_VALUE);
+ ois.close();
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readUnsignedByte()
+ */
+ public void test_readUnsignedByte() throws IOException {
+ oos.writeByte(-1);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertEquals("Read incorrect unsignedByte value", 255, ois
+ .readUnsignedByte());
+ ois.close();
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readUnsignedShort()
+ */
+ public void test_readUnsignedShort() throws IOException {
+ oos.writeShort(-1);
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertEquals("Read incorrect unsignedShort value", 65535, ois
+ .readUnsignedShort());
+ ois.close();
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#readUTF()
+ */
+ public void test_readUTF() throws IOException {
+ oos.writeUTF("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ assertEquals("Read incorrect utf value", "HelloWorld", ois.readUTF());
+ ois.close();
+ }
+
+ /**
+ * @tests java.io.ObjectInputStream#skipBytes(int)
+ */
+ public void test_skipBytesI() throws IOException {
+ byte[] buf = new byte[10];
+ oos.writeBytes("HelloWorld");
+ oos.close();
+ ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
+ ois.skipBytes(5);
+ ois.read(buf, 0, 5);
+ ois.close();
+ assertEquals("Skipped incorrect bytes", "World", new String(buf, 0, 5, "UTF-8"));
+
+ // Regression for HARMONY-844
+ try {
+ new ObjectInputStream() {}.skipBytes(0);
+ fail("NullPointerException expected");
+ } catch (NullPointerException e) {}
+ }
+
+ // Regression Test for JIRA 2192
+ public void test_readObject_withPrimitiveClass() throws Exception {
+ File file = new File("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);
+ }
+
+ //Regression Test for JIRA-2249
+ public static class ObjectOutputStreamWithWriteDesc extends
+ ObjectOutputStream {
+ public ObjectOutputStreamWithWriteDesc(OutputStream os)
+ throws IOException {
+ super(os);
}
-
+
@Override
- public int hashCode() {
- return lString.hashCode();
+ public void writeClassDescriptor(ObjectStreamClass desc)
+ throws IOException {
}
}
- 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);
- }
- }
+ public static class ObjectIutputStreamWithReadDesc extends
+ ObjectInputStream {
+ private Class returnClass;
- 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);
+ public ObjectIutputStreamWithReadDesc(InputStream is, Class returnClass)
+ throws IOException {
+ super(is);
+ this.returnClass = returnClass;
}
- }
-
- 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.
+
+ @Override
+ public ObjectStreamClass readClassDescriptor() throws IOException,
+ ClassNotFoundException {
+ return ObjectStreamClass.lookup(returnClass);
+
}
}
- static class TestObjectInputStream extends ObjectInputStream {
- public TestObjectInputStream(InputStream in) throws IOException {
+ static class TestClassForSerialization implements Serializable {
+ private static final long serialVersionUID = 1L;
+ }
+
+ 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());
+ ObjectIutputStreamWithReadDesc ois = new ObjectIutputStreamWithReadDesc(
+ bais, cls);
+ Object obj = ois.readObject();
+ ois.close();
+ assertEquals(cls, obj);
+ }
+
+ // Regression Test for JIRA-2340
+ public static class ObjectOutputStreamWithWriteDesc1 extends
+ ObjectOutputStream {
+ public ObjectOutputStreamWithWriteDesc1(OutputStream os)
+ throws IOException {
+ super(os);
+ }
+
+ @Override
+ public void writeClassDescriptor(ObjectStreamClass desc)
+ throws IOException {
+ super.writeClassDescriptor(desc);
+ }
+ }
+
+ public static class ObjectIutputStreamWithReadDesc1 extends
+ ObjectInputStream {
+
+ public ObjectIutputStreamWithReadDesc1(InputStream is)
+ throws IOException {
+ super(is);
+ }
+
+ @Override
+ 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)
+ @Override
+ @SuppressWarnings("unchecked")
+ protected Class resolveClass(ObjectStreamClass desc)
throws IOException, ClassNotFoundException {
- if (desc.getName().endsWith("ObjectInputStreamTest$TestClass1")) {
- return TestClass2.class;
+ if (desc.getName().equals(
+ "org.apache.harmony.luni.tests.pkg1.TestClass")) {
+ return org.apache.harmony.luni.tests.pkg2.TestClass.class;
}
return super.resolveClass(desc);
}
}
- static class TestClass1 implements Serializable {
- private static final long serialVersionUID = 11111L;
- int i = 0;
+ 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 TestClass2 implements Serializable {
- private static final long serialVersionUID = 11111L;
- int i = 0;
+ static class ObjectInputStreamWithResolveObject extends ObjectInputStream {
+
+ public static Integer intObj = Integer.valueOf(1000);
+
+ public ObjectInputStreamWithResolveObject(InputStream in) throws IOException {
+ super(in);
+ enableResolveObject(true);
+ }
+
+ @Override
+ protected Object resolveObject(Object obj) throws IOException {
+ if(obj instanceof Integer){
+ obj = intObj;
+ }
+ return super.resolveObject(obj);
+ }
}
- @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();
+
+ /**
+ * @tests java.io.ObjectInputStream#resolveObject(Object)
+ */
+ 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);
- ByteArrayInputStream bais;
- ObjectInputStream ois;
-
- to1.i = 555;
- oos.writeObject(to1);
+ 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);
+ }
+
+ 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);
+ ObjectIutputStreamWithReadDesc1 ois = new ObjectIutputStreamWithReadDesc1(
+ bais);
+ Object obj = ois.readClassDescriptor();
+ ois.close();
+ assertEquals(desc.getClass(), obj.getClass());
+
+ //eof
bais = new ByteArrayInputStream(bytes);
- ois = new TestObjectInputStream(bais);
+ ExceptionalBufferedInputStream bis = new ExceptionalBufferedInputStream(
+ bais);
+ ois = new ObjectIutputStreamWithReadDesc1(bis);
+
+ bis.setEOF(true);
try {
- ois.readObject();
- fail("Test 1: InvalidClassException expected.");
- } catch (InvalidClassException ice) {
- // Expected.
+ obj = ois.readClassDescriptor();
+ } catch (IOException e) {
+ //e.printStackTrace();
+ } finally {
+ ois.close();
+ }
+
+ //throw exception
+ bais = new ByteArrayInputStream(bytes);
+ bis = new ExceptionalBufferedInputStream(bais);
+ ois = new ObjectIutputStreamWithReadDesc1(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 ObjectIutputStreamWithReadDesc1(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);
+ }
+
+ @Override
+ 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;
+ }
+ }
+
+ public static class ObjectIutputStreamWithReadDesc2 extends
+ ObjectInputStream {
+ private Class returnClass;
+
+ public ObjectIutputStreamWithReadDesc2(InputStream is, Class returnClass)
+ throws IOException {
+ super(is);
+ this.returnClass = returnClass;
+ }
+
+ @Override
+ public ObjectStreamClass readClassDescriptor() throws IOException,
+ ClassNotFoundException {
+ ObjectStreamClass osc = super.readClassDescriptor();
+
+ if (osc.getName().equals(returnClass.getName())) {
+ return ObjectStreamClass.lookup(returnClass);
+ }
+ return osc;
}
}
+
+ /*
+ * Testing classDescriptor replacement with the value generated by
+ * ObjectStreamClass.lookup() method.
+ * Regression test for HARMONY-4638
+ */
+ public void test_readClassDescriptor_1() throws IOException, ClassNotFoundException {
+ A a = new A();
+ a.name = "It's a test";
+ PipedOutputStream pout = new PipedOutputStream();
+ PipedInputStream pin = new PipedInputStream(pout);
+ ObjectOutputStream out = new ObjectOutputStream(pout);
+ ObjectInputStream in = new ObjectIutputStreamWithReadDesc2(pin, A.class);
+
+ // test single object
+ out.writeObject(a);
+ A a1 = (A) in.readObject();
+ assertEquals("Single case: incorrectly read the field of A", a.name, a1.name);
+
+ // test cyclic reference
+ HashMap m = new HashMap();
+ a = new A();
+ a.name = "It's a test 0";
+ a1 = new A();
+ a1.name = "It's a test 1";
+ m.put("0", a);
+ m.put("1", a1);
+ out.writeObject(m);
+ HashMap m1 = (HashMap) in.readObject();
+ assertEquals("Incorrectly read the field of A", a.name, ((A) m1.get("0")).name);
+ assertEquals("Incorrectly read the field of A1", a1.name, ((A) m1.get("1")).name);
+ }
+
+ public void test_registerValidation() throws Exception {
+ // Regression Test for Harmony-2402
+ 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
+ }
+
+ // Regression Test for Harmony-3916
+ baos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+ oos.writeObject(new RegisterValidationClass());
+ oos.close();
+ ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
+ ObjectInputStream fis = new ObjectInputStream(bais);
+ // should not throw NotActiveException
+ fis.readObject();
+ }
+
+ private static class RegisterValidationClass implements Serializable {
+ @SuppressWarnings("unused")
+ private A a = new A();
+ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
+ stream.defaultReadObject();
+ stream.registerValidation(new MockObjectInputValidation(), 0);
+ }
+ }
+
+ private static class MockObjectInputValidation implements ObjectInputValidation {
+ public void validateObject() throws InvalidObjectException {
+
+ }
+ }
+
+ //Regression Test for HARMONY-3726
+ public void test_readObject_array() throws Exception {
+
+ final String resourcePrefix = ObjectInputStreamTest.class.getPackage().getName().replace('.', '/');
+
+// ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/temp/test_array_strings.ser"));
+// TestArray ta = new TestArray(new String[] { "AAA", "BBB" });
+// oos.writeObject(ta);
+// oos.close();
+// oos = new ObjectOutputStream(new FileOutputStream("/temp/test_array_integers.ser"));
+// ta = new TestArray(new Integer[] { 10, 20 });
+// oos.writeObject(ta);
+// oos.close();
+
+ ObjectInputStream oin = new ObjectInputStream(this.getClass().getClassLoader().getResourceAsStream(
+ "serialization/" + resourcePrefix + "/test_array_strings.ser"));
+ TestArray testArray = (TestArray) oin.readObject();
+ String[] strings = new String[] { "AAA", "BBB" };
+ assertTrue(java.util.Arrays.equals(strings, testArray.array));
+
+ oin = new ObjectInputStream(this.getClass().getClassLoader().getResourceAsStream(
+ "serialization/" + resourcePrefix + "/test_array_integers.ser"));
+ testArray = (TestArray) oin.readObject();
+ Integer[] integers = new Integer[] { 10, 20 };
+ assertTrue(java.util.Arrays.equals(integers, testArray.array));
+ }
+
+ public static class TestExtObject implements Externalizable {
+ public void writeExternal(ObjectOutput out) throws IOException {
+ out.writeInt(10);
+ }
+
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+ in.readInt();
+ }
+ }
+
+ static class TestObjectOutputStream extends ObjectOutputStream {
+ private ObjectStreamClass[] objs;
+ private int pos = 0;
+
+ public TestObjectOutputStream(OutputStream out, ObjectStreamClass[] objs) throws IOException {
+ super(out);
+ this.objs = objs;
+ }
+
+ @Override
+ protected void writeClassDescriptor(ObjectStreamClass osc) throws IOException {
+ objs[pos++] = osc; }
+ }
+
+ static class TestObjectInputStream extends ObjectInputStream {
+ private ObjectStreamClass[] objs;
+ private int pos = 0;
+
+ public TestObjectInputStream(InputStream in, ObjectStreamClass[] objs) throws IOException {
+ super(in);
+ this.objs = objs;
+ }
+
+ @Override
+ protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException {
+ return objs[pos++];
+ }
+ }
+
+ // Regression test for HARMONY-4996
+ public void test_readObject_replacedClassDescriptor() throws Exception {
+ ObjectStreamClass[] objs = new ObjectStreamClass[1000];
+ PipedOutputStream pout = new PipedOutputStream();
+ PipedInputStream pin = new PipedInputStream(pout);
+ ObjectOutputStream oout = new TestObjectOutputStream(pout, objs);
+ oout.writeObject(new TestExtObject());
+ oout.writeObject("test");
+ oout.close();
+ ObjectInputStream oin = new TestObjectInputStream(pin, objs);
+ oin.readObject();
+ oin.readObject();
+ }
+
+ /**
+ * 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 {
+ super.setUp();
+ oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
+ }
+}
+
+class TestArray implements Serializable
+{
+ private static final long serialVersionUID = 1L;
+
+ public Object[] array;
+
+ public TestArray(Object[] array) {
+ this.array = array;
+ }
+
}
+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 };
+ @Override
+ 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/org/apache/harmony/luni/tests/java/io/ObjectStreamConstantsTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/io/ObjectStreamConstantsTest.java
index f13c537..b86e9f6 100644
--- 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
@@ -19,25 +19,27 @@ 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() {
+ public void test_TC_ENUM() {
assertEquals(126, ObjectStreamConstants.TC_ENUM);
+ }
+
+ /**
+ * @tests java.io.ObjectStreamConstants#SC_ENUM
+ */
+ public void test_SC_ENUM() {
assertEquals(16, ObjectStreamConstants.SC_ENUM);
+ }
+
+ /**
+ * @tests java.io.ObjectStreamConstants#TC_MAX
+ */
+ public void test_TC_MAX() {
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
index 732ee50..837b443 100644
--- 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
@@ -1,81 +1,703 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileReader;
+import java.io.FileWriter;
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 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;
+
+ private static final int UPPER = 0xd800;
+
+ private static final int BUFFER_SIZE = 10000;
+
+ private ByteArrayOutputStream out;
+
+ private OutputStreamWriter writer;
+
+ static private final String source = "This is a test message with Unicode character. \u4e2d\u56fd is China's name in Chinese";
+
+ 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 ByteArrayOutputStream fos;
+
+ 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\n";
+
+ /*
+ * @see TestCase#setUp()
+ */
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ out = new ByteArrayOutputStream();
+ writer = new OutputStreamWriter(out, "utf-8");
+
+ fos = new ByteArrayOutputStream();
+ osw = new OutputStreamWriter(fos);
+ }
+
+ /*
+ * @see TestCase#tearDown()
+ */
+ @Override
+ protected void tearDown() throws Exception {
try {
- out = new OutputStreamWriter(new ByteArrayOutputStream(),
- "UTF-16BE");
+ writer.close();
+
+ if (isr != null) {
+ isr.close();
+ }
+ osw.close();
+ } catch (Exception e) {
+ // Ignored
+ }
+
+ super.tearDown();
+ }
+
+ public void testClose() throws Exception {
+ writer.flush();
+ writer.close();
+ try {
+ writer.flush();
+ fail();
+ } catch (IOException e) {
+ // Expected
+ }
+ }
+
+ public void testFlush() throws Exception {
+ writer.write(source);
+ writer.flush();
+ String result = out.toString("utf-8");
+ assertEquals(source, result);
+ }
+
+ /*
+ * Class under test for void write(char[], int, int)
+ */
+ public void testWritecharArrayintint() throws IOException {
+ char[] chars = source.toCharArray();
+
+ // Throws IndexOutOfBoundsException if offset is negative
+ try {
+ writer.write((char[]) null, -1, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ // throws NullPointerException though count is negative
+ try {
+ writer.write((char[]) null, 1, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ writer.write((char[]) null, 1, 1);
+ fail();
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ writer.write(new char[0], 0, 1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ try {
+ writer.write(chars, -1, 1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ try {
+ writer.write(chars, 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ try {
+ writer.write(chars, 1, chars.length);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ writer.write(chars, 1, 2);
+ writer.flush();
+ assertEquals("hi", out.toString("utf-8"));
+ writer.write(chars, 0, chars.length);
+ writer.flush();
+ assertEquals("hi" + source, out.toString("utf-8"));
+
+ writer.close();
+ // After the stream is closed, should throw IOException first
+ try {
+ writer.write((char[]) null, -1, -1);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // Expected
+ }
+ }
+
+ /*
+ * Class under test for void write(int)
+ */
+ public void testWriteint() throws IOException {
+ writer.write(1);
+ writer.flush();
+ String str = new String(out.toByteArray(), "utf-8");
+ assertEquals("\u0001", str);
+
+ writer.write(2);
+ writer.flush();
+ str = new String(out.toByteArray(), "utf-8");
+ assertEquals("\u0001\u0002", str);
+
+ writer.write(-1);
+ writer.flush();
+ str = new String(out.toByteArray(), "utf-8");
+ assertEquals("\u0001\u0002\uffff", str);
+
+ writer.write(0xfedcb);
+ writer.flush();
+ str = new String(out.toByteArray(), "utf-8");
+ assertEquals("\u0001\u0002\uffff\uedcb", str);
+
+ writer.close();
+ // After the stream is closed, should throw IOException
+ try {
+ writer.write(1);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for void write(String, int, int)
+ */
+ public void testWriteStringintint() throws IOException {
+ try {
+ writer.write((String) null, 1, 1);
+ fail();
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ writer.write("", 0, 1);
+ fail();
+ } catch (StringIndexOutOfBoundsException e) {
+ // Expected
+ }
+ try {
+ writer.write("abc", -1, 1);
+ fail();
+ } catch (StringIndexOutOfBoundsException e) {
+ // Expected
+ }
+ try {
+ writer.write("abc", 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+ try {
+ writer.write("abc", 1, 3);
+ fail();
+ } catch (StringIndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ // Throws IndexOutOfBoundsException before NullPointerException if count
+ // is negative
+ try {
+ writer.write((String) null, -1, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ // Throws NullPointerException before StringIndexOutOfBoundsException
+ try {
+ writer.write((String) null, -1, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ writer.write("abc", 1, 2);
+ writer.flush();
+ assertEquals("bc", out.toString("utf-8"));
+ writer.write(source, 0, source.length());
+ writer.flush();
+ assertEquals("bc" + source, out.toString("utf-8"));
+
+ writer.close();
+ // Throws IndexOutOfBoundsException first if count is negative
+ try {
+ writer.write((String) null, 0, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ try {
+ writer.write((String) null, -1, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Expected
+ }
+
+ try {
+ writer.write("abc", -1, 0);
+ fail("should throw StringIndexOutOfBoundsException");
+ } catch (StringIndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ // Throws IOException
+ try {
+ writer.write("abc", 0, 1);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for void OutputStreamWriter(OutputStream)
+ */
+ public void testOutputStreamWriterOutputStream() throws IOException {
+ try {
+ writer = new OutputStreamWriter(null);
+ fail();
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ OutputStreamWriter writer2 = new OutputStreamWriter(out);
+ writer2.close();
+ }
+
+ /*
+ * Class under test for void OutputStreamWriter(OutputStream, String)
+ */
+ public void testOutputStreamWriterOutputStreamString() throws IOException {
+ try {
+ writer = new OutputStreamWriter(null, "utf-8");
+ fail();
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ writer = new OutputStreamWriter(out, "");
+ fail();
+ } catch (UnsupportedEncodingException e) {
+ // Expected
+ }
+ try {
+ writer = new OutputStreamWriter(out, "badname");
+ fail();
+ } catch (UnsupportedEncodingException e) {
+ // Expected
+ }
+ try {
+ writer = new OutputStreamWriter(out, (String) null);
+ fail();
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ OutputStreamWriter writer2 = new OutputStreamWriter(out, "ascii");
+ assertEquals(Charset.forName("ascii"), Charset.forName(writer2
+ .getEncoding()));
+ writer2.close();
+ }
+
+ /*
+ * Class under test for void OutputStreamWriter(OutputStream)
+ */
+ public void testOutputStreamWriterOutputStreamCharset() throws IOException {
+ Charset cs = Charset.forName("ascii");
+ try {
+ writer = new OutputStreamWriter(null, cs);
+ fail();
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ writer = new OutputStreamWriter(out, (Charset) null);
+ fail();
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ OutputStreamWriter writer2 = new OutputStreamWriter(out, cs);
+ assertEquals(cs, Charset.forName(writer2.getEncoding()));
+ writer2.close();
+ }
+
+ /*
+ * Class under test for void OutputStreamWriter(OutputStream, String)
+ */
+ public void testOutputStreamWriterOutputStreamCharsetEncoder()
+ throws IOException {
+ Charset cs = Charset.forName("ascii");
+ CharsetEncoder enc = cs.newEncoder();
+ try {
+ writer = new OutputStreamWriter(null, enc);
+ fail();
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ try {
+ writer = new OutputStreamWriter(out, (CharsetEncoder) null);
+ fail();
+ } catch (NullPointerException e) {
+ // Expected
+ }
+ OutputStreamWriter writer2 = new OutputStreamWriter(out, enc);
+ assertEquals(cs, Charset.forName(writer2.getEncoding()));
+ writer2.close();
+ }
+
+ public void testGetEncoding() {
+ Charset cs = Charset.forName("utf-8");
+ assertEquals(cs, Charset.forName(writer.getEncoding()));
+ }
+
+ public void testHandleEarlyEOFChar_1() throws IOException {
+ 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;
+ 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 = File.createTempFile("one", "by_one");
+ f.deleteOnExit();
+ FileWriter fw = new FileWriter(f);
+ fw.write(strChars);
+ fw.close();
+ FileInputStream fis = new FileInputStream(f);
+ InputStreamReader in = new InputStreamReader(fis);
+ for (int offset = 0; offset < strChars.length; ++offset) {
+ int b = in.read();
+ assertFalse("Early EOF at offset", -1 == b);
+ }
+ }
+
+ public void testHandleEarlyEOFChar_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$
+ f.deleteOnExit();
+ 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);
+
+ assertEquals(len, flen);
+ assertEquals(inputStr, outStr);
+ }
+
+ public void testSingleCharIO() throws Exception {
+ InputStreamReader isr = null;
+ for (int i = 0; i < MINIMAL_CHARSETS.length; ++i) {
+ try {
+ out = new ByteArrayOutputStream();
+ writer = new OutputStreamWriter(out, MINIMAL_CHARSETS[i]);
+
+ int upper = UPPER;
+ switch (i) {
+ case 0:
+ upper = 128;
+ break;
+ case 1:
+ upper = 256;
+ break;
+ }
+
+ 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 {
+ isr.close();
+ } catch (Exception e) {
+ }
+ try {
+ writer.close();
+ } catch (Exception e) {
+ }
+ }
+ }
+ }
+
+ public void testBlockIO() throws Exception {
+ InputStreamReader isr = null;
+ char[] largeBuffer = new char[BUFFER_SIZE];
+ for (int i = 0; i < MINIMAL_CHARSETS.length; ++i) {
+ try {
+ out = new ByteArrayOutputStream();
+ writer = new OutputStreamWriter(out, MINIMAL_CHARSETS[i]);
+
+ int upper = UPPER;
+ switch (i) {
+ case 0:
+ upper = 128;
+ break;
+ case 1:
+ upper = 256;
+ break;
+ }
+
+ 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 = out.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 {
+ isr.close();
+ } catch (Exception e) {
+ }
+ try {
+ writer.close();
+ } catch (Exception e) {
+ }
+ }
+ }
+ }
+
+ /**
+ * @tests java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
+ */
+ public void test_ConstructorLjava_io_OutputStream() {
+ assertTrue("Used in tests", true);
+ }
+
+ /**
+ * @tests java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream,
+ * java.lang.String)
+ */
+ public void test_ConstructorLjava_io_OutputStreamLjava_lang_String()
+ throws UnsupportedEncodingException {
+ osw = new OutputStreamWriter(fos, "8859_1");
+ try {
+ osw = new OutputStreamWriter(fos, "Bogus");
+ fail("Failed to throw Unsupported Encoding exception");
} catch (UnsupportedEncodingException e) {
- fail("Should not throw UnsupportedEncodingException");
+ // Expected
}
+ }
+
+ /**
+ * @tests java.io.OutputStreamWriter#close()
+ */
+ public void test_close() throws IOException {
+ osw.close();
+
try {
- out.close();
+ osw.write(testString, 0, testString.length());
+ fail("Chars written after close");
} catch (IOException e) {
- fail("Should not throw IOException");
+ // Expected
+ }
+
+ 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("invalid conversion 1: " + 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("invalid conversion 2: " + converted, converted
+ .equals("\u001b$B$("));
+ writer.close();
+ converted = new String(bout.toByteArray(), "ISO8859_1");
+ assertTrue("invalid conversion 3: " + 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("invalid conversion 4", "\u001b$B$($(\u001b(B",
+ new String(bout.toByteArray(), "ISO8859_1"));
+ } catch (UnsupportedEncodingException e) {
+ // Can't test missing converter
+ System.out.println(e);
}
+ }
+
+ /**
+ * @tests java.io.OutputStreamWriter#flush()
+ */
+ public void test_flush() throws IOException {
+ char[] buf = new char[testString.length()];
+ osw.write(testString, 0, testString.length());
+ osw.flush();
+ openInputStream();
+ isr.read(buf, 0, buf.length);
+ assertTrue("Chars not flushed", new String(buf, 0, buf.length)
+ .equals(testString));
+ }
+
+ /**
+ * @tests java.io.OutputStreamWriter#getEncoding()
+ */
+ public void test_getEncoding() throws IOException {
+ try {
+ osw = new OutputStreamWriter(fos, "8859_1");
+ } catch (UnsupportedEncodingException e) {
+ assertEquals("Returned incorrect encoding", "8859_1", osw
+ .getEncoding());
+ }
+
+ OutputStreamWriter out = new OutputStreamWriter(
+ new ByteArrayOutputStream(), "UTF-16BE");
+ out.close();
+
String result = out.getEncoding();
assertNull(result);
- }
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getEncoding",
- args = {}
- )
- public void testGetEncoding_NotHistorical() {
- OutputStreamWriter out = null;
+ out = null;
try {
out = new OutputStreamWriter(new ByteArrayOutputStream(),
"UTF-16BE");
} catch (UnsupportedEncodingException e) {
// ok
}
- String result = out.getEncoding();
+ result = out.getEncoding();
assertEquals("UnicodeBigUnmarked", result);
}
-} \ No newline at end of file
+
+ /**
+ * @tests java.io.OutputStreamWriter#write(char[], int, int)
+ */
+ public void test_write$CII() throws IOException {
+ char[] buf = new char[testString.length()];
+ osw.write(testString, 0, testString.length());
+ osw.close();
+ openInputStream();
+ isr.read(buf, 0, buf.length);
+ assertTrue("Incorrect chars returned", new String(buf, 0, buf.length)
+ .equals(testString));
+ }
+
+ /**
+ * @tests java.io.OutputStreamWriter#write(int)
+ */
+ public void test_writeI() throws IOException {
+ osw.write('T');
+ osw.close();
+ openInputStream();
+ int c = isr.read();
+ assertEquals("Incorrect char returned", 'T', (char) c);
+ }
+
+ /**
+ * @tests java.io.OutputStreamWriter#write(java.lang.String, int, int)
+ */
+ public void test_writeLjava_lang_StringII() throws IOException {
+ char[] buf = new char[testString.length()];
+ osw.write(testString, 0, testString.length());
+ osw.close();
+ openInputStream();
+ isr.read(buf);
+ assertTrue("Incorrect chars returned", new String(buf, 0, buf.length)
+ .equals(testString));
+ }
+
+ private void openInputStream() {
+ isr = new InputStreamReader(new ByteArrayInputStream(fos.toByteArray()));
+ }
+}
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
index 4756c09..67e1fb5 100644
--- 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
@@ -1,51 +1,984 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.EOFException;
import java.io.File;
+import java.io.FileInputStream;
+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;
-@TestTargetClass(RandomAccessFile.class)
-public class RandomAccessFileTest extends TestCase {
+import java.nio.channels.FileChannel;
+import java.nio.channels.NonWritableChannelException;
+
+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";
+
+ //java.io.FileOutputStream fos;
+
+ 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_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.RandomAccessFile#RandomAccessFile(java.io.File, java.lang.String)
+ * @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 {
+ public void test_ConstructorLjava_io_FileLjava_lang_String()
+ throws Exception {
+ // Test for method java.io.RandomAccessFile(java.io.File,
+ // java.lang.String)
+ RandomAccessFile raf = new java.io.RandomAccessFile(f, "rw");
+ raf.write(20);
+ raf.seek(0);
+ assertEquals("Incorrect int read/written", 20, raf.read());
+ raf.close();
+
+ raf = new java.io.RandomAccessFile(f, "rwd");
+ raf.write(20);
+ raf.seek(0);
+ assertEquals("Incorrect int read/written", 20, raf.read());
+ raf.close();
+
+ raf = new java.io.RandomAccessFile(f, "rws");
+ raf.write(20);
+ raf.seek(0);
+ assertEquals("Incorrect int read/written", 20, raf.read());
+ raf.close();
+
// Regression for HARMONY-50
File f = File.createTempFile("xxx", "yyy");
f.deleteOnExit();
- RandomAccessFile raf = new RandomAccessFile(f, "rws");
+ raf = new RandomAccessFile(f, "rws");
raf.close();
f = File.createTempFile("xxx", "yyy");
f.deleteOnExit();
raf = new RandomAccessFile(f, "rwd");
- raf.close();
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#RandomAccessFile(java.lang.String,
+ * java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_StringLjava_lang_String()
+ throws IOException {
+ // Test for method java.io.RandomAccessFile(java.lang.String,
+ // java.lang.String)
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.write("Test".getBytes(), 0, 4);
+ raf.close();
+
+ raf = new java.io.RandomAccessFile(fileName, "rwd");
+ raf.write("Test".getBytes(), 0, 4);
+ raf.close();
+
+ raf = new java.io.RandomAccessFile(fileName, "rws");
+ raf.write("Test".getBytes(), 0, 4);
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#close()
+ */
+ 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#getFD()
+ */
+ 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("Returned invalid fd", raf.getFD().valid());
+
+ raf.close();
+ assertFalse("Returned valid fd after close", raf.getFD().valid());
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#getFilePointer()
+ */
+ public void test_getFilePointer() throws IOException {
+ // Test for method long java.io.RandomAccessFile.getFilePointer()
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.write(fileString.getBytes(), 0, 1000);
+ assertEquals("Incorrect filePointer returned", 1000, raf
+ .getFilePointer());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#length()
+ */
+ public void test_length() throws IOException {
+ // Test for method long java.io.RandomAccessFile.length()
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.write(fileString.getBytes());
+ assertEquals("Incorrect length returned", fileString.length(), raf
+ .length());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#read()
+ */
+ public void test_read() throws IOException {
+ // Test for method int java.io.RandomAccessFile.read()
+ FileOutputStream fos = new java.io.FileOutputStream(fileName);
+ fos.write(fileString.getBytes("UTF-8"), 0, fileString.length());
+ fos.close();
+
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r");
+ assertEquals("Incorrect bytes returned from read",
+ fileString.charAt(0), raf.read());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#read(byte[])
+ */
+ public void test_read$B() throws IOException {
+ // Test for method int java.io.RandomAccessFile.read(byte [])
+ FileOutputStream fos = new java.io.FileOutputStream(fileName);
+ fos.write(fileString.getBytes(), 0, fileString.length());
+ fos.close();
+
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r");
+ byte[] rbuf = new byte[4000];
+ raf.read(rbuf);
+ assertEquals("Incorrect bytes returned from read", fileString,
+ new String(rbuf, 0, fileString.length()));
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#read(byte[], int, int)
+ */
+ public void test_read$BII() throws IOException {
+ // Test for method int java.io.RandomAccessFile.read(byte [], int, int)
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ byte[] rbuf = new byte[4000];
+ FileOutputStream fos = new java.io.FileOutputStream(fileName);
+ fos.write(fileString.getBytes(), 0, fileString.length());
+ fos.close();
+ raf.read(rbuf, 0, fileString.length());
+ assertEquals("Incorrect bytes returned from read", fileString,
+ new String(rbuf, 0, fileString.length()));
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#readBoolean()
+ */
+ public void test_readBoolean() throws IOException {
+ // Test for method boolean java.io.RandomAccessFile.readBoolean()
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeBoolean(true);
+ raf.seek(0);
+ assertTrue("Incorrect boolean read/written", raf.readBoolean());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#readByte()
+ */
+ public void test_readByte() throws IOException {
+ // Test for method byte java.io.RandomAccessFile.readByte()
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeByte(127);
+ raf.seek(0);
+ assertEquals("Incorrect bytes read/written", 127, raf.readByte());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#readChar()
+ */
+ public void test_readChar() throws IOException {
+ // Test for method char java.io.RandomAccessFile.readChar()
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeChar('T');
+ raf.seek(0);
+ assertEquals("Incorrect char read/written", 'T', raf.readChar());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#readDouble()
+ */
+ public void test_readDouble() throws IOException {
+ // Test for method double java.io.RandomAccessFile.readDouble()
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeDouble(Double.MAX_VALUE);
+ raf.seek(0);
+ assertEquals("Incorrect double read/written", Double.MAX_VALUE, raf
+ .readDouble(), 0);
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#readFloat()
+ */
+ public void test_readFloat() throws IOException {
+ // Test for method float java.io.RandomAccessFile.readFloat()
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeFloat(Float.MAX_VALUE);
+ raf.seek(0);
+ assertEquals("Incorrect float read/written", Float.MAX_VALUE, raf
+ .readFloat(), 0);
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#readFully(byte[])
+ */
+ public void test_readFully$B() throws IOException {
+ // Test for method void java.io.RandomAccessFile.readFully(byte [])
+ byte[] buf = new byte[10];
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeBytes("HelloWorld");
+ raf.seek(0);
+ raf.readFully(buf);
+ assertEquals("Incorrect bytes read/written", "HelloWorld", new String(
+ buf, 0, 10, "UTF-8"));
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#readFully(byte[], int, int)
+ */
+ public void test_readFully$BII() throws IOException {
+ // Test for method void java.io.RandomAccessFile.readFully(byte [], int,
+ // int)
+ byte[] buf = new byte[10];
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeBytes("HelloWorld");
+ raf.seek(0);
+ raf.readFully(buf, 0, buf.length);
+ assertEquals("Incorrect bytes read/written", "HelloWorld", new String(
+ buf, 0, 10, "UTF-8"));
+ try {
+ raf.readFully(buf, 0, buf.length);
+ fail("Reading past end of buffer did not throw EOFException");
+ } catch (EOFException e) {}
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#readInt()
+ */
+ public void test_readInt() throws IOException {
+ // Test for method int java.io.RandomAccessFile.readInt()
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeInt(Integer.MIN_VALUE);
+ raf.seek(0);
+ assertEquals("Incorrect int read/written", Integer.MIN_VALUE, raf
+ .readInt());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#readLine()
+ */
+ 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("UTF-8"), 0, s.length());
+ raf.seek(0);
+
+ assertEquals("Goodbye", raf.readLine());
+ assertEquals("Cruel", raf.readLine());
+ assertEquals("World", raf.readLine());
+
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#readLong()
+ */
+ public void test_readLong() throws IOException {
+ // Test for method long java.io.RandomAccessFile.readLong()
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeLong(Long.MAX_VALUE);
+ raf.seek(0);
+ assertEquals("Incorrect long read/written", Long.MAX_VALUE, raf
+ .readLong());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#readShort()
+ */
+ public void test_readShort() throws IOException {
+ // Test for method short java.io.RandomAccessFile.readShort()
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeShort(Short.MIN_VALUE);
+ raf.seek(0);
+ assertEquals("Incorrect long read/written", Short.MIN_VALUE, raf
+ .readShort());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#readUnsignedByte()
+ */
+ public void test_readUnsignedByte() throws IOException {
+ // Test for method int java.io.RandomAccessFile.readUnsignedByte()
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeByte(-1);
+ raf.seek(0);
+ assertEquals("Incorrect byte read/written", 255, raf.readUnsignedByte());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#readUnsignedShort()
+ */
+ public void test_readUnsignedShort() throws IOException {
+ // Test for method int java.io.RandomAccessFile.readUnsignedShort()
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeShort(-1);
+ raf.seek(0);
+ assertEquals("Incorrect byte read/written", 65535, raf
+ .readUnsignedShort());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#readUTF()
+ */
+ public void test_readUTF() throws IOException {
+ // Test for method java.lang.String java.io.RandomAccessFile.readUTF()
+
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeUTF(unihw);
+ raf.seek(0);
+ assertEquals("Incorrect utf string read", unihw, raf.readUTF());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#seek(long)
+ */
+ public void test_seekJ() throws IOException {
+ // Test for method void java.io.RandomAccessFile.seek(long)
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.write(fileString.getBytes(), 0, fileString.length());
+ raf.seek(12);
+ assertEquals("Seek failed to set filePointer", 12, raf.getFilePointer());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#skipBytes(int)
+ */
+ public void test_skipBytesI() throws IOException {
+ // Test for method int java.io.RandomAccessFile.skipBytes(int)
+ byte[] buf = new byte[5];
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeBytes("HelloWorld");
+ raf.seek(0);
+ raf.skipBytes(5);
+ raf.readFully(buf);
+ assertEquals("Failed to skip bytes", "World", new String(buf, 0, 5, "UTF-8"));
+ raf.close();
}
+
+ /**
+ * @tests java.io.RandomAccessFile#write(byte[])
+ */
+ public void test_write$B() throws IOException {
+ // Test for method void java.io.RandomAccessFile.write(byte [])
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+
+ byte[] nullByteArray = null;
+ try {
+ raf.write(nullByteArray);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ //expected
+ }
+
+ byte[] rbuf = new byte[4000];
+ raf.write(fileString.getBytes());
+ raf.close();
+
+ try {
+ raf.write(nullByteArray);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ //expected
+ }
+
+ //will not throw IOException if array's length is 0
+ raf.write(new byte[0]);
+
+ try {
+ raf.write(fileString.getBytes());
+ fail("should throw IOException");
+ } catch (IOException e) {
+ //expected
+ }
+
+ FileInputStream fis = new java.io.FileInputStream(fileName);
+ fis.read(rbuf, 0, fileString.length());
+ assertEquals("Incorrect bytes written", fileString, new String(rbuf, 0,
+ fileString.length()));
+ fis.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#write(byte[], int, int)
+ */
+ public void test_write$BII() throws IOException {
+ // Test for method void java.io.RandomAccessFile.write(byte [], int,
+ // int)
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ byte[] rbuf = new byte[4000];
+ raf.write(fileString.getBytes(), 0, fileString.length());
+ raf.close();
+ FileInputStream fis = new java.io.FileInputStream(fileName);
+ fis.read(rbuf, 0, fileString.length());
+ assertEquals("Incorrect bytes written", fileString, new String(rbuf, 0,
+ fileString.length()));
+ fis.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#write(byte[], int, int)
+ */
+ public void test_write_$BII_Exception() throws IOException {
+ raf = new java.io.RandomAccessFile(f, "rw");
+ byte[] nullByteArray = null;
+ byte[] byteArray = new byte[10];
+
+ try {
+ raf.write(nullByteArray, -1, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ raf.write(nullByteArray, 0, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ raf.write(nullByteArray, 1, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ raf.write(nullByteArray, 1, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ raf.write(nullByteArray, 1, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ raf.write(byteArray, -1, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ raf.write(byteArray, -1, 0);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ raf.write(byteArray, -1, 1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ raf.write(byteArray, 0, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ raf.write(byteArray, 0, 0);
+ raf.write(byteArray, 0, byteArray.length);
+ raf.write(byteArray, 1, 0);
+ raf.write(byteArray, byteArray.length, 0);
+
+ try {
+ raf.write(byteArray, byteArray.length + 1, 0);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+
+ try {
+ raf.write(byteArray, byteArray.length + 1, 1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+
+ raf.close();
+
+ try {
+ raf.write(nullByteArray, -1, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ raf.write(byteArray, -1, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ raf.write(byteArray, 0, 1);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ //expected
+ }
+
+ try {
+ raf.write(byteArray, 0, byteArray.length);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ //expected
+ }
+
+ try {
+ raf.write(byteArray, 1, 1);
+ fail("should throw IOException");
+ } catch (IOException e) {
+ //expected
+ }
+
+ try {
+ raf.write(byteArray, byteArray.length + 1, 0);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+
+ // will not throw IOException if count = 0
+ raf.write(byteArray, 0, 0);
+ raf.write(byteArray, byteArray.length, 0);
+ }
+
+
+ /**
+ * @tests java.io.RandomAccessFile#write(int)
+ */
+ public void test_writeI() throws IOException {
+ // Test for method void java.io.RandomAccessFile.write(int)
+ byte[] rbuf = new byte[4000];
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.write('t');
+ raf.close();
+ FileInputStream fis = new java.io.FileInputStream(fileName);
+ fis.read(rbuf, 0, 1);
+ assertEquals("Incorrect byte written", 't', rbuf[0]);
+ fis.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#writeBoolean(boolean)
+ */
+ public void test_writeBooleanZ() throws IOException {
+ // Test for method void java.io.RandomAccessFile.writeBoolean(boolean)
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeBoolean(true);
+ raf.seek(0);
+ assertTrue("Incorrect boolean read/written", raf.readBoolean());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#writeByte(int)
+ */
+ public void test_writeByteI() throws IOException {
+ // Test for method void java.io.RandomAccessFile.writeByte(int)
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeByte(127);
+ raf.seek(0);
+ assertEquals("Incorrect byte read/written", 127, raf.readByte());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#writeBytes(java.lang.String)
+ */
+ public void test_writeBytesLjava_lang_String() throws IOException {
+ // Test for method void
+ // java.io.RandomAccessFile.writeBytes(java.lang.String)
+ byte[] buf = new byte[10];
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeBytes("HelloWorld");
+ raf.seek(0);
+ raf.readFully(buf);
+ assertEquals("Incorrect bytes read/written", "HelloWorld", new String(
+ buf, 0, 10, "UTF-8"));
+ raf.close();
+
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#writeChar(int)
+ */
+ public void test_writeCharI() throws IOException {
+ // Test for method void java.io.RandomAccessFile.writeChar(int)
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeChar('T');
+ raf.seek(0);
+ assertEquals("Incorrect char read/written", 'T', raf.readChar());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#writeChars(java.lang.String)
+ */
+ public void test_writeCharsLjava_lang_String() throws IOException {
+ // Test for method void
+ // java.io.RandomAccessFile.writeChars(java.lang.String)
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeChars("HelloWorld");
+ char[] hchars = new char[10];
+ "HelloWorld".getChars(0, 10, hchars, 0);
+ raf.seek(0);
+ for (int i = 0; i < hchars.length; i++)
+ assertEquals("Incorrect string written", hchars[i], raf.readChar());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#writeDouble(double)
+ */
+ public void test_writeDoubleD() throws IOException {
+ // Test for method void java.io.RandomAccessFile.writeDouble(double)
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeDouble(Double.MAX_VALUE);
+ raf.seek(0);
+ assertEquals("Incorrect double read/written", Double.MAX_VALUE, raf
+ .readDouble(), 0);
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#writeFloat(float)
+ */
+ public void test_writeFloatF() throws IOException {
+ // Test for method void java.io.RandomAccessFile.writeFloat(float)
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeFloat(Float.MAX_VALUE);
+ raf.seek(0);
+ assertEquals("Incorrect float read/written", Float.MAX_VALUE, raf
+ .readFloat(), 0);
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#writeInt(int)
+ */
+ public void test_writeIntI() throws IOException {
+ // Test for method void java.io.RandomAccessFile.writeInt(int)
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeInt(Integer.MIN_VALUE);
+ raf.seek(0);
+ assertEquals("Incorrect int read/written", Integer.MIN_VALUE, raf
+ .readInt());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#writeLong(long)
+ */
+ public void test_writeLongJ() throws IOException {
+ // Test for method void java.io.RandomAccessFile.writeLong(long)
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeLong(Long.MAX_VALUE);
+ raf.seek(0);
+ assertEquals("Incorrect long read/written", Long.MAX_VALUE, raf
+ .readLong());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#writeShort(int)
+ */
+ public void test_writeShortI() throws IOException {
+ // Test for method void java.io.RandomAccessFile.writeShort(int)
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeShort(Short.MIN_VALUE);
+ raf.seek(0);
+ assertEquals("Incorrect long read/written", Short.MIN_VALUE, raf
+ .readShort());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#writeUTF(java.lang.String)
+ */
+ public void test_writeUTFLjava_lang_String() throws IOException {
+ // Test for method void
+ // java.io.RandomAccessFile.writeUTF(java.lang.String)
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ raf.writeUTF(unihw);
+ raf.seek(0);
+ assertEquals("Incorrect utf string", unihw, raf.readUTF());
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#seek(long)
+ *
+ * Regression for HARMONY-374
+ */
+ public void test_seekI() throws IOException {
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ try {
+ raf.seek(-1);
+ fail("IOException must be thrown if pos < 0");
+ } catch (IOException e) {
+ }
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#read(byte[], int, int)
+ *
+ * Regression for HARMONY-377
+ */
+ public void test_readBII() throws IOException {
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ try {
+ raf.read(new byte[1], -1, 1);
+ fail("IndexOutOfBoundsException must be thrown if off <0");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ raf.read(new byte[1], 0, -1);
+ fail("IndexOutOfBoundsException must be thrown if len <0");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ raf.read(new byte[1], 0, 5);
+ fail("IndexOutOfBoundsException must be thrown if off+len > b.length");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ raf.read(new byte[10], Integer.MAX_VALUE, 5);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ raf.read(new byte[10], 5, Integer.MAX_VALUE);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#read(byte[],int,int)
+ */
+ public void test_read_$BII_IndexOutOfBoundsException() throws IOException {
+ FileOutputStream fos = new java.io.FileOutputStream(fileName);
+ fos.write(fileString.getBytes(), 0, fileString.length());
+ fos.close();
+
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r");
+ byte[] rbuf = new byte[100];
+ raf.close();
+ try {
+ raf.read(rbuf,-1,0);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#read(byte[],int,int)
+ */
+ public void test_read_$BII_IOException() throws IOException {
+ FileOutputStream fos = new java.io.FileOutputStream(fileName);
+ fos.write(fileString.getBytes(), 0, fileString.length());
+ fos.close();
+
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r");
+ byte[] rbuf = new byte[100];
+ raf.close();
+ int read = raf.read(rbuf,0,0);
+ assertEquals(0,read);
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#read(byte[])
+ */
+ public void test_read_$B_IOException() throws IOException {
+ FileOutputStream fos = new java.io.FileOutputStream(fileName);
+ fos.write(fileString.getBytes(), 0, fileString.length());
+ fos.close();
+
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r");
+ byte[] rbuf = new byte[0];
+ raf.close();
+ int read = raf.read(rbuf);
+ assertEquals(0,read);
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#read(byte[],int,int)
+ */
+ public void test_read_$BII_NullPointerException() throws IOException {
+ File f = File.createTempFile("tmp", "tmp");
+ f.deleteOnExit();
+ RandomAccessFile raf = new RandomAccessFile(f, "r");
+ byte[] rbuf = null;
+ try {
+ raf.read(rbuf, 0, -1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ raf.close();
+ }
+
+ /**
+ * @tests java.io.RandomAccessFile#write(byte[], int, int)
+ *
+ * Regression for HARMONY-377
+ */
+ public void test_writeBII() throws IOException {
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw");
+ try {
+ raf.write(new byte[1], -1, 1);
+ fail("IndexOutOfBoundsException must be thrown if off <0");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ raf.write(new byte[1], 0, -1);
+ fail("IndexOutOfBoundsException must be thrown if len <0");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ raf.write(new byte[1], 0, 5);
+ fail("IndexOutOfBoundsException must be thrown if off+len > b.length");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ raf.write(new byte[10], Integer.MAX_VALUE, 5);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ }
+
+ try {
+ raf.write(new byte[10], 5, Integer.MAX_VALUE);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ raf.close();
+ }
+
+ /**
+ * Regression for HARMONY-69
+ */
+ public void testRandomAccessFile_String_String() throws IOException {
+ f.createNewFile();
+ RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "r");
+ FileChannel fcr = raf.getChannel();
+
+ try {
+ fcr.lock(0L, Long.MAX_VALUE, false);
+ fail("NonWritableChannelException expected!");
+ } catch (NonWritableChannelException e) {}
+ raf.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();
+ 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();
+ }
+
}
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
index 5bad541..da3185e 100644
--- 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
@@ -4,67 +4,78 @@
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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));
+ /**
+ * @tests java.io.Writer#append(char)
+ */
+ 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();
}
-
- @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));
+
+ /**
+ * @tests java.io.Writer#append(CharSequence)
+ */
+ 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();
+
}
- class MockWriter extends Writer {
+ /**
+ * @tests java.io.Writer#append(CharSequence, int, int)
+ */
+ 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();
+
+ }
+
+
+
+ /**
+ * @tests java.io.Writer#write(String)
+ */
+ public void test_writeLjava_lang_String() throws IOException {
+ // Regression for HARMONY-51
+ Object lock = new Object();
+ Writer wr = new MockLockWriter(lock);
+ wr.write("Some string");
+ wr.close();
+ }
+
+ class MockLockWriter extends Writer {
final Object myLock;
- MockWriter() {
- super();
- myLock = this;
- }
-
- MockWriter(Object lock) {
+ MockLockWriter(Object lock) {
super(lock);
myLock = lock;
}
@@ -83,9 +94,55 @@ public class WriterTest extends TestCase {
public void write(char[] arg0, int arg1, int arg2) throws IOException {
assertTrue(Thread.holdsLock(myLock));
}
+ }
- public boolean lockSet(Object o) {
- return (lock == o);
+
+ 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/org/apache/harmony/luni/tests/java/lang/AbstractMethodErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/AbstractMethodErrorTest.java
index c3679f1..2166716 100644
--- 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
@@ -1,51 +1,62 @@
/*
- * Copyright (C) 2007 The Android Open Source Project
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
- * 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
*
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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());
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class AbstractMethodErrorTest extends junit.framework.TestCase {
+
+ /**
+ * @tests {@link java.lang.AbstractMethodError#AbstractMethodError()}
+ */
+ public void test_Constructor() {
+ // Test for method java.lang.AbstractMethodError()
+ Error error = new AbstractMethodError();
+ assertNull(error.getCause());
+ assertNull(error.getMessage());
+ }
+
+ /**
+ * @tests {@link java.lang.AbstractMethodError#AbstractMethodError(String)}
+ */
+ public void test_ConstructorLjava_lang_String() {
+ // Test for method java.lang.AbstractMethodError(java.lang.String)
+ Error error = new AbstractMethodError(null);
+ assertNull(error.getMessage());
+ assertNull(error.getCause());
+
+ error = new AbstractMethodError("msg");
+ assertEquals("msg", error.getMessage());
+ assertNull(error.getCause());
}
- @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());
+ /**
+ * @tests serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+ SerializationTest.verifySelf(new AbstractMethodError());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+ SerializationTest.verifyGolden(this, new AbstractMethodError());
}
+
}
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
index 438e560..d6fb8ab 100644
--- 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
@@ -30,7 +30,7 @@ public class AllTests {
}
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.lang");
+ TestSuite suite = new TestSuite("Tests for java.lang");
suite.addTestSuite(AbstractMethodErrorTest.class);
suite.addTestSuite(ArithmeticExceptionTest.class);
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
index bce6f5d..f99be20 100644
--- 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
@@ -17,25 +17,13 @@
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());
@@ -45,12 +33,6 @@ public class ArithmeticExceptionTest extends TestCase {
/**
* @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());
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
index 3117e49..c7537c0 100644
--- 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
@@ -17,25 +17,13 @@
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());
@@ -47,12 +35,6 @@ public class ArrayIndexOutOfBoundsExceptionTest extends TestCase {
/**
* @tests java.lang.ArrayIndexOutOfBoundsException#ArrayIndexOutOfBoundsException()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ArrayIndexOutOfBoundsException",
- args = {}
- )
public void test_Constructor() {
ArrayIndexOutOfBoundsException e = new ArrayIndexOutOfBoundsException();
assertNull(e.getMessage());
@@ -62,12 +44,6 @@ public class ArrayIndexOutOfBoundsExceptionTest extends TestCase {
/**
* @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());
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
index d2345cb..c8979d0 100644
--- 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
@@ -17,25 +17,13 @@
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());
@@ -46,12 +34,6 @@ public class ArrayStoreExceptionTest extends TestCase {
/**
* @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());
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
index ec0d40f..e5a51cc 100644
--- 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
@@ -17,33 +17,16 @@
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);
@@ -55,67 +38,37 @@ public class AssertionErrorTest extends TestCase {
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());
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
index 23f9575..4c7c3e4 100644
--- 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
@@ -16,25 +16,13 @@
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());
@@ -43,12 +31,6 @@ public class BooleanTest extends TestCase {
/**
* @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"));
@@ -61,12 +43,6 @@ public class BooleanTest extends TestCase {
/**
* @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));
@@ -75,12 +51,6 @@ public class BooleanTest extends TestCase {
/**
* @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());
@@ -89,12 +59,6 @@ public class BooleanTest extends TestCase {
/**
* @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)));
@@ -108,12 +72,6 @@ public class BooleanTest extends TestCase {
/**
* @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()));
@@ -128,12 +86,6 @@ public class BooleanTest extends TestCase {
/**
* @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());
@@ -142,12 +94,6 @@ public class BooleanTest extends TestCase {
/**
* @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));
@@ -156,12 +102,6 @@ public class BooleanTest extends TestCase {
/**
* @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"));
@@ -182,12 +122,6 @@ public class BooleanTest extends TestCase {
/**
* @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));
@@ -196,12 +130,6 @@ public class BooleanTest extends TestCase {
/**
* @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"));
@@ -214,12 +142,6 @@ public class BooleanTest extends TestCase {
/**
* @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);
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
index d99223a..c1317cc 100644
--- 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
@@ -16,25 +16,13 @@
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));
@@ -51,12 +39,6 @@ public class ByteTest extends TestCase {
/**
* @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());
@@ -67,12 +49,6 @@ public class ByteTest extends TestCase {
/**
* @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"));
@@ -106,12 +82,6 @@ public class ByteTest extends TestCase {
/**
* @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());
@@ -122,13 +92,7 @@ public class ByteTest extends TestCase {
/**
* @tests java.lang.Byte#byteValue()
*/
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "byteValue",
- args = {}
- )
- public void test_byteValue1() {
+ public void test_booleanValue() {
assertEquals(1, new Byte((byte) 1).byteValue());
assertEquals(2, new Byte((byte) 2).byteValue());
assertEquals(0, new Byte((byte) 0).byteValue());
@@ -138,12 +102,6 @@ public class ByteTest extends TestCase {
/**
* @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));
@@ -158,12 +116,6 @@ public class ByteTest extends TestCase {
/**
* @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());
@@ -174,12 +126,6 @@ public class ByteTest extends TestCase {
/**
* @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));
@@ -190,12 +136,6 @@ public class ByteTest extends TestCase {
/**
* @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"));
@@ -229,12 +169,6 @@ public class ByteTest extends TestCase {
/**
* @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));
@@ -272,12 +206,6 @@ public class ByteTest extends TestCase {
/**
* @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"));
@@ -311,12 +239,6 @@ public class ByteTest extends TestCase {
/**
* @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));
@@ -354,12 +276,6 @@ public class ByteTest extends TestCase {
/**
* @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"));
@@ -392,12 +308,6 @@ public class ByteTest extends TestCase {
/**
* @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);
@@ -407,12 +317,6 @@ public class ByteTest extends TestCase {
/**
* @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);
@@ -422,12 +326,6 @@ public class ByteTest extends TestCase {
/**
* @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());
@@ -437,12 +335,6 @@ public class ByteTest extends TestCase {
/**
* @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());
@@ -452,12 +344,6 @@ public class ByteTest extends TestCase {
/**
* @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());
@@ -467,12 +353,6 @@ public class ByteTest extends TestCase {
/**
* @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);
@@ -501,12 +381,6 @@ public class ByteTest extends TestCase {
/**
* @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)
@@ -517,12 +391,6 @@ public class ByteTest extends TestCase {
/**
* @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)
@@ -536,12 +404,6 @@ public class ByteTest extends TestCase {
/**
* @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",
@@ -551,12 +413,6 @@ public class ByteTest extends TestCase {
/**
* @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);
@@ -567,12 +423,6 @@ public class ByteTest extends TestCase {
/**
* @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)
@@ -633,12 +483,6 @@ public class ByteTest extends TestCase {
/**
* @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);
}
@@ -646,12 +490,6 @@ public class ByteTest extends TestCase {
/**
* @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);
@@ -664,12 +502,6 @@ public class ByteTest extends TestCase {
/**
* @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);
}
@@ -677,12 +509,6 @@ public class ByteTest extends TestCase {
/**
* @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());
@@ -691,12 +517,6 @@ public class ByteTest extends TestCase {
/**
* @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());
@@ -705,12 +525,6 @@ public class ByteTest extends TestCase {
/**
* @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());
@@ -719,12 +533,6 @@ public class ByteTest extends TestCase {
/**
* @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"));
@@ -754,12 +562,6 @@ public class ByteTest extends TestCase {
/**
* @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);
@@ -811,12 +613,6 @@ public class ByteTest extends TestCase {
/**
* @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());
}
@@ -824,12 +620,6 @@ public class ByteTest extends TestCase {
/**
* @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());
@@ -839,12 +629,6 @@ public class ByteTest extends TestCase {
/**
* @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));
@@ -854,12 +638,6 @@ public class ByteTest extends TestCase {
/**
* @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());
@@ -876,12 +654,6 @@ public class ByteTest extends TestCase {
/**
* @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());
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
index 9a10cc4..a81775e 100644
--- 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
@@ -16,23 +16,10 @@
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}
- )
public void test_valueOfC() {
// test the cache range
// BEGIN android-changed
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
index f99fb86..a44a31d 100644
--- 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
@@ -92,8 +92,4 @@ public class Character_SubsetTest extends TestCase {
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
index 0766f28..cd485f2 100644
--- 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
@@ -16,22 +16,10 @@
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));
@@ -270,12 +258,6 @@ public class Character_UnicodeBlockTest extends TestCase {
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));
@@ -578,12 +560,7 @@ public class Character_UnicodeBlockTest extends TestCase {
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);
@@ -591,12 +568,7 @@ public class Character_UnicodeBlockTest extends TestCase {
} 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"));
@@ -891,12 +863,6 @@ public class Character_UnicodeBlockTest extends TestCase {
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);
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
index 1e61f87..bc56cef 100644
--- 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
@@ -17,44 +17,26 @@
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() {
+ /**
+ * @tests java.lang.ClassCastException#ClassCastException()
+ */
+ 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() {
+ /**
+ * @tests java.lang.ClassCastException#ClassCastException(java.lang.String)
+ */
+ 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
index 7acf714..b062a8c 100644
--- 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
@@ -1,51 +1,39 @@
-/*
- * 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
- *
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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 junit.framework.TestCase; // android-changed
-@TestTargetClass(ClassCircularityError.class)
-public class ClassCircularityErrorTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ClassCircularityError",
- args = {}
- )
+public class ClassCircularityErrorTest extends TestCase { // android-changed
+ // Thrown when a circularity has been detected while initializing a class.
+ /**
+ * @tests java.lang.ClassCircularityError#ClassCircularityError()
+ */
public void test_ClassCircularityError() {
- ClassCircularityError cce = new ClassCircularityError();
- assertNull(cce.getMessage());
+ new ClassCircularityError();
}
-
- @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());
- }
+
+ /**
+ * @tests java.lang.ClassCircularityError#ClassCircularityError(java.lang.String)
+ */
+ public void test_ClassCircularityError_LString() {
+ ClassCircularityError e = new ClassCircularityError(
+ "Some Error message");
+ assertEquals("Wrong message", "Some Error message", e.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
index 0aeef9b..2fd9aac 100644
--- 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
@@ -1,51 +1,43 @@
-/*
- * 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
- *
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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; // android-changed
-import junit.framework.TestCase;
+public class ClassFormatErrorTest extends TestCase { // android-changed
+ /**
+ * Thrown when the Java Virtual Machine attempts to read a class file and
+ * determines that the file is malformed or otherwise cannot be interpreted
+ * as a class file.
+ */
-@TestTargetClass(ClassFormatError.class)
-public class ClassFormatErrorTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ClassFormatError",
- args = {}
- )
+ /**
+ * @tests java.lang.ClassFormatError#ClassFormatError()
+ */
public void test_ClassFormatError() {
- ClassFormatError cfe = new ClassFormatError();
- assertNull(cfe.getMessage());
+ new ClassFormatError();
+ }
+
+ /**
+ * @tests java.lang.ClassFormatError#ClassFormatError(java.lang.String)
+ */
+ public void test_ClassFormatError_LString() {
+ ClassFormatError e = new ClassFormatError("Some Error Message");
+ assertEquals("Wrong message", "Some Error Message", e.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
index 43a73ed..22f49bb 100644
--- 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
@@ -17,304 +17,41 @@
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 {
-
- private static final String SYSTEM_RESOURCE_PATH = "META-INF/MANIFEST.MF";
- public static volatile int flag;
+import java.security.SecurityPermission;
- @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}
- )
- @BrokenTest("Infinite loop in classloader. Actually a known failure.")
- 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 = {}
- )
- @KnownFailure("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 = getClass().getClassLoader();
- 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());
- }
- }
+import junit.framework.TestCase;
- @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 {
+public class ClassLoaderTest extends TestCase {
- 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());
- }
- */
- }
+ public static volatile int flag;
- @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 {
+ // Regression for HARMONY-765
+ DynamicPolicy plc = new DynamicPolicy();
+ Policy back = Policy.getPolicy();
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
+ Policy.setPolicy(plc);
+
+ Class<?> a = new Ldr().define();
+
+ Permission p = new SecurityPermission("abc");
+ assertFalse("impossible! misconfiguration?", a.getProtectionDomain().implies(p));
+
+ plc.pc = p.newPermissionCollection();
+ plc.pc.add(p);
+ assertTrue("default domain is not dynamic", a.getProtectionDomain().implies(p));
+ } finally {
+ Policy.setPolicy(back);
}
}
@@ -354,7 +91,8 @@ public class ClassLoaderTest extends TestCase {
0, 1, 0, 1, 0, 8, 0, 0, 0, 2,
0, 9 };
- protected Class findClass(String name) throws ClassNotFoundException {
+ @Override
+ protected Class<?> findClass(String name) throws ClassNotFoundException {
try {
while (flag != 2) {
synchronized (lock) {
@@ -366,21 +104,21 @@ public class ClassLoaderTest extends TestCase {
if (name.equals("TestClass")) {
numFindClassCalled++;
return defineClass(null, classData, 0, classData.length);
- } else {
- throw new ClassNotFoundException("Class " + name + " not found.");
}
+ throw new ClassNotFoundException("Class " + name + " not found.");
}
}
static class SyncLoadTestThread extends Thread {
volatile boolean started;
ClassLoader cl;
- Class cls;
+ Class<?> cls;
SyncLoadTestThread(ClassLoader cl) {
this.cl = cl;
}
+ @Override
public void run() {
try {
started = true;
@@ -397,14 +135,6 @@ public class ClassLoaderTest extends TestCase {
* 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("Defining classes not supported, unfortunately the test appears"
- + " to succeed, which is not true, so marking it broken.")
public void test_loadClass_concurrentLoad() throws Exception
{
Object lock = new Object();
@@ -430,109 +160,13 @@ public class ClassLoaderTest extends TestCase {
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() throws
- IllegalAccessException, InstantiationException,
- ClassNotFoundException {
- PackageClassLoader pcl = new PackageClassLoader(
- getClass().getClassLoader());
- String className = getClass().getPackage().getName() + ".A";
-
- Class<?> clazz = pcl.loadClass(className, false);
- assertEquals(className, clazz.getName());
- assertNotNull(clazz.newInstance());
-
- clazz = pcl.loadClass(className, true);
- assertEquals(className, clazz.getName());
- assertNotNull(clazz.newInstance());
-
- try {
- 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 = getClass().getClassLoader().getResource("hyts_Foo.c");
+ java.net.URL u = ClassLoader.getSystemClassLoader().getResource("hyts_Foo.c");
assertNotNull("Unable to find resource", u);
java.io.InputStream is = null;
try {
@@ -542,577 +176,61 @@ public class ClassLoaderTest extends TestCase {
} catch (java.io.IOException e) {
fail("IOException getting stream for resource : " + e.getMessage());
}
-
-
-
- assertNull(getClass().getClassLoader()
- .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 = getClass().getClassLoader()
- .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));
-
-
+ assertNotNull("Failed to find resource: hyts_Foo.c", (is = ClassLoader
+ .getSystemClassLoader().getResourceAsStream("hyts_Foo.c")));
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(SYSTEM_RESOURCE_PATH);
+ 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}
- )
- @AndroidOnly("The RI doesn't have a classes.dex as resource in the "
- + "core-tests.jar. Also on Android this file is the only one "
- + "that is sure to exist.")
- public void test_getSystemResourceLjava_lang_String() throws IOException {
+ public void test_getSystemResourceLjava_lang_String() {
+ // Test for method java.net.URL
// 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 = getClass().getClassLoader().getSystemResource(SYSTEM_RESOURCE_PATH);
- assertNotNull(String.format("Failed to find resource: %s", SYSTEM_RESOURCE_PATH), url);
- java.io.InputStream is = url.openStream();
-
- assertTrue("System resource not found", is.available() > 0);
- assertNull("Doesn't return null for unknown resource.",
- getClass().getClassLoader().getSystemResource("NotFound"));
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSystemResourceAsStream",
- args = {java.lang.String.class}
- )
- @AndroidOnly("The RI doesn't have a classes.dex as resource in the "
- + "core-tests.jar. Also on Android this file is the only one "
- + "that is sure to exist.")
- public void test_getSystemResourceAsStreamLjava_lang_String()
- throws IOException {
-
- //String classResource = getClass().getPackage().getName().replace(".", "/") + "/" +
- // getClass().getSimpleName() + ".class";
- //assertNotNull("Failed to find resource: " + classResource,
- // ClassLoader.getSystemResourceAsStream(classResource));
-
- java.io.InputStream is = getClass().getClassLoader()
- .getSystemResourceAsStream(SYSTEM_RESOURCE_PATH);
- assertNotNull(String.format("Failed to find resource: %s", SYSTEM_RESOURCE_PATH), is);
-
- assertTrue("System resource not found", is.available() > 0);
-
- assertNull(ClassLoader.getSystemResourceAsStream("NotFoundResource"));
+ assertNotNull("Failed to find resource: hyts_Foo.c", ClassLoader
+ .getSystemResource("hyts_Foo.c"));
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSystemResources",
- args = {java.lang.String.class}
- )
- @AndroidOnly("The RI doesn't have a classes.dex as resource in the "
- + "core-tests.jar. Also on Android this file is the only one "
- + "that is sure to exist.")
- public void test_getSystemResources() {
-
- String textResource = SYSTEM_RESOURCE_PATH;
-
- try {
- Enumeration<URL> urls = ClassLoader.getSystemResources(textResource);
- assertNotNull(urls);
- assertTrue(urls.nextElement().getPath().endsWith(textResource));
- while (urls.hasMoreElements()) {
- assertNotNull(urls.nextElement());
- }
- 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(
- getClass().getClassLoader());
-
- 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(
- getClass().getClassLoader());
-
- 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(getClass().getClassLoader());
- 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 = getClass().getClassLoader().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(getClass().getClassLoader()
- .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(
- getClass().getClassLoader());
-
- 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(
- getClass().getClassLoader());
- pcl.findClass(getClass().getPackage().getName() + ".A");
- fail("ClassNotFoundException was not thrown.");
- } catch(ClassNotFoundException cnfe) {
- //expected
- }
-
- try {
- PackageClassLoader pcl = new PackageClassLoader(
- getClass().getClassLoader());
- 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(
- getClass().getClassLoader());
- 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(
- getClass().getClassLoader()).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(
- getClass().getClassLoader()).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(
- getClass().getClassLoader());
-
- Class [] classes = { String.class, Integer.class, Object.class,
- Object[].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(
- getClass().getClassLoader());
-
- 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);
- }
+ //Regression Test for JIRA-2047
+ public void test_getResourceAsStream_withSharpChar() throws Exception {
+ InputStream in = this.getClass().getClassLoader().getResourceAsStream(
+ ClassTest.FILENAME);
+ assertNotNull(in);
+ in.close();
+ }
}
class DynamicPolicy extends Policy {
@@ -1138,127 +256,14 @@ class A {
}
class Ldr extends ClassLoader {
-
- /*
- * These bytes are the content of the file
- * /org/apache/harmony/luni/tests/java/lang/A.class
- */
- byte[] classBytes = new byte[] { -54, -2, -70, -66, 0, 0, 0, 49, 0, 16, 7,
- 0, 2, 1, 0, 41, 111, 114, 103, 47, 97, 112, 97, 99, 104, 101, 47,
- 104, 97, 114, 109, 111, 110, 121, 47, 108, 117, 110, 105, 47, 116,
- 101, 115, 116, 115, 47, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47,
- 65, 7, 0, 4, 1, 0, 16, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47,
- 79, 98, 106, 101, 99, 116, 1, 0, 6, 60, 105, 110, 105, 116, 62, 1,
- 0, 3, 40, 41, 86, 1, 0, 4, 67, 111, 100, 101, 10, 0, 3, 0, 9, 12, 0,
- 5, 0, 6, 1, 0, 15, 76, 105, 110, 101, 78, 117, 109, 98, 101, 114,
- 84, 97, 98, 108, 101, 1, 0, 18, 76, 111, 99, 97, 108, 86, 97, 114,
- 105, 97, 98, 108, 101, 84, 97, 98, 108, 101, 1, 0, 4, 116, 104, 105,
- 115, 1, 0, 43, 76, 111, 114, 103, 47, 97, 112, 97, 99, 104, 101, 47,
- 104, 97, 114, 109, 111, 110, 121, 47, 108, 117, 110, 105, 47, 116,
- 101, 115, 116, 115, 47, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47,
- 65, 59, 1, 0, 10, 83, 111, 117, 114, 99, 101, 70, 105, 108, 101, 1,
- 0, 20, 67, 108, 97, 115, 115, 76, 111, 97, 100, 101, 114, 84, 101,
- 115, 116, 46, 106, 97, 118, 97, 0, 32, 0, 1, 0, 3, 0, 0, 0, 0, 0, 1,
- 0, 0, 0, 5, 0, 6, 0, 1, 0, 7, 0, 0, 0, 47, 0, 1, 0, 1, 0, 0, 0, 5,
- 42, -73, 0, 8, -79, 0, 0, 0, 2, 0, 10, 0, 0, 0, 6, 0, 1, 0, 0, 4,
- -128, 0, 11, 0, 0, 0, 12, 0, 1, 0, 0, 0, 5, 0, 12, 0, 13, 0, 0, 0,
- 1, 0, 14, 0, 0, 0, 2, 0, 15 };
-
- 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 {
-
- if(len < 0) len = classBytes.length;
- Class<?> clazz = null;
- String className = "org.apache.harmony.luni.tests.java.lang.A";
- switch(testCase) {
- case TEST_CASE_DEFINE_0:
- clazz = defineClass(className, classBytes, 0, len);
- break;
- case TEST_CASE_DEFINE_1:
- clazz = defineClass(classBytes, 0, len);
- break;
- case TEST_CASE_DEFINE_2:
- clazz = defineClass(className, classBytes, 0, len,
- getClass().getProtectionDomain());
- break;
- case TEST_CASE_DEFINE_3:
- ByteBuffer bb = ByteBuffer.wrap(classBytes);
- clazz = defineClass(className,
- bb, getClass().getProtectionDomain());
- break;
- }
- return clazz;
+ public Class<?> define() throws Exception {
+ Package p = getClass().getPackage();
+ // Class loader paths use '/' character as separator
+ String path = p == null ? "" : p.getName().replace('.', '/') + '/';
+ InputStream is = getResourceAsStream(path + "A.class");
+ byte[] buf = new byte[512];
+ int len = is.read(buf);
+ return defineClass(buf, 0, len);
}
-
- public Class<?> define(int testCase) throws Exception {
- return define(-1, testCase);
- }
-
}
-
-class PackageClassLoader extends ClassLoader {
- public PackageClassLoader() {
- super();
- }
-
- public PackageClassLoader(ClassLoader parent) {
- super(parent);
- }
-
- 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
index b8051cc..3a26a79 100644
--- 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
@@ -17,114 +17,44 @@
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 junit.framework.TestCase;
-@TestTargetClass(ClassNotFoundException.class)
public class ClassNotFoundExceptionTest extends TestCase {
-
/**
- * @tests java.lang.ClassNotFoundException#ClassNotFoundException()
+ * Thrown when an application tries to load in a class through its string
+ * name using the forName method in class Class.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ClassNotFoundException",
- args = {}
- )
- public void test_Constructor() {
+
+ /**
+ * @tests java.lang.ClassNotFoundException#ClassNotFoundException()
+ */
+ 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() {
+ /**
+ * @tests java.lang.ClassNotFoundException#ClassNotFoundException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
ClassNotFoundException e = new ClassNotFoundException("fixture");
assertEquals("fixture", e.getMessage());
assertNull(e.getCause());
+ }
+
+ /**
+ * @tests java.lang.ClassNotFoundException#ClassNotFoundException(java.lang.String, java.lang.Throwable)
+ */
+ public void test_ClassNotFoundException_LString_LThrowable() {
+ IOException in = new IOException();
+ ClassNotFoundException e = new ClassNotFoundException("SomeMessage", in);
+ assertEquals("Wrong Exception", in, e.getException());
+ assertEquals("Wrong message", "SomeMessage", e.getMessage());
+ assertEquals("Wrong cause", in, 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/CloneNotSupportedExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/CloneNotSupportedExceptionTest.java
index 58e86fa..da66da9 100644
--- 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
@@ -17,44 +17,26 @@
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() {
+ /**
+ * @tests java.lang.CloneNotSupportedException#CloneNotSupportedException()
+ */
+ 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() {
+ /**
+ * @tests java.lang.CloneNotSupportedException#CloneNotSupportedException(java.lang.String)
+ */
+ 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
index 5c01a36..4793a42 100644
--- 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
@@ -17,117 +17,49 @@
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("");
- }
+ assertNull("Incorrect behavior.", Compiler.command(new Object()));
}
/**
* @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);
+ // 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);
}
/**
* @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.
+ // 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());
- }
+ Compiler.disable();
+ Compiler.compileClass(Compiler.class);
}
/**
* @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());
- }
+ Compiler.disable();
+ Compiler.enable();
+ Compiler.compileClass(Compiler.class);
}
}
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
index d91584b..2fea1b1 100644
--- 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
@@ -16,14 +16,8 @@
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 {
@@ -34,20 +28,7 @@ public class EnumConstantNotPresentExceptionTest extends TestCase {
* @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");
@@ -58,12 +39,6 @@ public class EnumConstantNotPresentExceptionTest extends TestCase {
/**
* @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());
@@ -72,12 +47,6 @@ public class EnumConstantNotPresentExceptionTest extends TestCase {
/**
* @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
index 94b495f..afe1146 100644
--- 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
@@ -16,9 +16,7 @@
package org.apache.harmony.luni.tests.java.lang;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
+import java.util.HashMap;
import junit.framework.TestCase;
@@ -26,9 +24,6 @@ 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 {
@@ -49,37 +44,18 @@ public class EnumTest extends TestCase {
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
+ enum MockCloneEnum {
+ ONE;
+
+ public void callClone() throws CloneNotSupportedException{
+ super.clone();
+ }
}
/**
* @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));
@@ -95,12 +71,6 @@ public class EnumTest extends TestCase {
/**
* @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));
@@ -112,12 +82,6 @@ public class EnumTest extends TestCase {
/**
* @tests java.lang.Enum#getDeclaringClass()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDeclaringClass",
- args = {}
- )
public void test_getDeclaringClass() {
assertEquals(Sample.class, moe.getDeclaringClass());
}
@@ -125,27 +89,13 @@ public class EnumTest extends TestCase {
/**
* @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());
}
@@ -153,12 +103,6 @@ public class EnumTest extends TestCase {
/**
* @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());
@@ -168,12 +112,6 @@ public class EnumTest extends TestCase {
/**
* @tests java.lang.Enum#toString()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
public void test_toString() {
assertTrue(moe.toString().equals("MOE"));
}
@@ -181,12 +119,6 @@ public class EnumTest extends TestCase {
/**
* @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"));
@@ -248,13 +180,6 @@ public class EnumTest extends TestCase {
/**
* @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);
@@ -265,31 +190,32 @@ public class EnumTest extends TestCase {
assertEquals(0, Empty.values().length);
}
+
+ /**
+ * @tests java.lang.Enum#clone()
+ */
+ public void test_clone() {
+ try {
+ MockCloneEnum.ONE.callClone();
+ fail("Should throw CloneNotSupprotedException");
+ } catch (CloneNotSupportedException e1) {
+ // expected
+ }
+
+ }
/**
* @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"));
+ "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.
@@ -315,18 +241,11 @@ public class EnumTest extends TestCase {
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
@@ -342,5 +261,4 @@ public class EnumTest extends TestCase {
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
index 03735c2..32db9b3 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.Error#Error()
+ */
public void test_Constructor() {
Error e = new Error();
assertNull(e.getMessage());
@@ -46,41 +34,9 @@ public class ErrorTest extends TestCase {
/**
* @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
index 6614090..83c6cd8 100644
--- 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
@@ -17,31 +17,11 @@
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 = {}
- )
- })
+ /**
+ * @tests java.lang.ExceptionInInitializerError#ExceptionInInitializerError()
+ */
public void test_Constructor() {
ExceptionInInitializerError e = new ExceptionInInitializerError();
assertNull(e.getMessage());
@@ -52,56 +32,22 @@ public class ExceptionInInitializerErrorTest extends junit.framework.TestCase {
/**
* @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");
+ /**
+ * @tests java.lang.ExceptionInInitializerExceptionInInitializerError#ExceptionInInitializerError(java.lang.Throwable)
+ */
+ 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
index 9057269..88cc2e4 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.Exception#Exception()
+ */
public void test_Constructor() {
Exception e = new Exception();
assertNull(e.getMessage());
@@ -46,42 +34,9 @@ public class ExceptionTest extends TestCase {
/**
* @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/IllegalAccessErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/IllegalAccessErrorTest.java
index caec351..5b032e1 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.IllegalAccessError#IllegalAccessError()
+ */
public void test_Constructor() {
IllegalAccessError e = new IllegalAccessError();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class IllegalAccessErrorTest extends TestCase {
/**
* @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());
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
index a14ae66..2a984cb 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.IllegalAccessException#IllegalAccessException()
+ */
public void test_Constructor() {
IllegalAccessException e = new IllegalAccessException();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class IllegalAccessExceptionTest extends TestCase {
/**
* @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());
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
index 3acc8e4..9acf54c 100644
--- 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
@@ -17,57 +17,51 @@
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();
+ /**
+ * @tests java.lang.IllegalArgumentException#IllegalArgumentException()
+ */
+ 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() {
+ /**
+ * @tests java.lang.IllegalArgumentException#IllegalArgumentException(java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_String() {
IllegalArgumentException e = new IllegalArgumentException("fixture");
assertEquals("fixture", e.getMessage());
assertNull(e.getCause());
+ }
+
+ /**
+ * @tests {@link java.lang.IllegalArgumentException#IllegalArgumentException(Throwable)}
+ */
+ public void test_ConstructorLjava_lang_Throwable() {
+ Throwable emptyThrowable = new Exception();
+ IllegalArgumentException emptyException = new IllegalArgumentException(emptyThrowable);
+ assertEquals(emptyThrowable.getClass().getName(), emptyException.getMessage());
+ assertEquals(emptyThrowable.getClass().getName(), emptyException.getLocalizedMessage());
+ assertEquals(emptyThrowable.getClass().getName(), emptyException.getCause().toString());
+
+ Throwable exception = new Exception("msg");
+ IllegalArgumentException e = new IllegalArgumentException(exception);
+ assertEquals(exception.getClass().getName() + ": " + "msg", e.getMessage());
+ assertEquals(exception.getClass().getName(), emptyException.getLocalizedMessage());
+ assertEquals(exception.getClass().getName(), emptyException.getCause().toString());
}
/**
* @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();
@@ -77,27 +71,9 @@ public class IllegalArgumentExceptionTest extends TestCase {
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());
}
@@ -105,12 +81,6 @@ public class IllegalArgumentExceptionTest extends TestCase {
/**
* @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
index adc155f..37ce9c3 100644
--- 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
@@ -17,25 +17,13 @@
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());
@@ -46,12 +34,6 @@ public class IllegalMonitorStateExceptionTest extends TestCase {
/**
* @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());
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
index 03acac6..2d55d6c 100644
--- 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
@@ -17,26 +17,15 @@
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 = {}
- )
+ /**
+ * @tests java.lang.IllegalStateException#IllegalStateException()
+ */
public void test_Constructor() {
IllegalStateException e = new IllegalStateException();
assertNull(e.getMessage());
@@ -47,60 +36,50 @@ public class IllegalStateExceptionTest extends TestCase {
/**
* @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());
}
+
+ /**
+ * @tests {@link java.land.IllegalStateException#IllIllegalStateException(java.lang.Throwable)}
+ */
+ public void test_ConstructorLjava_lang_Throwable() {
+ Throwable emptyThrowable = new Exception();
+ IllegalStateException emptyException = new IllegalStateException(emptyThrowable);
+ assertEquals(emptyThrowable.getClass().getName(), emptyException.getMessage());
+ assertEquals(emptyThrowable.getClass().getName(), emptyException.getLocalizedMessage());
+ assertEquals(emptyThrowable.getClass().getName(), emptyException.getCause().toString());
- @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());
+ Throwable throwable = new Exception("msg");
+ IllegalStateException exception = new IllegalStateException(throwable);
+ assertEquals(throwable.getClass().getName() + ": " + "msg", exception.getMessage());
+ assertEquals(throwable.getClass().getName(), emptyException.getLocalizedMessage());
+ assertEquals(throwable.getClass().getName(), emptyException.getCause().toString());
}
- @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 {@link java.land.IllegalStateException#IllIllegalStateException(java.lang.String, java.lang.Throwable)}
+ */
+ public void test_ConstructorLjava_lang_StringLjava_lang_Throwable() {
+ Throwable emptyThrowable = new Exception();
+ IllegalStateException emptyException = new IllegalStateException("msg", emptyThrowable);
+ assertEquals("msg", emptyException.getMessage());
+ assertEquals("msg", emptyException.getLocalizedMessage());
+ assertEquals(emptyThrowable.getClass().getName(), emptyException.getCause().toString());
+
+ Throwable throwable = new Exception("msg_exception");
+ IllegalStateException exception = new IllegalStateException("msg", throwable);
+ assertEquals("msg", exception.getMessage());
+ assertEquals("msg", exception.getLocalizedMessage());
+ assertEquals(throwable.getClass().getName() + ": " + throwable.getMessage(), exception
+ .getCause().toString());
}
-
+
/**
* @tests serialization/deserialization.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization.",
- method = "!SerializationSelf",
- args = {}
- )
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(new IllegalStateException());
@@ -109,12 +88,6 @@ public class IllegalStateExceptionTest extends TestCase {
/**
* @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
index 1b3a03d..475f6bb 100644
--- 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
@@ -17,25 +17,13 @@
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());
@@ -46,12 +34,6 @@ public class IllegalThreadStateExceptionTest extends TestCase {
/**
* @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());
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
index 7893b29..b6a8d6a 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.IncompatibleClassChangeError#IncompatibleClassChangeError()
+ */
public void test_Constructor() {
IncompatibleClassChangeError e = new IncompatibleClassChangeError();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class IncompatibleClassChangeErrorTest extends TestCase {
/**
* @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());
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
index d897e47..617c71c 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.IndexOutOfBoundsException#IndexOutOfBoundsException()
+ */
public void test_Constructor() {
IndexOutOfBoundsException e = new IndexOutOfBoundsException();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class IndexOutOfBoundsExceptionTest extends TestCase {
/**
* @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());
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
index 5601755..1d9722c 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.InstantiationError#InstantiationError()
+ */
public void test_Constructor() {
InstantiationError e = new InstantiationError();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class InstantiationErrorTest extends TestCase {
/**
* @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());
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
index febeee2..5f636d5 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.InstantiationException#InstantiationException()
+ */
public void test_Constructor() {
InstantiationException e = new InstantiationException();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class InstantiationExceptionTest extends TestCase {
/**
* @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());
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
index 4b93777..3ff4711 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.InternalError#InternalError()
+ */
public void test_Constructor() {
InternalError e = new InternalError();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class InternalErrorTest extends TestCase {
/**
* @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());
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
index 4faa301..96c85e6 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.InterruptedException#InterruptedException()
+ */
public void test_Constructor() {
InterruptedException e = new InterruptedException();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class InterruptedExceptionTest extends TestCase {
/**
* @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());
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
index c856705..9c1adcb 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.LinkageError#LinkageError()
+ */
public void test_Constructor() {
LinkageError e = new LinkageError();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class LinkageErrorTest extends TestCase {
/**
* @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());
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
index ef1c9a6..93b6dbd 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.NegativeArraySizeException#NegativeArraySizeException()
+ */
public void test_Constructor() {
NegativeArraySizeException e = new NegativeArraySizeException();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class NegativeArraySizeExceptionTest extends TestCase {
/**
* @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());
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
index 9c76a56..db7dced 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.NoClassDefFoundError#NoClassDefFoundError()
+ */
public void test_Constructor() {
NoClassDefFoundError e = new NoClassDefFoundError();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class NoClassDefFoundErrorTest extends TestCase {
/**
* @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());
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
index 0ca4f41..88889e5 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.NoSuchFieldError#NoSuchFieldError()
+ */
public void test_Constructor() {
NoSuchFieldError e = new NoSuchFieldError();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class NoSuchFieldErrorTest extends TestCase {
/**
* @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());
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
index 135fdb5..5902d86 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.NoSuchFieldException#NoSuchFieldException()
+ */
public void test_Constructor() {
NoSuchFieldException e = new NoSuchFieldException();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class NoSuchFieldExceptionTest extends TestCase {
/**
* @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());
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
index 5c8a462..b7e711b 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.NoSuchMethodError#NoSuchMethodError()
+ */
public void test_Constructor() {
NoSuchMethodError e = new NoSuchMethodError();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class NoSuchMethodErrorTest extends TestCase {
/**
* @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());
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
index 8e01984..68d46a2 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.NoSuchMethodException#NoSuchMethodException()
+ */
public void test_Constructor() {
NoSuchMethodException e = new NoSuchMethodException();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class NoSuchMethodExceptionTest extends TestCase {
/**
* @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());
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
index f1c870d..a3df668 100644
--- 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
@@ -16,25 +16,13 @@
*/
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 = {}
- )
+ /**
+ * @tests java.lang.NullPointerException#NullPointerException()
+ */
public void test_Constructor() {
NullPointerException e = new NullPointerException();
assertNull(e.getMessage());
@@ -45,12 +33,6 @@ public class NullPointerExceptionTest extends TestCase {
/**
* @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());
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
index 579b0b9..3cdf445 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.NumberFormatException#NumberFormatException()
+ */
public void test_Constructor() {
NumberFormatException e = new NumberFormatException();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class NumberFormatExceptionTest extends TestCase {
/**
* @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());
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
index d1caf92..5b7d7f7 100644
--- 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
@@ -17,108 +17,50 @@
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#byteValue()
+ */
+ 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());
+ /**
+ * @tests java.lang.Number#shortValue()
+ */
+ 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/OutOfMemoryErrorTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/OutOfMemoryErrorTest.java
index 4782f1e..a23789b 100644
--- 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
@@ -17,48 +17,30 @@
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();
+ /**
+ * @tests java.lang.OutOfMemoryError#OutOfMemoryError()
+ */
+ 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);
+ /**
+ * @tests java.lang.OutOfMemoryError#OutOfMemoryError(java.lang.String)
+ */
+ 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
index 283c1db..61dab9a 100644
--- 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
@@ -16,48 +16,27 @@
*/
package org.apache.harmony.luni.tests.java.lang;
-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 java.io.File;
+import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
-import java.lang.annotation.Annotation;
-
-import java.lang.annotation.Annotation;
-import tests.support.Support_ClassLoader;
import tests.support.resource.Support_Resources;
-@TestTargetClass(Package.class)
public class PackageTest extends junit.framework.TestCase {
private File resources;
private String resPath;
-
- Class clazz;
Package getTestPackage(String resourceJar, String className)
throws Exception {
-
- if ("Dalvik".equals(System.getProperty("java.vm.name"))) {
- resourceJar = resourceJar.substring(0, resourceJar.indexOf(".")) +
- "_dex.jar";
- }
Support_Resources.copyFile(resources, "Package", resourceJar);
URL resourceURL = new URL("file:/" + resPath + "/Package/"
+ resourceJar);
- ClassLoader cl = Support_ClassLoader.getInstance(resourceURL,
- getClass().getClassLoader());
-
- clazz = cl.loadClass(className);
- return clazz.getPackage();
+ URLClassLoader ucl = new URLClassLoader(new URL[] { resourceURL }, null);
+ return Class.forName(className, true, ucl).getPackage();
}
@Override
@@ -82,45 +61,6 @@ public class PackageTest extends junit.framework.TestCase {
* @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");
@@ -231,13 +171,6 @@ public class PackageTest extends junit.framework.TestCase {
/**
* @tests java.lang.Package#getName()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getName",
- args = {}
- )
- @BrokenTest("Different behavior between cts host and run-core-test")
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
@@ -247,34 +180,17 @@ public class PackageTest extends junit.framework.TestCase {
/**
* @tests java.lang.Package#getPackage(java.lang.String)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPackage",
- args = {java.lang.String.class}
- )
- @KnownFailure("Real package information missing on android.")
- public void test_getPackageLjava_lang_String() throws Exception {
+ public void test_getPackageLjava_lang_String() {
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;
@@ -290,12 +206,6 @@ public class PackageTest extends junit.framework.TestCase {
/**
* @tests java.lang.Package#hashCode()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
public void test_hashCode() {
Package p1 = Package.getPackage("java.lang");
if (p1 != null) {
@@ -306,13 +216,6 @@ public class PackageTest extends junit.framework.TestCase {
/**
* @tests java.lang.Package#isCompatibleWith(java.lang.String)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isCompatibleWith",
- args = {java.lang.String.class}
- )
- @KnownFailure("Dalvik packages are always version '0.0'.")
public void test_isCompatibleWithLjava_lang_String() throws Exception {
Package p = getTestPackage("hyts_c.jar", "p.C");
@@ -363,31 +266,14 @@ public class PackageTest extends junit.framework.TestCase {
/**
* @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
@@ -399,91 +285,106 @@ public class PackageTest extends junit.framework.TestCase {
/**
* @tests java.lang.Package#toString()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- @BrokenTest("Different behavior between cts host and run-core-test")
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));
+ public void test_SealedPackage_forName() throws Exception {
+ Support_Resources.copyFile(resources, "Package", "hyts_c.jar");
+ Support_Resources.copyFile(resources, "Package", "hyts_d.jar");
+ Support_Resources.copyFile(resources, "Package", "hyts_d1.jar");
+ Support_Resources.copyFile(resources, "Package", "hyts_d2.jar");
+
+ URL resourceURL1 = new URL("file:/" + resPath + "/Package/hyts_c.jar");
+ URL resourceURL2 = new URL("file:/" + resPath + "/Package/hyts_d.jar");
+ URL resourceURL3 = new URL("file:/" + resPath + "/Package/hyts_d1.jar");
+ URL resourceURL4 = new URL("file:/" + resPath + "/Package/hyts_d2.jar");
+ URL resourceURL5 = new URL("file:/" + resPath + "/");
+
+ URLClassLoader uclClassLoader;
+ // load from the sealed jar, then an unsealed jar with no manifest
+ uclClassLoader = new java.net.URLClassLoader(new URL[] { resourceURL1,
+ resourceURL2 }, null);
+ Class.forName("p.C", true, uclClassLoader);
+ try {
+ Class.forName("p.D", true, uclClassLoader);
+ fail("should throw SecurityException");
+ } catch (SecurityException e) {
+ // Expected
+ }
+
+ // setup for next test
+ Support_Resources.copyFile(resources, "p", "");
+ InputStream in = uclClassLoader.getResourceAsStream("p/D.class");
+ Support_Resources.copyLocalFileto(new File(resources.toString(),
+ "p/D.class"), in);
+
+ // load from a sealed jar, then the directory
+ uclClassLoader = new java.net.URLClassLoader(new URL[] { resourceURL1,
+ resourceURL5 }, null);
+ Class.forName("p.C", true, uclClassLoader);
+ try {
+ Class.forName("p.D", true, uclClassLoader);
+ fail("should throw SecurityException");
+ } catch (SecurityException e) {
+ // Expected
+ }
+
+ // load from a directory, then the sealed jar
+ uclClassLoader = new java.net.URLClassLoader(new URL[] { resourceURL1,
+ resourceURL5 }, null);
+ Class.forName("p.D", true, uclClassLoader);
+ try {
+ Class.forName("p.C", true, uclClassLoader);
+ fail("should throw SecurityException");
+ } catch (SecurityException e) {
+ // Expected
+ }
+
+ // load from an unsealed jar with no manifest, then the sealed jar
+ uclClassLoader = new java.net.URLClassLoader(new URL[] { resourceURL1,
+ resourceURL2 }, null);
+ Class.forName("p.D", true, uclClassLoader);
+ try {
+ Class.forName("p.C", true, uclClassLoader);
+ fail("should throw SecurityException");
+ } catch (SecurityException e) {
+ // Expected
+ }
+
+ // load from an unsealed jar with a manifest, then the sealed jar
+ uclClassLoader = new java.net.URLClassLoader(new URL[] { resourceURL1,
+ resourceURL3 }, null);
+ Class.forName("p.C", true, uclClassLoader);
+ try {
+ Class.forName("p.D", true, uclClassLoader);
+ fail("should throw SecurityException");
+ } catch (SecurityException e) {
+ // Expected
+ }
+
+ // load from an sealed jar, then the unsealed jar with a manifest
+ uclClassLoader = new java.net.URLClassLoader(new URL[] { resourceURL1,
+ resourceURL3 }, null);
+ Class.forName("p.D", true, uclClassLoader);
+ try {
+ Class.forName("p.C", true, uclClassLoader);
+ fail("should throw SecurityException");
+ } catch (SecurityException e) {
+ // Expected
+ }
+
+ // load from the sealed jar, then another sealed jar
+ uclClassLoader = new java.net.URLClassLoader(new URL[] { resourceURL1,
+ resourceURL4 }, null);
+ Class.forName("p.C", true, uclClassLoader);
+ try {
+ Class.forName("p.D", true, uclClassLoader);
+ fail("should throw SecurityException");
+ } catch (SecurityException e) {
+ // Expected
+ }
}
-
- @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/RuntimePermissionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/RuntimePermissionTest.java
index cc5145e..ebe3a40 100644
--- 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
@@ -17,46 +17,28 @@
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)
+ */
+ 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());
- }
+ /**
+ * @tests java.lang.RuntimePermission#RuntimePermission(java.lang.String,
+ * java.lang.String)
+ */
+ 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/SecurityExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/SecurityExceptionTest.java
index 407d6f9..94c7dc2 100644
--- 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
@@ -17,26 +17,15 @@
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 = {}
- )
+
+ /**
+ * @tests java.lang.SecurityException#SecurityException()
+ */
public void test_Constructor() {
SecurityException e = new SecurityException();
assertNull(e.getMessage());
@@ -47,12 +36,6 @@ public class SecurityExceptionTest extends TestCase {
/**
* @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());
@@ -62,12 +45,6 @@ public class SecurityExceptionTest extends TestCase {
/**
* @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();
@@ -79,12 +56,6 @@ public class SecurityExceptionTest extends TestCase {
/**
* @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();
@@ -95,12 +66,6 @@ public class SecurityExceptionTest extends TestCase {
/**
* @tests serialization/deserialization.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- )
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(new SecurityException());
@@ -109,12 +74,6 @@ public class SecurityExceptionTest extends TestCase {
/**
* @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
index 0bd0c1f..d8c3751 100644
--- 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
@@ -4,9 +4,9 @@
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -16,19 +16,10 @@
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 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;
@@ -36,20 +27,13 @@ import java.security.AllPermission;
import java.security.Permission;
import java.security.ProtectionDomain;
import java.security.Security;
-import java.security.SecurityPermission;
+
+import junit.framework.TestCase;
+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;
@@ -57,50 +41,9 @@ public class SecurityManagerTest extends TestCase {
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.");
@@ -149,12 +92,6 @@ public class SecurityManagerTest extends TestCase {
/**
* @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.");
@@ -203,17 +140,11 @@ public class SecurityManagerTest extends TestCase {
/**
* @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"));
+ mutableSM
+ .denyPermission(new RuntimePermission("accessDeclaredMembers"));
System.setSecurityManager(mutableSM);
try {
getClass().getDeclaredFields();
@@ -223,80 +154,37 @@ public class SecurityManagerTest extends TestCase {
fail("This should throw a SecurityException.");
} catch (SecurityException e) {
}
-
- try {
- delegateCallToCheckMemberAccess2(Object.class, Member.DECLARED);
- fail("SecurityException was not thrown.");
- } catch(SecurityException se) {
- //expected
- }
-
- try {
- delegateCallToCheckMemberAccess2(null, Member.PUBLIC);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
+
} finally {
System.setSecurityManager(null);
}
}
/**
- * Don't call checkMemberAccess directly, since we're checking our caller
- * (and not ourselves). This is necessary for unit tests, since JUnit's
- * TestCase is usually in the boot classpath for dalvik. This delegating
- * method corresponds to Class.getDeclared*();
- */
- private void delegateCallToCheckMemberAccess2(Class<Object> cls, int type) {
- delegateCallToCheckMemberAccess1(cls, type);
- }
-
- /**
- * This delegating method corresponds to Class.checkMemberAccess().
- */
- private void delegateCallToCheckMemberAccess1(Class<Object> cls, int type) {
- mutableSM.checkMemberAccess(cls, type);
- }
-
- /**
* @tests java.lang.SecurityManager#checkPermission(java.security.Permission)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "checkPermission",
- args = {java.security.Permission.class}
- )
+ /* BEGIN android-removed: we don't have Support_Exec.execJava.
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
+ 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);
}
+ */
private static class checkPermissionLjava_security_PermissionTesting {
public static void main(String[] args) {
@@ -310,12 +198,6 @@ public class SecurityManagerTest extends TestCase {
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);
}
@@ -325,259 +207,39 @@ public class SecurityManagerTest extends TestCase {
/**
* @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);
+ mutableSM.checkAccept("localhost", 1024);
+ fail("This should throw a SecurityException.");
+ } catch (SecurityException e) {
+ // expected
}
-
- 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
@@ -585,133 +247,20 @@ public class SecurityManagerTest extends TestCase {
mutableSM.denyPermission(new SocketPermission("localhost:1024-",
"accept, connect, listen"));
System.setSecurityManager(mutableSM);
+ ProtectionDomain pDomain = this.getClass().getProtectionDomain();
+ ProtectionDomain[] pd = { pDomain };
+ AccessControlContext acc = new AccessControlContext(pd);
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();
+ mutableSM.checkConnect("localhost", 1024, acc);
+ fail("This should throw a SecurityException.");
} 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);
+ // expected
}
}
/**
* @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
@@ -724,36 +273,16 @@ public class SecurityManagerTest extends TestCase {
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 {
@@ -761,20 +290,12 @@ public class SecurityManagerTest extends TestCase {
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
@@ -782,42 +303,20 @@ public class SecurityManagerTest extends TestCase {
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);
+ mutableSM.checkLink("harmony");
+ fail("This should throw a SecurityException.");
+ } catch (SecurityException e) {
+ // expected
}
}
/**
* @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);
@@ -844,22 +343,11 @@ public class SecurityManagerTest extends TestCase {
* @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);
@@ -868,73 +356,35 @@ public class SecurityManagerTest extends TestCase {
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);
+ // 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
}
}
/**
- *
+ *
* @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
@@ -951,43 +401,16 @@ public class SecurityManagerTest extends TestCase {
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 {
@@ -997,99 +420,14 @@ public class SecurityManagerTest extends TestCase {
// 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 {
@@ -1099,314 +437,47 @@ public class SecurityManagerTest extends TestCase {
// 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());
+ mutableSM.denyPermission(new FilePermission("<<ALL FILES>>", "read"));
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());
+ AccessControlContext acc = new AccessControlContext(pd);
System.setSecurityManager(mutableSM);
try {
- mutableSM.checkSecurityAccess("getPolicy");
+ mutableSM.checkRead("aa", acc);
+ fail("This should throw a SecurityException.");
} 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);
+ // expected
}
}
/**
* @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());
+ mutableSM.checkSetFactory();
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());
@@ -1417,12 +488,6 @@ public class SecurityManagerTest extends TestCase {
/**
* @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
@@ -1430,61 +495,16 @@ public class SecurityManagerTest extends TestCase {
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();
- }
+ mutableSM.checkRead("aa", mutableSM.getSecurityContext());
+ fail("This should throw a SecurityException.");
+ } catch (SecurityException e) {
+ // expected
}
- 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"));
@@ -1493,12 +513,6 @@ public class SecurityManagerTest extends TestCase {
/**
* @tests {@link java.lang.SecurityManager#classLoaderDepth()}
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "classLoaderDepth",
- args = {}
- )
public void test_classLoaderDepth() {
assertEquals(-1, mockSM.classLoaderDepth());
}
@@ -1506,12 +520,6 @@ public class SecurityManagerTest extends TestCase {
/**
* @tests {@link java.lang.SecurityManager#currentClassLoader()}
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "currentClassLoader",
- args = {}
- )
public void test_currentClassLoader() {
assertNull(mockSM.currentClassLoader());
}
@@ -1519,12 +527,6 @@ public class SecurityManagerTest extends TestCase {
/**
* @tests {@link java.lang.SecurityManager#currentLoadedClass()}
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "currentLoadedClass",
- args = {}
- )
public void test_currentLoadedClass() {
assertNull(mockSM.currentLoadedClass());
}
@@ -1532,12 +534,6 @@ public class SecurityManagerTest extends TestCase {
/**
* @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"));
@@ -1547,43 +543,60 @@ public class SecurityManagerTest extends TestCase {
/**
* @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()}
+ * @tests {@link java.lang.SecurityManager#inClassLoader()}
*/
- @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]);
- }
+ assertEquals("MockSecurityManager should be the first in the classes stack",
+ mockSM.getClassContext()[0], MockSecurityManager.class);
}
// set some protected method to public for testing
+ class MockSecurityManager extends SecurityManager {
+
+ 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 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();
+ }
+ }
@Override
protected void setUp() throws Exception {
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
index 34f9958..30c9ea7 100644
--- 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
@@ -16,14 +16,8 @@
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);
@@ -31,12 +25,6 @@ public class ShortTest extends TestCase {
/**
* @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)
@@ -48,12 +36,6 @@ public class ShortTest extends TestCase {
/**
* @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);
@@ -79,12 +61,6 @@ public class ShortTest extends TestCase {
/**
* @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)
@@ -153,12 +129,6 @@ public class ShortTest extends TestCase {
/**
* @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");
@@ -194,12 +164,6 @@ public class ShortTest extends TestCase {
/**
* @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)
@@ -293,12 +257,6 @@ public class ShortTest extends TestCase {
/**
* @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")
@@ -314,12 +272,6 @@ public class ShortTest extends TestCase {
/**
* @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)
@@ -333,12 +285,6 @@ public class ShortTest extends TestCase {
/**
* @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)
@@ -351,12 +297,6 @@ public class ShortTest extends TestCase {
/**
* @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)
@@ -400,37 +340,25 @@ public class ShortTest extends TestCase {
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#valueOf(byte)
+ */
+ 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());
@@ -441,12 +369,6 @@ public class ShortTest extends TestCase {
/**
* @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"));
@@ -476,12 +398,6 @@ public class ShortTest extends TestCase {
/**
* @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());
@@ -492,13 +408,7 @@ public class ShortTest extends TestCase {
/**
* @tests java.lang.Short#byteValue()
*/
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Doesn't check boundary values.",
- method = "byteValue",
- args = {}
- )
- public void test_byteValue1() {
+ public void test_booleanValue() {
assertEquals(1, new Short((short)1).byteValue());
assertEquals(2, new Short((short)2).byteValue());
assertEquals(0, new Short((short)0).byteValue());
@@ -508,12 +418,6 @@ public class ShortTest extends TestCase {
/**
* @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));
@@ -528,12 +432,6 @@ public class ShortTest extends TestCase {
/**
* @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());
@@ -544,12 +442,6 @@ public class ShortTest extends TestCase {
/**
* @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));
@@ -560,12 +452,6 @@ public class ShortTest extends TestCase {
/**
* @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"));
@@ -595,12 +481,6 @@ public class ShortTest extends TestCase {
/**
* @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));
@@ -634,12 +514,6 @@ public class ShortTest extends TestCase {
/**
* @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"));
@@ -669,12 +543,6 @@ public class ShortTest extends TestCase {
/**
* @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));
@@ -708,12 +576,6 @@ public class ShortTest extends TestCase {
/**
* @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"));
@@ -724,13 +586,6 @@ public class ShortTest extends TestCase {
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) {}
@@ -750,12 +605,6 @@ public class ShortTest extends TestCase {
/**
* @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);
@@ -765,12 +614,6 @@ public class ShortTest extends TestCase {
/**
* @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);
@@ -780,12 +623,6 @@ public class ShortTest extends TestCase {
/**
* @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());
@@ -795,12 +632,6 @@ public class ShortTest extends TestCase {
/**
* @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());
@@ -810,12 +641,6 @@ public class ShortTest extends TestCase {
/**
* @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());
@@ -825,12 +650,6 @@ public class ShortTest extends TestCase {
/**
* @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));
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
index 009349f..b4e928f 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.StackOverflowError#StackOverflowError()
+ */
public void test_Constructor() {
StackOverflowError e = new StackOverflowError();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class StackOverflowErrorTest extends TestCase {
/**
* @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());
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
index 79b87fc..1f5de93 100644
--- 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
@@ -16,30 +16,18 @@
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.Serializable;
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");
@@ -49,22 +37,81 @@ public class StringBufferTest extends TestCase {
} catch (IndexOutOfBoundsException e) {
// expected
}
+
+ assertEquals("abcde", buffer.toString());
+ buffer.setLength(1);
+ buffer.append('f');
+ assertEquals("af", buffer.toString());
+
+ buffer = new StringBuffer("abcde");
+ assertEquals("cde", buffer.substring(2));
+ buffer.setLength(3);
+ buffer.append('f');
+ assertEquals("abcf", buffer.toString());
+
+ buffer = new StringBuffer("abcde");
+ buffer.setLength(2);
+ try {
+ buffer.charAt(3);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ }
+
+ buffer = new StringBuffer();
+ buffer.append("abcdefg");
+ buffer.setLength(2);
+ buffer.setLength(5);
+ for (int i = 2; i < 5; i++) {
+ assertEquals(0, buffer.charAt(i));
+ }
+
+ buffer = new StringBuffer();
+ buffer.append("abcdefg");
+ buffer.delete(2, 4);
+ buffer.setLength(7);
+ assertEquals('a', buffer.charAt(0));
+ assertEquals('b', buffer.charAt(1));
+ assertEquals('e', buffer.charAt(2));
+ assertEquals('f', buffer.charAt(3));
+ assertEquals('g', buffer.charAt(4));
+ for (int i = 5; i < 7; i++) {
+ assertEquals(0, buffer.charAt(i));
+ }
+
+ buffer = new StringBuffer();
+ buffer.append("abcdefg");
+ buffer.replace(2, 5, "z");
+ buffer.setLength(7);
+ for (int i = 5; i < 7; i++) {
+ assertEquals(0, buffer.charAt(i));
+ }
}
-
+
+ /**
+ * @tests java.lang.StringBuffer#toString()
+ */
+ public void test_toString() throws Exception {
+ StringBuffer buffer = new StringBuffer();
+ assertEquals("", buffer.toString());
+
+ buffer.append("abcde");
+ assertEquals("abcde", buffer.toString());
+ buffer.setLength(1000);
+ byte[] bytes = buffer.toString().getBytes("GB18030");
+ for (int i = 5; i < bytes.length; i++) {
+ assertEquals(0, bytes[i]);
+ }
+
+ buffer.setLength(5);
+ buffer.append("fghij");
+ assertEquals("abcdefghij", buffer.toString());
+ }
+
/**
* @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.");
@@ -72,12 +119,7 @@ public class StringBufferTest extends TestCase {
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");
@@ -92,12 +134,6 @@ public class StringBufferTest extends TestCase {
/**
* @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"));
@@ -109,35 +145,10 @@ public class StringBufferTest extends TestCase {
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();
@@ -155,24 +166,11 @@ public class StringBufferTest extends TestCase {
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 {
@@ -186,12 +184,6 @@ public class StringBufferTest extends TestCase {
/**
* @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 {
@@ -205,12 +197,6 @@ public class StringBufferTest extends TestCase {
/**
* @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);
@@ -253,12 +239,6 @@ public class StringBufferTest extends TestCase {
/**
* @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";
@@ -341,12 +321,6 @@ public class StringBufferTest extends TestCase {
/**
* @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 {
@@ -360,12 +334,6 @@ public class StringBufferTest extends TestCase {
/**
* @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);
@@ -379,12 +347,6 @@ public class StringBufferTest extends TestCase {
/**
* @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));
@@ -420,12 +382,6 @@ public class StringBufferTest extends TestCase {
/**
* @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));
@@ -461,12 +417,6 @@ public class StringBufferTest extends TestCase {
/**
* @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));
@@ -502,41 +452,19 @@ public class StringBufferTest extends TestCase {
/**
* @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) {
+ fail("ArrayIndexOutOfBoundsException expected");
+ } catch (ArrayIndexOutOfBoundsException 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);
@@ -602,12 +530,6 @@ public class StringBufferTest extends TestCase {
/**
* @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";
@@ -638,12 +560,6 @@ public class StringBufferTest extends TestCase {
/**
* @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";
@@ -689,12 +605,6 @@ public class StringBufferTest extends TestCase {
/**
* @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"),
@@ -704,12 +614,6 @@ public class StringBufferTest extends TestCase {
/**
* @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"),
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
index 0243fdb..596453d 100644
--- 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
@@ -17,565 +17,412 @@
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 junit.framework.TestCase;
+
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")
+ /**
+ * @tests java.lang.StringBuilder.StringBuilder()
+ */
+ public void test_Constructor() {
+ StringBuilder sb = new StringBuilder();
+ assertNotNull(sb);
+ assertEquals(16, sb.capacity());
+ }
+
+ /**
+ * @tests java.lang.StringBuilder.StringBuilder(int)
+ */
+ 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)
+ */
+ @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")
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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[])
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ @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();
+ 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());
+ }
+
+ /**
+ * @tests java.lang.StringBuilder.append(double)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)'
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)'
+ */
+ 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() {
+ }
+
+ /**
+ * @tests java.lang.StringBuilder.capacity()'
+ */
+ 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)'
+ */
+ 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)
+ */
+ public void test_codePointAtI() {
StringBuilder sb = new StringBuilder("abc");
assertEquals('a', sb.codePointAt(0));
assertEquals('b', sb.codePointAt(1));
@@ -607,18 +454,12 @@ public class StringBuilderTest extends TestCase {
} catch (IndexOutOfBoundsException e) {
}
- }
+ }
- /**
- * @tests java.lang.StringBuilder.codePointBefore(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "codePointBefore",
- args = {int.class}
- )
- public void test_codePointBeforeI() {
+ /**
+ * @tests java.lang.StringBuilder.codePointBefore(int)
+ */
+ public void test_codePointBeforeI() {
StringBuilder sb = new StringBuilder("abc");
assertEquals('a', sb.codePointBefore(1));
assertEquals('b', sb.codePointBefore(2));
@@ -651,18 +492,12 @@ public class StringBuilderTest extends TestCase {
} 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() {
+ /**
+ * @tests java.lang.StringBuilder.codePointCount(int, int)
+ */
+ 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));
@@ -693,371 +528,326 @@ public class StringBuilderTest extends TestCase {
} 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.delete(int, int)
+ */
+ 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
+ }
+
+ // HARMONY 6212
+ sb = new StringBuilder();
+ sb.append("abcde");
+ String str = sb.toString();
+ sb.delete(0, sb.length());
+ sb.append("YY");
+ assertEquals("abcde", str);
+ assertEquals("YY", sb.toString());
+ }
+
+ /**
+ * @tests java.lang.StringBuilder.deleteCharAt(int)
+ */
+ 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)'
+ */
+ 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)'
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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 = "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 {
@@ -1069,668 +859,584 @@ public class StringBuilderTest extends TestCase {
}
/**
- * @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")
+ * @tests java.lang.StringBuilder.insert(int, char[])'
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ @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() {
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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()
+ */
+ 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)'
+ */
+ public void test_offsetByCodePointsII() {
int result = new StringBuilder("a\uD800\uDC00b").offsetByCodePoints(0, 2);
assertEquals(3, result);
@@ -1791,87 +1497,102 @@ public class StringBuilderTest extends TestCase {
} catch (IndexOutOfBoundsException e) {
}
+ }
+
+ /**
+ * @tests java.lang.StringBuilder.replace(int, int, String)'
+ */
+ 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());
+ }
+
+ private void reverseTest(String org, String rev, String back) {
+ // create non-shared StringBuilder
+ StringBuilder sb = new StringBuilder(org);
+ sb.reverse();
+ String reversed = sb.toString();
+ assertEquals(rev, reversed);
+ // create non-shared StringBuilder
+ sb = new StringBuilder(reversed);
+ sb.reverse();
+ reversed = sb.toString();
+ assertEquals(back, reversed);
+
+ // test algorithm when StringBuilder is shared
+ sb = new StringBuilder(org);
+ String copy = sb.toString();
+ assertEquals(org, copy);
+ sb.reverse();
+ reversed = sb.toString();
+ assertEquals(rev, reversed);
+ sb = new StringBuilder(reversed);
+ copy = sb.toString();
+ assertEquals(rev, copy);
+ sb.reverse();
+ reversed = sb.toString();
+ assertEquals(back, reversed);
}
- /**
- * @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() {
+ /**
+ * @tests java.lang.StringBuilder.reverse()
+ */
+ public void test_reverse() {
final String fixture = "0123456789";
StringBuilder sb = new StringBuilder(fixture);
assertSame(sb, sb.reverse());
@@ -1888,252 +1609,336 @@ public class StringBuilderTest extends TestCase {
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());
+ String str;
+ str = "a";
+ reverseTest(str, str, str);
- try {
- sb.setCharAt(-1, 'A');
- fail("No IOOBE, negative index");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
+ str = "ab";
+ reverseTest(str, "ba", str);
- try {
- sb.setCharAt(4, 'A');
- fail("No IOOBE, index == length");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
+ str = "abcdef";
+ reverseTest(str, "fedcba", str);
- try {
- sb.setCharAt(5, 'A');
- fail("No IOOBE, index > length");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
+ str = "abcdefg";
+ reverseTest(str, "gfedcba", str);
- /**
- * @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());
+ str = "\ud800\udc00";
+ reverseTest(str, str, str);
- try {
- sb.setLength(-1);
- fail("No IOOBE, negative length.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
+ str = "\udc00\ud800";
+ reverseTest(str, "\ud800\udc00", "\ud800\udc00");
- /**
- * @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());
+ str = "a\ud800\udc00";
+ reverseTest(str, "\ud800\udc00a", str);
- ss = sb.subSequence(0, 0);
- assertEquals("", ss.toString());
+ str = "ab\ud800\udc00";
+ reverseTest(str, "\ud800\udc00ba", str);
- try {
- sb.subSequence(-1, 1);
- fail("No IOOBE, negative start.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
+ str = "abc\ud800\udc00";
+ reverseTest(str, "\ud800\udc00cba", str);
- try {
- sb.subSequence(0, -1);
- fail("No IOOBE, negative end.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
+ str = "\ud800\udc00\udc01\ud801\ud802\udc02";
+ reverseTest(str, "\ud802\udc02\ud801\udc01\ud800\udc00",
+ "\ud800\udc00\ud801\udc01\ud802\udc02");
- try {
- sb.subSequence(0, fixture.length() + 1);
- fail("No IOOBE, end > length.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
+ str = "\ud800\udc00\ud801\udc01\ud802\udc02";
+ reverseTest(str, "\ud802\udc02\ud801\udc01\ud800\udc00", str);
- try {
- sb.subSequence(3, 2);
- fail("No IOOBE, start > end.");
- } catch (IndexOutOfBoundsException e) {
- // Expected
- }
- }
+ str = "\ud800\udc00\udc01\ud801a";
+ reverseTest(str, "a\ud801\udc01\ud800\udc00",
+ "\ud800\udc00\ud801\udc01a");
- /**
- * @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);
+ str = "a\ud800\udc00\ud801\udc01";
+ reverseTest(str, "\ud801\udc01\ud800\udc00a", str);
- ss = sb.substring(10);
- assertEquals("", ss);
+ str = "\ud800\udc00\udc01\ud801ab";
+ reverseTest(str, "ba\ud801\udc01\ud800\udc00",
+ "\ud800\udc00\ud801\udc01ab");
- try {
- sb.substring(-1);
- fail("No SIOOBE, negative start.");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
+ str = "ab\ud800\udc00\ud801\udc01";
+ reverseTest(str, "\ud801\udc01\ud800\udc00ba", str);
- try {
- sb.substring(0, -1);
- fail("No SIOOBE, negative end.");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
+ str = "\ud800\udc00\ud801\udc01";
+ reverseTest(str, "\ud801\udc01\ud800\udc00", str);
- try {
- sb.substring(fixture.length() + 1);
- fail("No SIOOBE, start > length.");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
+ str = "a\ud800\udc00z\ud801\udc01";
+ reverseTest(str, "\ud801\udc01z\ud800\udc00a", str);
+
+ str = "a\ud800\udc00bz\ud801\udc01";
+ reverseTest(str, "\ud801\udc01zb\ud800\udc00a", str);
+
+ str = "abc\ud802\udc02\ud801\udc01\ud800\udc00";
+ reverseTest(str, "\ud800\udc00\ud801\udc01\ud802\udc02cba", str);
+
+ str = "abcd\ud802\udc02\ud801\udc01\ud800\udc00";
+ reverseTest(str, "\ud800\udc00\ud801\udc01\ud802\udc02dcba", str);
}
- /**
- * @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);
+ /**
+ * @tests java.lang.StringBuilder.setCharAt(int, char)
+ */
+ 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)'
+ */
+ 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
+ }
+
+ sb = new StringBuilder("abcde");
+ assertEquals("abcde", sb.toString());
+ sb.setLength(1);
+ sb.append('g');
+ assertEquals("ag", sb.toString());
- ss = sb.substring(0, 0);
- assertEquals("", ss);
+ sb = new StringBuilder("abcde");
+ sb.setLength(3);
+ sb.append('g');
+ assertEquals("abcg", sb.toString());
+ sb = new StringBuilder("abcde");
+ sb.setLength(2);
try {
- sb.substring(-1, 1);
- fail("No SIOOBE, negative start.");
- } catch (StringIndexOutOfBoundsException e) {
+ sb.charAt(3);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
// Expected
}
- try {
- sb.substring(0, -1);
- fail("No SIOOBE, negative end.");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
+ sb = new StringBuilder();
+ sb.append("abcdefg");
+ sb.setLength(2);
+ sb.setLength(5);
+ for (int i = 2; i < 5; i++) {
+ assertEquals(0, sb.charAt(i));
}
- try {
- sb.substring(0, fixture.length() + 1);
- fail("No SIOOBE, end > length.");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
+ sb = new StringBuilder();
+ sb.append("abcdefg");
+ sb.delete(2, 4);
+ sb.setLength(7);
+ assertEquals('a', sb.charAt(0));
+ assertEquals('b', sb.charAt(1));
+ assertEquals('e', sb.charAt(2));
+ assertEquals('f', sb.charAt(3));
+ assertEquals('g', sb.charAt(4));
+ for (int i = 5; i < 7; i++) {
+ assertEquals(0, sb.charAt(i));
}
- try {
- sb.substring(3, 2);
- fail("No SIOOBE, start > end.");
- } catch (StringIndexOutOfBoundsException e) {
- // Expected
- }
- }
+ sb = new StringBuilder();
+ sb.append("abcdefg");
+ sb.replace(2, 5, "z");
+ sb.setLength(7);
+ for (int i = 5; i < 7; i++) {
+ assertEquals(0, sb.charAt(i));
+ }
+ }
+
+ /**
+ * @tests java.lang.StringBuilder.subSequence(int, int)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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() {
+ public void test_toString() throws Exception {
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());
+ sb.setLength(0);
+ sb.append("abcde");
+ assertEquals("abcde", sb.toString());
+ sb.setLength(1000);
+ byte[] bytes = sb.toString().getBytes("GB18030");
+ for (int i = 5; i < bytes.length; i++) {
+ assertEquals(0, bytes[i]);
+ }
+
+ sb.setLength(5);
+ sb.append("fghij");
+ assertEquals("abcdefghij", sb.toString());
}
+ /**
+ * @tests java.lang.StringBuilder.trimToSize()'
+ */
+ 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,
@@ -2149,12 +1954,6 @@ public class StringBuilderTest extends TestCase {
/**
* @tests serialization/deserialization.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization.",
- method = "!SerializationSelf",
- args = {}
- )
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(new StringBuilder("0123456789"),
@@ -2164,28 +1963,22 @@ public class StringBuilderTest extends TestCase {
/**
* @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 static final class Fixture {
+ static final Fixture INSTANCE = new Fixture();
- private Fixture() {
- super();
- }
+ private Fixture() {
+ super();
+ }
- @Override
+ @Override
public String toString() {
- return "fixture";
- }
- }
+ 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
index 2adf610..8ffeb3a 100644
--- 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
@@ -17,25 +17,13 @@
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());
@@ -46,26 +34,9 @@ public class StringIndexOutOfBoundsExceptionTest extends TestCase {
/**
* @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/ThreadDeathTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/ThreadDeathTest.java
index abb52c1..c40e0b0 100644
--- 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
@@ -17,26 +17,14 @@
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();
+ /**
+ * @tests java.lang.ThreadDeath#ThreadDeath()
+ */
+ 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/TypeNotPresentExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/lang/TypeNotPresentExceptionTest.java
index 4b01a98..1f86648 100644
--- 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
@@ -16,25 +16,13 @@
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);
@@ -55,12 +43,6 @@ public class TypeNotPresentExceptionTest extends TestCase {
/**
* @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());
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
index a894d7e..15f264b 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.UnknownError#UnknownError()
+ */
public void test_Constructor() {
UnknownError e = new UnknownError();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class UnknownErrorTest extends TestCase {
/**
* @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());
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
index 39a8855..84229d8 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.UnsatisfiedLinkError#UnsatisfiedLinkError()
+ */
public void test_Constructor() {
UnsatisfiedLinkError e = new UnsatisfiedLinkError();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class UnsatisfiedLinkErrorTest extends TestCase {
/**
* @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());
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
index c1f3ee9..e9757f1 100644
--- 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
@@ -1,55 +1,46 @@
-/*
- * 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
- *
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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; // android-changed
-import junit.framework.TestCase;
+public class UnsupportedClassVersionErrorTest extends TestCase { // android-changed
+ /**
+ * Thrown when the Java Virtual Machine attempts to read a class file and
+ * determines that the major and minor version numbers in the file are not
+ * supported.
+ */
-@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());
+ /**
+ * @tests java.lang.UnsupportedClassVersionError#UnsupportedClassVersionError()
+ */
+ public void test_UnsupportedClassVersionError() {
+ UnsupportedClassVersionError error = new UnsupportedClassVersionError();
+ assertNotNull(error);
+ assertNull(error.getMessage());
}
-
- @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());
+
+ /**
+ *@tests java.lang.UnsupportedClassVersionError#UnsupportedClassVersionError(java.lang.String)
+ */
+ public void test_UnsupportedClassVersionError_LString() {
+ UnsupportedClassVersionError e = new UnsupportedClassVersionError(
+ "Some Error Message");
+ assertEquals("Wrong message", "Some Error Message", e.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
index 73176bb..0458012 100644
--- 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
@@ -17,26 +17,15 @@
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 = {}
- )
+ /**
+ * @tests java.lang.UnsupportedOperationException#UnsupportedOperationException()
+ */
public void test_Constructor() {
UnsupportedOperationException e = new UnsupportedOperationException();
assertNull(e.getMessage());
@@ -47,55 +36,54 @@ public class UnsupportedOperationExceptionTest extends TestCase {
/**
* @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());
+ /**
+ * @tests {@link java.land.UnsupportedOperationException#UnsupportedOperationException(java.lang.Throwable)}
+ */
+ public void test_ConstructorLjava_lang_Throwable() {
+ Throwable emptyThrowable = new Exception();
+ UnsupportedOperationException emptyException = new UnsupportedOperationException(
+ emptyThrowable);
+ assertEquals(emptyThrowable.getClass().getName(), emptyException.getMessage());
+ assertEquals(emptyThrowable.getClass().getName(), emptyException.getLocalizedMessage());
+ assertEquals(emptyThrowable.getClass().getName(), emptyException.getCause().toString());
+
+ Throwable throwable = new Exception("msg");
+ UnsupportedOperationException exception = new UnsupportedOperationException(throwable);
+ assertEquals(throwable.getClass().getName() + ": " + "msg", exception.getMessage());
+ assertEquals(throwable.getClass().getName(), emptyException.getLocalizedMessage());
+ assertEquals(throwable.getClass().getName(), emptyException.getCause().toString());
}
-
- @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 {@link java.land.UnsupportedOperationException#UnsupportedOperationException(java.lang.String, java.lang.Throwable)}
+ */
+ public void test_ConstructorLjava_lang_StringLjava_lang_Throwable() {
+ Throwable emptyThrowable = new Exception();
+ UnsupportedOperationException emptyException = new UnsupportedOperationException(
+ "msg", emptyThrowable);
+ assertEquals("msg", emptyException.getMessage());
+ assertEquals("msg", emptyException.getLocalizedMessage());
+ assertEquals(emptyThrowable.getClass().getName(), emptyException.getCause().toString());
+
+ Throwable throwable = new Exception("msg_exception");
+ UnsupportedOperationException exception = new UnsupportedOperationException(
+ "msg", throwable);
+ assertEquals("msg", exception.getMessage());
+ assertEquals("msg", exception.getLocalizedMessage());
+ assertEquals(throwable.getClass().getName() + ": " + throwable.getMessage(), exception
+ .getCause().toString());
}
+
/**
* @tests serialization/deserialization.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- )
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(new UnsupportedOperationException());
@@ -104,12 +92,6 @@ public class UnsupportedOperationExceptionTest extends TestCase {
/**
* @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,
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
index 3115698..7bd2581 100644
--- 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
@@ -17,25 +17,13 @@
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 = {}
- )
+ /**
+ * @tests java.lang.VerifyError#VerifyError()
+ */
public void test_Constructor() {
VerifyError e = new VerifyError();
assertNull(e.getMessage());
@@ -46,12 +34,6 @@ public class VerifyErrorTest extends TestCase {
/**
* @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());
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
index b998b98..c8ce58c 100644
--- 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
@@ -17,26 +17,14 @@
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 = {}
- )
+ /**
+ * @tests java.lang.VirtualMachineError#VirtualMachineError()
+ */
public void test_Constructor() {
VirtualMachineError e = new VirtualMachineError() {};
assertNull(e.getMessage());
@@ -47,12 +35,6 @@ public class VirtualMachineErrorTest extends TestCase {
/**
* @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());
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
index 91ca3a4..ef60ac3 100644
--- 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
@@ -30,7 +30,7 @@ public class AllTests {
}
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.net");
+ TestSuite suite = new TestSuite("Tests for java.net");
// add net testsuites here
suite.addTestSuite(ContentHandlerTest.class);
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
index 6b1957a..07a374b 100644
--- 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
@@ -17,11 +17,6 @@
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;
@@ -29,19 +24,12 @@ 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, };
@@ -49,7 +37,7 @@ public class ContentHandlerTest extends TestCase {
((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());
@@ -58,33 +46,6 @@ public class ContentHandlerTest extends TestCase {
((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());
}
}
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
index 3e3cafe..bc14d6f 100644
--- 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
@@ -17,11 +17,6 @@
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;
@@ -30,7 +25,6 @@ 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$
@@ -54,12 +48,6 @@ public class HttpRetryExceptionTest extends TestCase {
/**
* @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);
@@ -68,12 +56,6 @@ public class HttpRetryExceptionTest extends TestCase {
/**
* @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/URITest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URITest.java
index e290e27..e7be391 100644
--- 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
@@ -1,177 +1,1859 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import junit.framework.TestCase;
-@TestTargetClass(URI.class)
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
public class URITest extends TestCase {
+
+ private URI[] uris;
+
+ 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(java.lang.String)
+ * @tests java.net.URI#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 {
+ // tests for public URI(String uri) throws URISyntaxException
+
+ 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
+ };
+
+ 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);
+ }
+ }
+
+ 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
+ };
+
+ 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) {
+ }
+ }
+
// 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());
+ 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.
+ // 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){
+ } catch (URISyntaxException e) {
// Expected
}
-
- uri = new URI("http","//myhost:-8096", null);
+
+ 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){
+ } catch (URISyntaxException e) {
// Expected
}
}
-
+
/**
- * @tests java.net.URI(java.lang.String, java.lang.String, java.lang.String)
+ * @tests java.net.URI#URI(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
+ public void test_URI_String() {
try {
- new URI("","//authority/path", "fragment");
- fail ("Assert 0: Expected URISyntaxException with empty URI scheme");
- } catch(URISyntaxException e) {
+ 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)
+ */
+ public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String()
+ throws URISyntaxException {
+ URI 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());
+
+ // scheme specific part can not be null
+ try {
+ uri = new URI("mailto", null, null);
+ fail("Expected URISyntaxException");
+ } catch (URISyntaxException e) {
+ // Expected
+ }
+
+ // scheme needs to start with an alpha char
+ try {
+ uri = new URI("3scheme", "//authority/path", "fragment");
+ fail("Expected URISyntaxException");
+ } catch (URISyntaxException e) {
+ // Expected
+ }
+
+ // scheme can not be empty string
+ try {
+ uri = new URI("", "//authority/path", "fragment");
+ fail("Expected URISyntaxException");
+ } catch (URISyntaxException e) {
// Expected
- assertEquals("Assert 1: Wrong index in URISyntaxException.", 0, e.getIndex());
}
}
-
+
+ /**
+ * @tests java.net.URI#URI(java.lang.String, java.lang.String,
+ * java.lang.String, int, java.lang.String, java.lang.String,
+ * java.lang.String)
+ */
+ public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_StringILjava_lang_StringLjava_lang_StringLjava_lang_String() {
+ // 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ public void test_compareToLjava_lang_Object() throws Exception {
+ // 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..
+
+ // different 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++) {
+ 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]);
+ }
+ }
+ }
+
+ /**
+ * @throws URISyntaxException
+ * @tests java.net.URI#compareTo(java.lang.Object)
+ */
+ 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)
+ */
+ public void test_createLjava_lang_String() {
+ try {
+ URI myUri = URI.create("a scheme://reg/");
+ fail("IllegalArgumentException expected but not received.");
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * @tests java.net.URI#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() throws Exception {
+ 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++) {
+ 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]);
+ }
+ }
+
+ }
+
+ /**
+ * @throws URISyntaxException
+ * @tests java.net.URI#equals(java.lang.Object)
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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 character 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.PARTIAL,
- notes = "NullPointerException checking missed.",
- method = "relativize",
- args = {java.net.URI.class}
- )
- public void test_relativizeLjava_net_URI() throws URISyntaxException{
+ public void test_relativizeLjava_net_URI() throws URISyntaxException {
+ // 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);
+ }
+ }
+
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));
-
+ 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));
+ 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));
+ 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 {
+
+ // Regression test for HARMONY-6075
+ public void test_relativize3() throws Exception {
+ URI uri = new URI("file", null, "/test/location", null);
+
+ URI base = new URI("file", null, "/test", null);
+
+ URI relative = base.relativize(uri);
+ assertEquals("location", relative.getSchemeSpecificPart());
+ assertNull(relative.getScheme());
+ }
+
+ /**
+ * @tests java.net.URI#relativize(java.net.URI)
+ */
+ public void test_relativize2() throws URISyntaxException {
+ 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));
+
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#resolve(java.net.URI)
+ */
+ 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)
+ */
+ 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: " + b.resolve(r)
+ + ", 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);
+ }
+ }
+ }
+
+ /**
+ * @tests java.net.URI#toASCIIString()
+ */
+ 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()
+ */
+ 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()
+ */
+ public void test_toURL() throws Exception {
+ String absoluteuris[] = new String[] { "mailto:noreply@apache.org",
+ "urn:isbn:123498989h", "news:software.ibm.com",
+ "http://www.apache.org", "file:///d:/temp/results.txt",
+ "scheme:ssp", };
+
+ String relativeuris[] = new String[] { "calculate.pl?isbn=123498989h",
+ "?isbn=123498989h", "//www.apache.org", "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
+ }
+ }
+ }
/**
- * @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);
-
+ * @tests serialization/deserialization.
+ */
+ public void testSerializationSelf() throws Exception {
+ URI uri = new URI("http://harmony.apache.org/");
+
+ SerializationTest.verifySelf(uri);
}
}
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
index 52fdf4a..67a81cf 100644
--- 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
@@ -1,57 +1,67 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.URLDecoder;
import java.net.URLEncoder;
import junit.framework.TestCase;
+import tests.support.Support_Configuration;
-@TestTargetClass(URLEncoder.class)
public class URLEncoderTest extends TestCase {
-
+
+ /**
+ * @tests java.net.URLEncoder#encode(java.lang.String)
+ */
+ @SuppressWarnings("deprecation")
+ public void test_encodeLjava_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 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 {
+ public void test_encodeLjava_lang_StringLjava_lang_String()
+ throws Exception {
// Regression for HARMONY-24
try {
- URLEncoder.encode("str","unknown_enc");
+ URLEncoder.encode("str", "unknown_enc");
fail("Assert 0: Should throw UEE for invalid encoding");
} catch (UnsupportedEncodingException e) {
// expected
- }
- //Regression for HARMONY-1233
+ }
+
+ // Regression for HARMONY-1233
try {
URLEncoder.encode(null, "harmony");
fail("NullPointerException expected");
} catch (NullPointerException e) {
- //expected
+ // expected
}
}
}
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
index 801727c..6021c32 100644
--- 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
@@ -17,29 +17,17 @@
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>() {
@@ -65,12 +53,6 @@ public class AbstractCollectionTest extends TestCase {
/**
* @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>() {
@@ -100,12 +82,6 @@ public class AbstractCollectionTest extends TestCase {
/**
* @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>() {
@@ -135,12 +111,6 @@ public class AbstractCollectionTest extends TestCase {
/**
* @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>(){
@@ -162,12 +132,6 @@ public class AbstractCollectionTest extends TestCase {
/**
* @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>() {
@@ -210,12 +174,6 @@ public class AbstractCollectionTest extends TestCase {
/**
* @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>() {
@@ -254,12 +212,6 @@ public class AbstractCollectionTest extends TestCase {
/**
* @tests java.util.AbstractCollection#toArray()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toArray",
- args = {}
- )
public void test_toArray() {
AbstractCollection<String> ac = new AbstractCollection<String>() {
@Override
@@ -300,12 +252,6 @@ public class AbstractCollectionTest extends TestCase {
/**
* @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
@@ -365,12 +311,6 @@ public class AbstractCollectionTest extends TestCase {
/**
* @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.)
@@ -396,128 +336,4 @@ public class AbstractCollectionTest extends TestCase {
} 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/AllTests.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/AllTests.java
index 2bfc7bf..88c4fad 100644
--- 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
@@ -30,7 +30,7 @@ public class AllTests {
}
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.util");
+ TestSuite suite = new TestSuite("Tests for java.util");
suite.addTestSuite(AbstractCollectionTest.class);
suite.addTestSuite(AbstractMapTest.class);
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
index ab29579..7c58d45 100644
--- 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
@@ -1,24 +1,343 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.ArrayList;
import java.util.Arrays;
+import java.util.Collection;
+import java.util.ConcurrentModificationException;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.Vector;
+
+import tests.support.Support_ListTest;
+
+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()
+ */
+ 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)
+ */
+ public void test_ConstructorI() {
+ // Test for method java.util.ArrayList(int)
+ ArrayList al = new ArrayList(5);
+ assertEquals("Incorrect arrayList created", 0, al.size());
+
+ al = new ArrayList(0);
+ assertEquals("Incorrect arrayList created", 0, al.size());
+
+ try {
+ al = new ArrayList(-1);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * @tests java.util.ArrayList#ArrayList(java.util.Collection)
+ */
+ 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]);
+
+ }
+
+ public void testConstructorWithConcurrentCollection() {
+ Collection<String> collection = shrinksOnSize("A", "B", "C", "D");
+ ArrayList<String> list = new ArrayList<String>(collection);
+ assertFalse(list.contains(null));
+ }
+
+ /**
+ * @tests java.util.ArrayList#add(int, java.lang.Object)
+ */
+ 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);
+
+ alist.add(0, o = new Object());
+ assertEquals("Failed to add Object", alist.get(0), o);
+ assertEquals(alist.get(1), objArray[0]);
+ assertEquals(alist.get(2), objArray[1]);
+
+ oldItem = alist.get(0);
+ alist.add(0, null);
+ assertNull("Should have returned null", alist.get(0));
+ assertEquals("Should have returned the old item from slot 0", alist
+ .get(1), oldItem);
+
+ try {
+ alist.add(-1, new Object());
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+
+ try {
+ alist.add(-1, null);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+
+ try {
+ alist.add(alist.size() + 1, new Object());
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+
+ try {
+ alist.add(alist.size() + 1, null);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.util.ArrayList#add(int, java.lang.Object)
+ */
+ public void test_addILjava_lang_Object_2() {
+ Object o = new Object();
+ int size = alist.size();
+ alist.add(size, o);
+ assertEquals("Failed to add Object", alist.get(size), o);
+ assertEquals(alist.get(size - 2), objArray[size - 2]);
+ assertEquals(alist.get(size - 1), objArray[size - 1]);
+
+ alist.remove(size);
+
+ size = alist.size();
+ alist.add(size, null);
+ assertNull("Should have returned null", alist.get(size));
+ assertEquals(alist.get(size - 2), objArray[size - 2]);
+ assertEquals(alist.get(size - 1), objArray[size - 1]);
+ }
+
+ /**
+ * @tests java.util.ArrayList#add(java.lang.Object)
+ */
+ 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)
+ */
+ 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);
+ }
+
+ /**
+ * @tests java.util.ArrayList#addAll(int, java.util.Collection)
+ */
+ @SuppressWarnings("unchecked")
+ 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) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+
+ // Regression for HARMONY-5705
+ String[] data = new String[] { "1", "2", "3", "4", "5", "6", "7", "8" };
+ ArrayList list1 = new ArrayList();
+ ArrayList list2 = new ArrayList();
+ for (String d : data) {
+ list1.add(d);
+ list2.add(d);
+ list2.add(d);
+ }
+ while (list1.size() > 0)
+ list1.remove(0);
+ list1.addAll(list2);
+ assertTrue("The object list is not the same as original list", list1
+ .containsAll(list2)
+ && list2.containsAll(list1));
+
+ obj = new ArrayList();
+ for (int i = 0; i < 100; i++) {
+ if (list1.size() > 0) {
+ obj.removeAll(list1);
+ obj.addAll(list1);
+ }
+ }
+ assertTrue("The object list is not the same as original list", obj
+ .containsAll(list1)
+ && list1.containsAll(obj));
-@TestTargetClass(ArrayList.class)
-public class ArrayListTest extends TestCase {
+ // Regression for Harmony-5799
+ list1 = new ArrayList();
+ list2 = new ArrayList();
+ int location = 2;
+
+ String[] strings = { "0", "1", "2", "3", "4", "5", "6" };
+ int[] integers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
+ for (int i = 0; i < 7; i++) {
+ list1.add(strings[i]);
+ }
+ for (int i = 0; i < 10; i++) {
+ list2.add(integers[i]);
+ }
+ list1.remove(location);
+ list1.addAll(location, list2);
+
+ // Inserted elements should be equal to integers array
+ for (int i = 0; i < integers.length; i++) {
+ assertEquals(integers[i], list1.get(location + i));
+ }
+ // Elements after inserted location should
+ // be equals to related elements in strings array
+ for (int i = location + 1; i < strings.length; i++) {
+ assertEquals(strings[i], list1.get(i + integers.length - 1));
+ }
+ }
+
+ /**
+ * @tests java.util.ArrayList#addAll(int, java.util.Collection)
+ */
+ public void test_addAllILjava_util_Collection_3() {
+ ArrayList obj = new ArrayList();
+ obj.addAll(0, obj);
+ obj.addAll(obj.size(), obj);
+ try {
+ obj.addAll(-1, obj);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+
+ try {
+ obj.addAll(obj.size() + 1, obj);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+
+ try {
+ obj.addAll(0, null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Excepted
+ }
+
+ try {
+ obj.addAll(obj.size() + 1, null);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+
+ try {
+ obj.addAll((int) -1, (Collection) null);
+ fail("IndexOutOfBoundsException expected");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+ }
- @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
@@ -35,23 +354,652 @@ public class ArrayListTest extends TestCase {
assertEquals("d", blist.get(2));
}
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test.",
- method = "addAll",
- args = {java.util.Collection.class}
- )
- public void test_growForInsert() {
- ArrayList<Integer> arrayList = new ArrayList<Integer>();
- arrayList.addAll(0, Arrays.asList(1, 2));
- arrayList.addAll(2, Arrays.asList(13));
- arrayList.addAll(0, Arrays.asList(0));
- arrayList.addAll(3, Arrays.asList(11, 12));
- arrayList.addAll(6, Arrays.asList(22, 23, 24, 25, 26, 27, 28, 29));
- arrayList.addAll(6, Arrays.asList(14, 15, 16, 17, 18, 19, 20, 21));
- arrayList.addAll(3, Arrays.asList(3, 4, 5, 6, 7, 8, 9, 10));
- assertEquals(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
- 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29),
- arrayList);
- }
-} \ No newline at end of file
+ /**
+ * @tests java.util.ArrayList#addAll(java.util.Collection)
+ */
+ 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());
+
+ try {
+ alist.addAll(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Excepted
+ }
+
+ // 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());
+
+ }
+
+ public void test_ArrayList_addAll_scenario1() {
+ ArrayList arrayListA = new ArrayList();
+ arrayListA.add(1);
+ ArrayList arrayListB = new ArrayList();
+ arrayListB.add(1);
+ arrayListA.addAll(1, arrayListB);
+ int size = arrayListA.size();
+ assertEquals(2, size);
+ for (int index = 0; index < size; index++) {
+ assertEquals(1, arrayListA.get(index));
+ }
+ }
+
+ public void test_ArrayList_addAll_scenario2() {
+ ArrayList arrayList = new ArrayList();
+ arrayList.add(1);
+ arrayList.addAll(1, arrayList);
+ int size = arrayList.size();
+ assertEquals(2, size);
+ for (int index = 0; index < size; index++) {
+ assertEquals(1, arrayList.get(index));
+ }
+ }
+
+ // Regression test for HARMONY-5839
+ public void testaddAllHarmony5839() {
+ Collection coll = Arrays.asList(new String[] { "1", "2" });
+ List list = new ArrayList();
+ list.add("a");
+ list.add(0, "b");
+ list.add(0, "c");
+ list.add(0, "d");
+ list.add(0, "e");
+ list.add(0, "f");
+ list.add(0, "g");
+ list.add(0, "h");
+ list.add(0, "i");
+
+ list.addAll(6, coll);
+
+ assertEquals(11, list.size());
+ assertFalse(list.contains(null));
+ }
+
+ /**
+ * @tests java.util.ArrayList#clear()
+ */
+ 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()
+ */
+ 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)
+ */
+ 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)
+ */
+ 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);
+ 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));
+ }
+
+ /**
+ * @tests java.util.ArrayList#get(int)
+ */
+ 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) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.util.ArrayList#indexOf(java.lang.Object)
+ */
+ 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()
+ */
+ 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)
+ */
+ 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 {@link java.util.ArrayList#removeRange(int, int)}
+ */
+ public void test_removeRange() {
+ MockArrayList mylist = new MockArrayList();
+ mylist.removeRange(0, 0);
+
+ try {
+ mylist.removeRange(0, 1);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+
+ int[] data = { 1, 2, 3 };
+ for (int i = 0; i < data.length; i++) {
+ mylist.add(i, data[i]);
+ }
+
+ mylist.removeRange(0, 1);
+ assertEquals(data[1], mylist.get(0));
+ assertEquals(data[2], mylist.get(1));
+
+ try {
+ mylist.removeRange(-1, 1);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+
+ try {
+ mylist.removeRange(0, -1);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+
+ try {
+ mylist.removeRange(1, 0);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+
+ try {
+ mylist.removeRange(2, 1);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.util.ArrayList#remove(int)
+ */
+ 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) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+
+ 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) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+ try {
+ l.remove(0);
+ fail("0 should case exception");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.util.ArrayList#set(int, java.lang.Object)
+ */
+ 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);
+
+ obj = new Object();
+ alist.set(0, obj);
+ assertTrue("Failed to set object", alist.get(0) == obj);
+
+ try {
+ alist.set(-1, obj);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+
+ try {
+ alist.set(alist.size(), obj);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+
+ try {
+ alist.set(-1, null);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+
+ try {
+ alist.set(alist.size(), null);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Expected
+ assertNotNull(e.getMessage());
+ }
+ }
+
+ /**
+ * @tests java.util.ArrayList#size()
+ */
+ 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.AbstractCollection#toString()
+ */
+ public void test_toString() {
+ ArrayList l = new ArrayList(1);
+ l.add(l);
+ String result = l.toString();
+ assertTrue("should contain self ref", result.indexOf("(this") > -1);
+ }
+
+ /**
+ * @tests java.util.ArrayList#toArray()
+ */
+ 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[])
+ */
+ 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]);
+ }
+ }
+
+ /**
+ * @tests java.util.ArrayList#trimToSize()
+ */
+ public void test_trimToSize() {
+ // 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");
+ ArrayList al = new ArrayList(v);
+ Iterator it = al.iterator();
+ al.trimToSize();
+ try {
+ it.next();
+ fail("should throw a ConcurrentModificationException");
+ } catch (ConcurrentModificationException ioobe) {
+ // expected
+ }
+ }
+
+ /**
+ * @test java.util.ArrayList#addAll(int, Collection)
+ */
+ 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());
+ }
+
+ public void testAddAllWithConcurrentCollection() {
+ ArrayList<String> list = new ArrayList<String>();
+ list.addAll(shrinksOnSize("A", "B", "C", "D"));
+ assertFalse(list.contains(null));
+ }
+
+ public void testAddAllAtPositionWithConcurrentCollection() {
+ ArrayList<String> list = new ArrayList<String>(
+ Arrays.asList("A", "B", "C", "D"));
+
+ list.addAll(3, shrinksOnSize("E", "F", "G", "H"));
+ assertFalse(list.contains(null));
+ }
+
+ public void test_override_size() throws Exception {
+ ArrayList testlist = new MockArrayList();
+ // though size is overriden, it should passed without exception
+ testlist.add("test_0");
+ testlist.add("test_1");
+ testlist.add("test_2");
+ testlist.add(1, "test_3");
+ testlist.get(1);
+ testlist.remove(2);
+ testlist.set(1, "test_4");
+ }
+
+ public static class ArrayListExtend extends ArrayList {
+
+ private int size = 0;
+
+ public ArrayListExtend() {
+ super(10);
+ }
+
+ public boolean add(Object o) {
+ size++;
+ return super.add(o);
+ }
+
+ public int size() {
+ return size;
+ }
+ }
+
+ public class MockArrayList extends ArrayList {
+ public int size() {
+ return 0;
+ }
+
+ public void removeRange(int start, int end) {
+ super.removeRange(start, end);
+ }
+ }
+
+ public void test_subclassing() {
+ ArrayListExtend a = new ArrayListExtend();
+ /*
+ * Regression test for subclasses that override size() (which used to
+ * cause an exception when growing 'a').
+ */
+ for (int i = 0; i < 100; i++) {
+ a.add(new Object());
+ }
+ }
+
+ /**
+ * 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]);
+ }
+
+ /**
+ * Returns a collection that emulates another thread calling remove() each
+ * time the current thread calls size().
+ */
+ private <T> Collection<T> shrinksOnSize(T... elements) {
+ return new HashSet<T>(Arrays.asList(elements)) {
+ boolean shrink = true;
+
+ @Override
+ public int size() {
+ int result = super.size();
+ if (shrink) {
+ Iterator<T> i = iterator();
+ i.next();
+ i.remove();
+ }
+ return result;
+ }
+
+ @Override
+ public Object[] toArray() {
+ shrink = false;
+ return super.toArray();
+ }
+ };
+ }
+}
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
index b26dd43..54f51f0 100644
--- 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
@@ -1,621 +1,1853 @@
/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.lang.reflect.Method;
import java.util.Arrays;
import java.util.Comparator;
+import java.util.LinkedList;
import java.util.List;
-import java.util.RandomAccess;
-import org.apache.harmony.testframework.serialization.SerializationTest;
+import tests.support.Support_UnmodifiableCollectionTest;
-@TestTargetClass(Arrays.class)
-public class ArraysTest extends TestCase {
+public class ArraysTest extends junit.framework.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);
+ 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;
+ }
+ }
+
+ static class MockComparable implements Comparable{
+ public int compareTo(Object o) {
+ return 0;
}
- 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));
}
+ 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[])
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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));
+
+ Object object = new Object();
+ Object[] objects = new MockComparable[] { new MockComparable() };
+ assertEquals("Should always return 0", 0, Arrays.binarySearch(objects, object));
+
+ Object[] string_objects = new String[] { "one" };
+ try {
+ Arrays.binarySearch(string_objects, object);
+ fail("No expected ClassCastException");
+ } catch (ClassCastException e) {
+ // Expected
+ }
+ }
+
+ /**
+ * @tests java.util.Arrays#binarySearch(java.lang.Object[],
+ * java.lang.Object, java.util.Comparator)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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);
+ }
+
+ /**
+ * @tests java.util.Arrays#fill(char[], char)
+ */
+ 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)
+ */
+ 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);
+ }
+
+ /**
+ * @tests java.util.Arrays#fill(int[], int)
+ */
+ 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)
+ */
+ 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);
+ }
+
+ /**
+ * @tests java.util.Arrays#fill(long[], long)
+ */
+ 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)
+ */
+ 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);
+ }
+
+ /**
+ * @tests java.util.Arrays#fill(float[], float)
+ */
+ 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)
+ */
+ 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);
+ }
+
+ /**
+ * @tests java.util.Arrays#fill(double[], double)
+ */
+ 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)
+ */
+ 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);
+ }
+
+ /**
+ * @tests java.util.Arrays#fill(boolean[], boolean)
+ */
+ 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)
+ */
+ 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);
+ }
+
+ /**
+ * @tests java.util.Arrays#fill(java.lang.Object[], java.lang.Object)
+ */
+ 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)
+ */
+ 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]);
+ }
+
+ /**
+ * @tests java.util.Arrays#equals(byte[], byte[])
+ */
+ 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[])
+ */
+ 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[])
+ */
+ 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[])
+ */
+ 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[])
+ */
+ 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[])
+ */
+ 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[])
+ */
+ 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[])
+ */
+ 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[])
+ */
+ 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[])
+ */
+ 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)
+ */
+ 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[])
+ */
+ 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)
+ */
+ 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[])
+ */
+ 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[] specials3 = new double[] { 0.0, Double.NaN, 1.0, 2.0, Double.NaN,
+ Double.NaN, 1.0, 3.0, -0.0};
+ double[] answer = new double[] { Double.NEGATIVE_INFINITY, -0d, 0d,
+ Double.MIN_VALUE, Double.MAX_VALUE, Double.POSITIVE_INFINITY,
+ Double.NaN };
+ double[] answer3 = new double[] { -0.0, 0.0, 1.0, 1.0, 2.0, 3.0, Double.NaN,
+ Double.NaN, 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));
+
+ Arrays.sort(specials3);
+ Object[] print3 = new Object[specials3.length];
+ for (int i = 0; i < specials3.length; i++)
+ print3[i] = new Double(specials3[i]);
+ assertTrue("specials sort incorrectly 3: " + Arrays.asList(print3),
+ Arrays.equals(specials3, answer3));
+ }
+
+ /**
+ * @tests java.util.Arrays#sort(double[], int, int)
+ */
+ 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[])
+ */
+ 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)
+ */
+ 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[])
+ */
+ 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)
+ */
+ 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[])
+ */
+ 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)
+ */
+ 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[])
+ */
+ 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]);
+ }
+
+ /**
+ * @tests java.util.Arrays#sort(java.lang.Object[], int, int)
+ */
+ 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) {
+ }
+ }
+
+ /**
+ * @tests java.util.Arrays#sort(java.lang.Object[], int, int,
+ * java.util.Comparator)
+ */
+ 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]);
+ }
+
+ /**
+ * @tests java.util.Arrays#sort(java.lang.Object[], java.util.Comparator)
+ */
+ 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);
+ }
+
+ // Regression HARMONY-6076
+ public void test_sort$Ljava_lang_ObjectLjava_util_Comparator_stable() {
+ Element[] array = new Element[11];
+ array[0] = new Element(122);
+ array[1] = new Element(146);
+ array[2] = new Element(178);
+ array[3] = new Element(208);
+ array[4] = new Element(117);
+ array[5] = new Element(146);
+ array[6] = new Element(173);
+ array[7] = new Element(203);
+ array[8] = new Element(56);
+ array[9] = new Element(208);
+ array[10] = new Element(96);
+
+ Comparator<Element> comparator = new Comparator<Element>() {
+ public int compare(Element object1, Element object2) {
+ return object1.value - object2.value;
+ }
+ };
+
+ Arrays.sort(array, comparator);
+
+ for (int i = 1; i < array.length; i++) {
+ assertTrue(comparator.compare(array[i - 1], array[i]) <= 0);
+ if (comparator.compare(array[i - 1], array[i]) == 0) {
+ assertTrue(array[i - 1].index < array[i].index);
+ }
+ }
+ }
+
+ public static class Element {
+ public int value;
+
+ public int index;
+
+ private static int count = 0;
+
+ public Element(int value) {
+ this.value = value;
+ index = count++;
+ }
+ }
+
+ /**
+ * @tests java.util.Arrays#sort(short[])
+ */
+ 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)
+ */
+ 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#binarySearch(float[], float)
+ * @tests java.util.Arrays#sort(byte[], int, int)
*/
- @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);
+ 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
}
- 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[])
+ * @tests java.util.Arrays#sort(char[], int, int)
*/
- @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 }));
+ 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#equals(float[], float[])
+ * @tests java.util.Arrays#sort(double[], int, int)
*/
- @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 }));
+ 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(double[])
+ * @tests java.util.Arrays#sort(float[], int, int)
*/
- @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);
+ 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
}
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < reversedArray.length; counter ++) {
- assertTrue("Assert 0: Resulting array not sorted",
- reversedArray[counter] == counter);
+ 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
}
+ }
- // 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]);
+ /**
+ * @tests java.util.Arrays#sort(int[], int, int)
+ */
+ 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
}
- 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]);
+ 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
}
- assertTrue("Assert 2: specials sort incorrectly " + Arrays.asList(print2),
- Arrays.equals(specials2, answer));
}
-
+
/**
- * @tests java.util.Arrays#sort(float[])
+ * @tests java.util.Arrays#sort(Object[], int, int)
*/
- @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);
+ 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
}
- Arrays.sort(reversedArray);
- for (int counter = 0; counter < reversedArray.length; counter ++) {
- assertTrue("Assert 0: Resulting array not sorted",
- reversedArray[counter] == counter);
+ 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
}
-
- 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]);
+ 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
}
- 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]);
+ /**
+ * @tests java.util.Arrays#sort(long[], int, int)
+ */
+ 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
}
- assertTrue("Assert 2: specials sort incorrectly" + Arrays.asList(print2),
- Arrays.equals(specials2, answer));
}
-
+
/**
- * @tests java.util.Arrays#toString(boolean[])
+ * @tests java.util.Arrays#sort(short[], int, int)
*/
- @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}));
+ 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#toString(byte[])
+ * @tests java.util.Arrays#deepEquals(Object[], Object[])
*/
- @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}));
+ 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#toString(char[])
+ * @tests java.util.Arrays#deepHashCode(Object[])
*/
- @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'}));
- }
+ 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#toString(double[])
+ * @tests java.util.Arrays#hashCode(boolean[] a)
*/
- @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}));
+ 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#toString(float[])
+ * @tests java.util.Arrays#hashCode(int[] a)
*/
- @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}));
+ 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#toString(int[])
+ * @tests java.util.Arrays#hashCode(char[] a)
*/
- @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}));
+ 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#toString(long[])
+ * @tests java.util.Arrays#hashCode(byte[] a)
*/
- @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}));
+ 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#toString(short[])
+ * @tests java.util.Arrays#hashCode(long[] a)
*/
- @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}));
+ 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#toString(Object[])
+ * @tests java.util.Arrays#hashCode(float[] a)
*/
- @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"}));
+ 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#deepToString(Object[])
+ * @tests java.util.Arrays#hashCode(double[] a)
*/
- @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;
+ public void test_hashCode$LD() {
+ int listHashCode;
+ int arrayHashCode;
- 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));
+ 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);
}
- @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));
+
+ /**
+ * @tests java.util.Arrays#hashCode(short[] a)
+ */
+ public void test_hashCode$LS() {
+ int listHashCode;
+ int arrayHashCode;
- try {
- Arrays.asList((Object[])null);
- fail("No NPE");
- } catch (NullPointerException e) {}
+ 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#deepToString(Object[])
- * @bug 1452542
+ * @tests java.util.Arrays#hashCode(Object[] a)
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Tests fix for Android bug 1452542",
- method = "deepToString",
- args = {java.lang.Object[].class}
- )
- public void test_deepToStringNestedEmptyArray() {
- Object[][] foo = new Object[1][];
- foo[0] = new Object[0];
- assertEquals("[[]]", Arrays.deepToString(foo));
+ 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];
- /**
- * @tests java.util.Arrays#deepToString(Object[])
- * @bug 1452542
+ 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;
+ }
+ }
+
+ /**
+ * @tests java.util.Arrays#swap(int, int, Object[])
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Tests fix for Android bug 1452542",
- method = "deepToString",
- args = {java.lang.Object[].class}
- )
- public void test_deepToStringNestedNullArray() {
- Object[][] foo = new Object[1][];
- assertEquals("[null]", Arrays.deepToString(foo));
+ public void test_swap_I_I_$Ljava_lang_Object() throws Exception {
+ Method m = Arrays.class.getDeclaredMethod("swap", int.class, int.class, Object[].class);
+ m.setAccessible(true);
+ Integer[] arr = {new Integer(0), new Integer(1), new Integer(2)};
+ m.invoke(null,0, 1, arr);
+ assertEquals("should be equal to 1",1, arr[0].intValue());
+ assertEquals("should be equal to 0",0, arr[1].intValue());
}
-
- @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) {}
- }
+ /**
+ * 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/BitSetTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/BitSetTest.java
index 769e31f..7126321 100644
--- 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
@@ -17,78 +17,1386 @@
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.BitSet;
import junit.framework.TestCase;
-import java.util.BitSet;
-
-@TestTargetClass(BitSet.class)
public class BitSetTest extends TestCase {
+ BitSet eightbs;
+
+ /**
+ * @tests java.util.BitSet#BitSet()
+ */
+ public void test_Constructor() {
+ BitSet bs = new BitSet();
+ assertEquals("Create BitSet of incorrect size", 64, bs.size());
+ assertEquals("New BitSet had invalid string representation", "{}",
+ bs.toString());
+ }
+
+ /**
+ * @tests java.util.BitSet#BitSet(int)
+ */
+ public void test_ConstructorI() {
+ BitSet bs = new BitSet(128);
+ assertEquals("Create BitSet of incorrect size", 128, bs.size());
+ assertEquals("New BitSet had invalid string representation: "
+ + bs.toString(), "{}", bs.toString());
+ // 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 element value");
+ } catch (NegativeArraySizeException e) {
+ // Correct behaviour
+ }
+ }
+
+ /**
+ * tests java.util.BitSet#clone()
+ */
+ public void test_clone() {
+ BitSet bs;
+ bs = (BitSet) eightbs.clone();
+ assertEquals("clone failed to return equal BitSet", bs, eightbs);
+ }
+
+ /**
+ * @tests java.util.BitSet#equals(java.lang.Object)
+ */
+ public void test_equalsLjava_lang_Object() {
+ BitSet bs;
+ bs = (BitSet) eightbs.clone();
+ assertEquals("Same BitSet returned false", eightbs, eightbs);
+ assertEquals("Identical BitSet returned false", bs, eightbs);
+ bs.clear(6);
+ assertFalse("Different BitSets returned true", eightbs.equals(bs));
+
+ bs = (BitSet) eightbs.clone();
+ bs.set(128);
+ assertFalse("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()
+ */
+ public void test_hashCode() {
+ // Test for method int java.util.BitSet.hashCode()
+ BitSet bs = (BitSet) eightbs.clone();
+ bs.clear(2);
+ bs.clear(6);
+ assertEquals("BitSet returns wrong hash value", 1129, bs.hashCode());
+ bs.set(10);
+ bs.clear(3);
+ assertEquals("BitSet returns wrong hash value", 97, bs.hashCode());
+ }
+
+ /**
+ * @tests java.util.BitSet#clear()
+ */
+ public void test_clear() {
+ eightbs.clear();
+ for (int i = 0; i < 8; i++) {
+ assertFalse("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)
+ */
+ public void test_clearI() {
+ // Test for method void java.util.BitSet.clear(int)
+
+ eightbs.clear(7);
+ assertFalse("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);
+ assertFalse("Failed to clear bit", eightbs.get(165));
+ // Try out of range
+ try {
+ eightbs.clear(-1);
+ fail("Failed to throw out of bounds exception");
+ } catch (IndexOutOfBoundsException e) {
+ // Correct behaviour
+ }
+
+ BitSet bs = new BitSet(0);
+ assertEquals("Test1: Wrong length,", 0, bs.length());
+ assertEquals("Test1: Wrong size,", 0, bs.size());
+
+ bs.clear(0);
+ assertEquals("Test2: Wrong length,", 0, bs.length());
+ assertEquals("Test2: Wrong size,", 0, bs.size());
+
+ bs.clear(60);
+ assertEquals("Test3: Wrong length,", 0, bs.length());
+ assertEquals("Test3: Wrong size,", 0, bs.size());
+
+ bs.clear(120);
+ assertEquals("Test4: Wrong size,", 0, bs.size());
+ assertEquals("Test4: Wrong length,", 0, bs.length());
+
+ bs.set(25);
+ assertEquals("Test5: Wrong size,", 64, bs.size());
+ assertEquals("Test5: Wrong length,", 26, bs.length());
+
+ bs.clear(80);
+ assertEquals("Test6: Wrong size,", 64, bs.size());
+ assertEquals("Test6: Wrong length,", 26, bs.length());
+
+ bs.clear(25);
+ assertEquals("Test7: Wrong size,", 64, bs.size());
+ assertEquals("Test7: Wrong length,", 0, bs.length());
+ }
+
/**
* @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() {
+ public void test_clearII() throws IndexOutOfBoundsException {
// Regression for HARMONY-98
BitSet bitset = new BitSet();
for (int i = 0; i < 20; i++) {
bitset.set(i);
}
bitset.clear(10, 10);
+
+ // 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)
+ assertFalse("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++)
+ assertFalse("Failed to clear bit " + i, bs.get(i));
+
+ for (int i = 11; i < initialSize; i++) {
+ if (i == 15)
+ assertFalse("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++) {
+ assertFalse("Shouldn't have flipped bit " + i, bs.get(i));
+ }
+
+ // pos1 and pos2 is in the same bitset element, boundry testing
+ bs = new BitSet(16);
+ initialSize = bs.size();
+ bs.set(0, initialSize);
+ bs.clear(7, 64);
+ assertEquals("Failed to grow BitSet", 64, 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++)
+ assertFalse("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++)
+ assertFalse("Failed to clear bit " + i, bs.get(i));
+ for (int i = 64; i < bs.size(); i++) {
+ assertFalse("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++)
+ assertFalse("Failed to clear bit " + i, bs.get(i));
+ for (int i = 65; i < bs.size(); i++) {
+ assertFalse("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)
+ assertFalse("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++)
+ assertFalse("Failed to clear bit " + i, bs.get(i));
+ for (int i = 74; i < initialSize; i++) {
+ if (i == 110)
+ assertFalse("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++) {
+ assertFalse("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)
+ assertFalse("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++)
+ assertFalse("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++)
+ assertFalse("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) {
+ // excepted
+ }
+
+ try {
+ bs.clear(2, -1);
+ fail("Test2: Attempt to flip with negative index failed to generate exception");
+ } catch (IndexOutOfBoundsException e) {
+ // excepted
+ }
+
+ bs.set(2, 4);
+ bs.clear(2, 2);
+ assertTrue("Bit got cleared incorrectly ", bs.get(2));
+
+ try {
+ bs.clear(4, 2);
+ fail("Test4: Attempt to flip with illegal args failed to generate exception");
+ } catch (IndexOutOfBoundsException e) {
+ // excepted
+ }
+
+ bs = new BitSet(0);
+ assertEquals("Test1: Wrong length,", 0, bs.length());
+ assertEquals("Test1: Wrong size,", 0, bs.size());
+
+ bs.clear(0, 2);
+ assertEquals("Test2: Wrong length,", 0, bs.length());
+ assertEquals("Test2: Wrong size,", 0, bs.size());
+
+ bs.clear(60, 64);
+ assertEquals("Test3: Wrong length,", 0, bs.length());
+ assertEquals("Test3: Wrong size,", 0, bs.size());
+
+ bs.clear(64, 120);
+ assertEquals("Test4: Wrong length,", 0, bs.length());
+ assertEquals("Test4: Wrong size,", 0, bs.size());
+
+ bs.set(25);
+ assertEquals("Test5: Wrong length,", 26, bs.length());
+ assertEquals("Test5: Wrong size,", 64, bs.size());
+
+ bs.clear(60, 64);
+ assertEquals("Test6: Wrong length,", 26, bs.length());
+ assertEquals("Test6: Wrong size,", 64, bs.size());
+
+ bs.clear(64, 120);
+ assertEquals("Test7: Wrong size,", 64, bs.size());
+ assertEquals("Test7: Wrong length,", 26, bs.length());
+
+ bs.clear(80);
+ assertEquals("Test8: Wrong size,", 64, bs.size());
+ assertEquals("Test8: Wrong length,", 26, bs.length());
+
+ bs.clear(25);
+ assertEquals("Test9: Wrong size,", 64, bs.size());
+ assertEquals("Test9: Wrong length,", 0, bs.length());
+ }
+
+ /**
+ * @tests java.util.BitSet#get(int)
+ */
+ public void test_getI() {
+ // Test for method boolean java.util.BitSet.get(int)
+
+ BitSet bs = new BitSet();
+ bs.set(8);
+ assertFalse("Get returned true for index out of range", eightbs.get(99));
+ assertTrue("Get returned false for set value", eightbs.get(3));
+ assertFalse("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);
+ assertFalse("Access greater than size", bs.get(64));
+
+ bs = new BitSet();
+ bs.set(63);
+ assertTrue("Test highest bit", bs.get(63));
+
+ bs = new BitSet(0);
+ assertEquals("Test1: Wrong length,", 0, bs.length());
+ assertEquals("Test1: Wrong size,", 0, bs.size());
+
+ bs.get(2);
+ assertEquals("Test2: Wrong length,", 0, bs.length());
+ assertEquals("Test2: Wrong size,", 0, bs.size());
+
+ bs.get(70);
+ assertEquals("Test3: Wrong length,", 0, bs.length());
+ assertEquals("Test3: Wrong size,", 0, bs.size());
+
+ }
+
+ /**
+ * @tests java.util.BitSet#get(int, int)
+ */
+ public void test_getII() {
+ BitSet bitset = new BitSet(30);
+ bitset.get(3, 3);
+
+ // 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);
+ assertEquals("Test1: Returned incorrect BitSet", correctbs, resultbs);
+
+ // pos1 and pos2 are in the same bitset element, at index 1
+ resultbs = bs.get(100, 125);
+ correctbs = new BitSet(25);
+ correctbs.set(21);
+ assertEquals("Test2: Returned incorrect BitSet", correctbs, resultbs);
+
+ // 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);
+ assertEquals("Test3: Returned incorrect BitSet", correctbs, resultbs);
+
+ // 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);
+ assertEquals("Test4: Returned incorrect BitSet", correctbs, resultbs);
+
+ // 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);
+ assertEquals("Test5: Returned incorrect BitSet", correctbs, resultbs);
+
+ // 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);
+ assertEquals("Test6: Returned incorrect BitSet", correctbs, resultbs);
+
+ assertEquals("equality principle 1 ", bs.get(0, bs.size()), bs);
+
+ // 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);
+ assertEquals("Test7: Returned incorrect BitSet", correctbs, resultbs);
+
+ // 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());
+ assertEquals("equality principle 2 ", resultbs, bs2);
+
+ 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());
+ assertEquals("equality principle 3 ", resultbs, bs2);
+
+ bs = new BitSet(0);
+ assertEquals("Test1: Wrong length,", 0, bs.length());
+ assertEquals("Test1: Wrong size,", 0, bs.size());
+
+ bs.get(0, 2);
+ assertEquals("Test2: Wrong length,", 0, bs.length());
+ assertEquals("Test2: Wrong size,", 0, bs.size());
+
+ bs.get(60, 64);
+ assertEquals("Test3: Wrong length,", 0, bs.length());
+ assertEquals("Test3: Wrong size,", 0, bs.size());
+
+ bs.get(64, 120);
+ assertEquals("Test4: Wrong length,", 0, bs.length());
+ assertEquals("Test4: Wrong size,", 0, bs.size());
+
+ bs.set(25);
+ assertEquals("Test5: Wrong length,", 26, bs.length());
+ assertEquals("Test5: Wrong size,", 64, bs.size());
+
+ bs.get(60, 64);
+ assertEquals("Test6: Wrong length,", 26, bs.length());
+ assertEquals("Test6: Wrong size,", 64, bs.size());
+
+ bs.get(64, 120);
+ assertEquals("Test7: Wrong size,", 64, bs.size());
+ assertEquals("Test7: Wrong length,", 26, bs.length());
+
+ bs.get(80);
+ assertEquals("Test8: Wrong size,", 64, bs.size());
+ assertEquals("Test8: Wrong length,", 26, bs.length());
+
+ bs.get(25);
+ assertEquals("Test9: Wrong size,", 64, bs.size());
+ assertEquals("Test9: Wrong length,", 26, bs.length());
+
+ }
+
+ /**
+ * @tests java.util.BitSet#flip(int)
+ */
+ 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);
+ assertFalse("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));
+ assertFalse("Failed to flip bit", bs.get(9));
+ assertFalse("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));
+ assertEquals("Incorrect length", i+1, bs.length());
+ 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)
+ * @tests java.util.BitSet#clear(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);
+
+ // 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));
+ }
+ assertFalse("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));
+ assertFalse("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, boundry testing
+ bs = new BitSet(16);
+ bs.set(7);
+ bs.set(10);
+ bs.flip(7, 64);
+ assertEquals("Failed to grow BitSet", 64, bs.size());
+ for (int i = 0; i < 7; i++) {
+ assertTrue("Shouldn't have flipped bit " + i, !bs.get(i));
+ }
+ assertFalse("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));
+ assertFalse("Failed to flip bit 10", bs.get(10));
+ for (int i = 11; i < 64; i++) {
+ assertTrue("failed to flip bit " + i, bs.get(i));
+ }
+ assertFalse("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));
+ }
+ assertFalse("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));
+ }
+ assertFalse("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++) {
+ assertFalse("Shouldn't have flipped bit " + i, bs.get(i));
+ }
+ assertTrue("Shouldn't have flipped bit 7", bs.get(7));
+ assertFalse("Shouldn't have flipped bit 8", bs.get(8));
+ assertTrue("Failed to flip bit 9", bs.get(9));
+ assertFalse("Failed to flip bit 10", bs.get(10));
+ for (int i = 11; i < 72; i++) {
+ assertTrue("failed to flip bit " + i, bs.get(i));
+ }
+ assertFalse("Failed to flip bit 72", bs.get(72));
+ assertTrue("Failed to flip bit 73", bs.get(73));
+ for (int i = 74; i < 110; i++) {
+ assertFalse("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++) {
+ assertFalse("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++) {
+ assertFalse("Shouldn't have flipped bit " + i, bs.get(i));
+ }
+ assertTrue("Shouldn't have flipped bit 7", bs.get(7));
+ assertFalse("Shouldn't have flipped bit 8", bs.get(8));
+ assertTrue("Failed to flip bit 9", bs.get(9));
+ assertFalse("Failed to flip bit 10", bs.get(10));
+ for (int i = 11; i < 72; i++) {
+ assertTrue("failed to flip bit " + i, bs.get(i));
+ }
+ assertFalse("Failed to flip bit 72", bs.get(72));
+ for (int i = 73; i < 110; i++) {
+ assertTrue("failed to flip bit " + i, bs.get(i));
+ }
+ assertFalse("Failed to flip bit 110", bs.get(110));
+ for (int i = 111; i < 181; i++) {
+ assertTrue("failed to flip bit " + i, bs.get(i));
+ }
+ assertFalse("Failed to flip bit 181", bs.get(181));
+ for (int i = 182; i < 219; i++) {
+ assertTrue("failed to flip bit " + i, bs.get(i));
+ }
+ assertFalse("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) {
+ // correct behavior
+ }
+
+ try {
+ bs.flip(2, -1);
+ fail("Test2: Attempt to flip with negative index failed to generate exception");
+ } catch (IndexOutOfBoundsException e) {
+ // correct behavior
+ }
+
+ try {
+ bs.flip(4, 2);
+ fail("Test4: Attempt to flip with illegal args failed to generate exception");
+ } catch (IndexOutOfBoundsException e) {
+ // correct behavior
+ }
}
/**
- * @tests java.util.BitSet#get(int, int)
+ * @tests java.util.BitSet#set(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);
+ 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));
+ assertEquals("Incorrect length", i+1, bs.length());
+ for (int j = bs.size(); --j > i;)
+ assertFalse("Incorrectly set bit " + j, bs.get(j));
+ for (int j = i; --j >= 0;)
+ assertFalse("Incorrectly set bit " + j, bs.get(j));
+ bs.clear(i);
+ }
+
+ bs = new BitSet(0);
+ assertEquals("Test1: Wrong length", 0, bs.length());
+ bs.set(0);
+ assertEquals("Test2: Wrong length", 1, bs.length());
+ }
+
+ /**
+ * @tests java.util.BitSet#set(int, boolean)
+ */
+ public void test_setIZ() {
+ // Test for method void java.util.BitSet.set(int, boolean)
+ eightbs.set(5, false);
+ assertFalse("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));
}
/**
* @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() {
+ public void test_setII() throws IndexOutOfBoundsException {
BitSet bitset = new BitSet(30);
bitset.set(29, 29);
+
+ // 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
+ assertFalse("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
+ assertFalse("Shouldn't have set bit " + i, bs.get(i));
+ }
+
+ // pos1 and pos2 is in the same bitset element, boundry testing
+ bs = new BitSet(16);
+ bs.set(7, 64);
+ assertEquals("Failed to grow BitSet", 64, bs.size());
+ for (int i = 0; i < 7; i++) {
+ assertFalse("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));
+ }
+ assertFalse("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));
+ }
+ assertFalse("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));
+ }
+ assertFalse("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
+ assertFalse("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
+ assertFalse("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
+ assertFalse("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++) {
+ assertFalse("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) {
+ // Correct behavior
+ }
+
+ try {
+ bs.set(2, -1);
+ fail("Test2: Attempt to flip with negative index failed to generate exception");
+ } catch (IndexOutOfBoundsException e) {
+ // Correct behavior
+ }
+
+ bs.set(2, 2);
+ assertFalse("Bit got set incorrectly ", bs.get(2));
+
+ try {
+ bs.set(4, 2);
+ fail("Test4: Attempt to flip with illegal args failed to generate exception");
+ } catch (IndexOutOfBoundsException e) {
+ // Correct behavior
+ }
+ }
+
+ /**
+ * @tests java.util.BitSet#set(int, int, boolean)
+ */
+ 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));
+
+ }
+
+ /**
+ * @tests java.util.BitSet#intersects(java.util.BitSet)
+ */
+ 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)
+ */
+ 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);
+ assertFalse("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++) {
+ assertFalse("Failed to clear extra bits in the receiver BitSet", bs
+ .get(i));
+ }
+ }
+
+ /**
+ * @tests java.util.BitSet#andNot(java.util.BitSet)
+ */
+ 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)
+ */
+ 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);
+ assertFalse("OR set a bit which should be off", bs.get(5));
+ }
+
+ /**
+ * @tests java.util.BitSet#xor(java.util.BitSet)
+ */
+ 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++) {
+ assertFalse("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()
+ */
+ 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()
+ */
+ 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()
+ */
+ public void test_length() {
+ BitSet bs = new BitSet();
+ assertEquals("BitSet returned wrong length", 0, bs.length());
+ bs.set(5);
+ assertEquals("BitSet returned wrong length", 6, bs.length());
+ bs.set(10);
+ assertEquals("BitSet returned wrong length", 11, bs.length());
+ bs.set(432);
+ assertEquals("BitSet returned wrong length", 433, bs.length());
+ bs.set(300);
+ assertEquals("BitSet returned wrong length", 433, bs.length());
+ }
+
+ /**
+ * @tests java.util.BitSet#nextSetBit(int)
+ */
+ 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) {
+ // correct behavior
+ }
+ 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)
+ */
+ public void test_nextClearBitI() {
+ // Test for method int java.util.BitSet.nextSetBit()
+ BitSet bs = new BitSet(500);
+ bs.set(0, bs.size() - 1); // ensure all the bits from 0 to bs.size()
+ // -1
+ bs.set(bs.size() - 1); // are set to true
+ 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) {
+ // correct behavior
+ }
+ 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()
+ */
+ 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()
+ */
+ 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());
+ }
+
+ protected void setUp() {
+
+ eightbs = new BitSet();
+
+ for (int i = 0; i < 8; i++)
+ eightbs.set(i);
}
+
+ protected void tearDown() {
+ }
+
}
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
index cb4097b..e11d5a3 100644
--- 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
@@ -1,49 +1,505 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.TimeZone;
-import junit.framework.TestCase;
+public class DateTest extends junit.framework.TestCase {
+
+ static class MockDate extends Date{
+ private String holiday;
-import java.util.Date;
+ public MockDate(long theTime) {
+ super(theTime);
+ holiday = "Christmas";
+ }
+
+ // Constructor should not call this public API,
+ // since it may be overrided to use variables uninitialized.
+ public void setTime(long theTime){
+ super.setTime(theTime);
+ holiday.hashCode();
+ }
+ }
+
+ /**
+ * @tests java.util.Date#Date()
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ public void test_ConstructorJ() {
+ // Test for method java.util.Date(long)
+ Date date = new MockDate(1000L);
+ assertNotNull(date);
+ }
+
+ /**
+ * @tests java.util.Date#Date(java.lang.String)
+ */
+ 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)
+ */
+ 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));
+ }
+
+ /**
+ * @tests java.util.Date#before(java.util.Date)
+ */
+ 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));
+ }
+
+ /**
+ * @tests java.util.Date#clone()
+ */
+ 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)
+ */
+ 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));
+
+ }
+
+ /**
+ * @tests java.util.Date#equals(java.lang.Object)
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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());
+ }
-@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() {
+ /**
+ * @tests java.util.Date#getMonth()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ public void test_getTimezoneOffset() {
+ // Test for method int java.util.Date.getTimezoneOffset()
+ assertTrue("Used to test", true);
+ }
+
+ /**
+ * @tests java.util.Date#getYear()
+ */
+ 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()
+ */
+ 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)
+ */
+ 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
+ }
+
// 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"));
- }
+ }
+
+ /**
+ * @tests java.util.Date#setDate(int)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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()
+ */
+ 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()
+ */
+ 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("EST"));
+ try {
+ Date d1 = new Date(0);
+ assertTrue("Returned incorrect string: " + d1, d1.toString()
+ .startsWith("Wed Dec 31 19:00:00")
+ && d1.toString().endsWith("1969"));
+ } finally {
+ TimeZone.setDefault(tz);
+ }
+
+ // Test for HARMONY-5468
+ TimeZone.setDefault(TimeZone.getTimeZone("MST"));
+ Date d2 = new Date(108, 7, 27);
+ assertTrue("Returned incorrect string: " + d2, d2.toString()
+ .startsWith("Wed Aug 27 00:00:00 MST")
+ && d2.toString().endsWith("2008"));
+ }
+
+ /**
+ * @tests java.util.Date#UTC(int, int, int, int, int, int)
+ */
+ 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);
+ }
+
+ static TimeZone defaultTimeZone = TimeZone.getDefault();
+
+ /**
+ * 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() {
+ TimeZone.setDefault(defaultTimeZone);
+ }
}
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
index e700fff..ff6c08f 100644
--- 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
@@ -16,31 +16,19 @@
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 junit.framework.TestCase;
+
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);
@@ -48,19 +36,11 @@ public class DuplicateFormatFlagsExceptionTest extends TestCase {
} 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(
@@ -71,12 +51,6 @@ public class DuplicateFormatFlagsExceptionTest extends TestCase {
/**
* @tests java.util.DuplicateFormatFlagsException#getMessage()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
public void test_getMessage() {
String strFlags = "MYTESTFLAGS";
DuplicateFormatFlagsException duplicateFormatException = new DuplicateFormatFlagsException(
@@ -103,12 +77,6 @@ public class DuplicateFormatFlagsExceptionTest extends TestCase {
/**
* @tests serialization/deserialization.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(new DuplicateFormatFlagsException(
@@ -118,12 +86,6 @@ public class DuplicateFormatFlagsExceptionTest extends TestCase {
/**
* @tests serialization/deserialization compatibility with RI.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
public void testSerializationCompatibility() throws Exception {
SerializationTest.verifyGolden(this, new DuplicateFormatFlagsException(
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
index a76ff54..2ead734 100644
--- 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
@@ -16,32 +16,20 @@
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 junit.framework.TestCase;
+
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, ' ');
@@ -50,18 +38,11 @@ public class FormatFlagsConversionMismatchExceptionTest extends TestCase {
// 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';
@@ -73,18 +54,10 @@ public class FormatFlagsConversionMismatchExceptionTest extends TestCase {
/**
* @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(
+ FormatFlagsConversionMismatchException formatFlagsConversionMismatchException = new FormatFlagsConversionMismatchException(
flags, conversion);
assertEquals(conversion, formatFlagsConversionMismatchException
.getConversion());
@@ -94,12 +67,6 @@ public class FormatFlagsConversionMismatchExceptionTest extends TestCase {
/**
* @tests java.util.FormatFlagsConversionMismatchException#getMessage()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
public void test_getMessage() {
String flags = "MYTESTFLAGS";
char conversion = 'T';
@@ -129,12 +96,6 @@ public class FormatFlagsConversionMismatchExceptionTest extends TestCase {
/**
* @tests serialization/deserialization.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(
@@ -145,12 +106,6 @@ public class FormatFlagsConversionMismatchExceptionTest extends TestCase {
/**
* @tests serialization/deserialization compatibility with RI.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
public void testSerializationCompatibility() throws Exception {
SerializationTest.verifyGolden(this,
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
index 97273f4..1f7e2e9 100644
--- 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
@@ -16,30 +16,17 @@
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.FormatterClosedException;
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());
@@ -48,24 +35,8 @@ public class FormatterClosedExceptionTest extends TestCase {
/**
* @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
index 5a2ec99..5468914 100644
--- 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
@@ -13,60 +13,4321 @@
* 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.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.math.MathContext;
+import java.nio.charset.Charset;
+import java.security.Permission;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+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 java.util.Formatter.BigDecimalLayoutForm;
import junit.framework.TestCase;
-import java.util.Formatter.BigDecimalLayoutForm;
-
-@TestTargetClass(java.util. Formatter.BigDecimalLayoutForm.class)
public class FormatterTest extends TestCase {
+ private boolean root;
+
+ 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()
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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();
+
+ if(!root){
+ 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)
+ */
+ 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();
+
+ if(!root){
+ 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)
+ */
+ 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();
+
+ if(!root){
+ 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)
+ */
+ 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();
+
+ if(!root){
+ 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)
+ */
+ 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();
+
+ if(!root){
+ 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)
+ */
+ 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();
+
+ if(!root){
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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)
+ */
+ 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()
+ */
+ public void test_locale() {
+ Formatter f = null;
+ f = new Formatter((Locale) null);
+ assertNull(f.locale());
+
+ f.close();
+ try {
+ f.locale();
+ fail("should throw FormatterClosedException");
+ } catch (FormatterClosedException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.util.Formatter#out()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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
+ */
+ 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
+ */
+ 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
+ */
+ 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
+ */
+ 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
+ */
+ 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
+ */
+ 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);
+ 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
+ */
+ 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
+ */
+ 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'
+ */
+ 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'
+ */
+ 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
+ */
+ 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
+ */
+ 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
+ */
+ 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'
+ */
+ 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'
+ */
+ 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'
+ */
+ 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
+ */
+ 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 GMT+08:00 1970"}, //$NON-NLS-2$
+ {Long.MAX_VALUE, 'c', "So. Aug 17 15:18:47 GMT+08:00 292278994"}, //$NON-NLS-2$
+ {-1000L, 'c', "Do. Jan 01 07:59:59 GMT+08:00 1970"}, //$NON-NLS-2$
+ {new Date(1147327147578L), 'c', "Do. Mai 11 13:59:07 GMT+08:00 2006"}, //$NON-NLS-2$
+ {paris, 'c', "Mo. Mai 08 12:00:00 MESZ 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', "vorm."}, //$NON-NLS-2$
+ {Long.MAX_VALUE, 'p', "nachm."}, //$NON-NLS-2$
+ {-1000L, 'p', "vorm."}, //$NON-NLS-2$
+ {new Date(1147327147578L), 'p', "nachm."}, //$NON-NLS-2$
+ {paris, 'p', "nachm."}, //$NON-NLS-2$
+ {china, 'p', "nachm."}, //$NON-NLS-2$
+ {0L, 'r', "08:00:00 vorm."}, //$NON-NLS-2$
+ {Long.MAX_VALUE, 'r', "03:18:47 nachm."}, //$NON-NLS-2$
+ {-1000L, 'r', "07:59:59 vorm."}, //$NON-NLS-2$
+ {new Date(1147327147578L), 'r', "01:59:07 nachm."}, //$NON-NLS-2$
+ {paris, 'r', "12:00:00 nachm."}, //$NON-NLS-2$
+ {china, 'r', "12:00:00 nachm."}, //$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 UTC+08:00 1970"}, //$NON-NLS-2$
+ {Long.MAX_VALUE, 'c', "dim. ao\u00fbt 17 15:18:47 UTC+08:00 292278994"}, //$NON-NLS-2$
+ {-1000L, 'c', "jeu. janv. 01 07:59:59 UTC+08:00 1970"}, //$NON-NLS-2$
+ {new Date(1147327147578L), 'c', "jeu. mai 11 13:59:07 UTC+08:00 2006"}, //$NON-NLS-2$
+ {paris, 'c', "lun. mai 08 12:00:00 HAEC 2006"}, //$NON-NLS-2$
+ {china, 'c', "lun. mai 08 12:00:00 UTC-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:18:47 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\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', "\u6728 1\u6708 01 08:00:00 GMT+08:00 1970"}, //$NON-NLS-2$
+ {Long.MAX_VALUE, 'c', "\u65e5 8\u6708 17 15:18:47 GMT+08:00 292278994"}, //$NON-NLS-2$
+ {-1000L, 'c', "\u6728 1\u6708 01 07:59:59 GMT+08:00 1970"}, //$NON-NLS-2$
+ {new Date(1147327147578L), 'c', "\u6728 5\u6708 11 13:59:07 GMT+08:00 2006"}, //$NON-NLS-2$
+ {paris, 'c', "\u6708 5\u6708 08 12:00:00 GMT+02:00 2006"}, //$NON-NLS-2$
+ {china, 'c', "\u6708 5\u6708 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\u6708"}, //$NON-NLS-2$
+ {Long.MAX_VALUE, 'h', "8\u6708"}, //$NON-NLS-2$
+ {-1000L, 'h', "1\u6708"}, //$NON-NLS-2$
+ {new Date(1147327147578L), 'h', "5\u6708"}, //$NON-NLS-2$
+ {paris, 'h', "5\u6708"}, //$NON-NLS-2$
+ {china, 'h', "5\u6708"}, //$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:18:47 \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][input], //$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', "18"}, //$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:18"}, //$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', "47"}, //$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:18:47"}, //$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', "18"}, //$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:18"}, //$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', "47"}, //$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:18:47"}, //$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', "18"}, //$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:18"}, //$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', "47"}, //$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:18:47"}, //$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
+ */
+ 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'
+ */
+ 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
+ */
+ 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
+ */
+ 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
+ */
+ 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'
+ */
+ 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'
+ */
+ 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
+ */
+ 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'
+ */
+ 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'
+ */
+ 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'
+ */
+ 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'
+ */
+ 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'
+ */
+ 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'
+ */
+ 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
+ */
+ 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
+ */
+ 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
+ */
+ 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());
+ }
+
+ /**
* @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]);
+ 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);
+ }
+
+ /*
+ * Regression test for Harmony-5845
+ * test the short name for timezone whether uses DaylightTime or not
+ */
+ public void test_DaylightTime() {
+ Calendar c1 = new GregorianCalendar(2007, 0, 1);
+ Calendar c2 = new GregorianCalendar(2007, 7, 1);
- try {
- decFloat = BigDecimalLayoutForm.valueOf("Wrong format");
- fail("IllegalArgumentException expected");
- } catch (IllegalArgumentException e) {
- //expected
+ for (String tz : TimeZone.getAvailableIDs()) {
+ if (tz.equals("America/Los_Angeles")) {
+ c1.setTimeZone(TimeZone.getTimeZone(tz));
+ c2.setTimeZone(TimeZone.getTimeZone(tz));
+ assertTrue(String.format("%1$tZ%2$tZ", c1, c2).equals("PSTPDT"));
+ }
+ if (tz.equals("America/Panama")) {
+ c1.setTimeZone(TimeZone.getTimeZone(tz));
+ c2.setTimeZone(TimeZone.getTimeZone(tz));
+ assertTrue(String.format("%1$tZ%2$tZ", c1, c2).equals("ESTEST"));
+ }
+ }
+ }
+
+ /*
+ * Regression test for Harmony-5845
+ * test scientific notation to follow RI's behavior
+ */
+ public void test_ScientificNotation() {
+ Formatter f = new Formatter();
+ MathContext mc = new MathContext(30);
+ BigDecimal value = new BigDecimal(0.1, mc);
+ f.format("%.30G", value);
+
+ String result = f.toString();
+ String expected = "0.100000000000000005551115123126";
+ assertEquals(expected, result);
+ }
+
+
+ /**
+ * Setup resource files for testing
+ */
+ protected void setUp() throws IOException {
+ root = System.getProperty("user.name").equalsIgnoreCase("root");
+ 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/org/apache/harmony/luni/tests/java/util/HashMapTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/HashMapTest.java
index 56ba684..39f7216 100644
--- 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
@@ -1,71 +1,754 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+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 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);
+import tests.support.Support_MapTest2;
+import tests.support.Support_UnmodifiableCollectionTest;
+
+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 V put(K key, V value) {
- throw new UnsupportedOperationException();
+ public int size() {
+ return 10;
}
}
+
+ interface MockInterface {
+ public String mockMethod();
+ }
- /**
- * @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() {
+ class MockClass implements MockInterface {
+ public String mockMethod() {
+ return "This is a MockClass";
+ }
+ }
+
+ class MockHandler implements InvocationHandler {
+
+ Object obj;
+
+ public MockHandler(Object o) {
+ obj = o;
+ }
+
+ public Object invoke(Object proxy, Method m, Object[] args)
+ throws Throwable {
+
+ Object result = null;
+
+ try {
+
+ result = m.invoke(obj, args);
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+
+ }
+ return result;
+ }
+
+ }
+
+
+ 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()
+ */
+ 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)
+ */
+ 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);
+ } catch (IllegalArgumentException e) {
+ return;
+ }
+ fail(
+ "Failed to throw IllegalArgumentException for initial capacity < 0");
+
+ 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)
+ */
+ 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);
+ } catch (IllegalArgumentException e) {
+ return;
+ }
+ fail(
+ "Failed to throw IllegalArgumentException for initial load factor <= 0");
+
+ 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)
+ */
+ 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
+ }
+
HashMap map = new HashMap();
map.put("a", "a");
SubMap map2 = new SubMap(map);
assertTrue(map2.containsKey("a"));
assertTrue(map2.containsValue("a"));
+ }
+
+ /**
+ * @tests java.util.HashMap#clear()
+ */
+ public void test_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]));
+
+ // Check clear on a large loaded map of Integer keys
+ HashMap<Integer, String> map = new HashMap<Integer, String>();
+ for (int i = -32767; i < 32768; i++) {
+ map.put(i, "foobar");
+ }
+ map.clear();
+ assertEquals("Failed to reset size on large integer map", 0, hm.size());
+ for (int i = -32767; i < 32768; i++) {
+ assertNull("Failed to clear integer map values", map.get(i));
+ }
+ }
+
+ /**
+ * @tests java.util.HashMap#clone()
+ */
+ 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)
+ */
+ 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)
+ */
+ 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()
+ */
+ 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()));
+ }
+
+ Iterator iter = s.iterator();
+ s.remove(iter.next());
+ assertEquals(1001, s.size());
+ }
+
+ /**
+ * @tests java.util.HashMap#get(java.lang.Object)
+ */
+ 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 for proxy object keys and values
+ */
+ public void test_proxies() {
+ // Regression for HARMONY-6237
+ MockInterface proxyKey = (MockInterface) Proxy.newProxyInstance(
+ MockInterface.class.getClassLoader(),
+ new Class[] { MockInterface.class }, new MockHandler(
+ new MockClass()));
+ MockInterface proxyValue = (MockInterface) Proxy.newProxyInstance(
+ MockInterface.class.getClassLoader(),
+ new Class[] { MockInterface.class }, new MockHandler(
+ new MockClass()));
+
+ // Proxy key
+ Object val = new Object();
+ hm.put(proxyKey, val);
+
+ assertEquals("Failed with proxy object key", val, hm
+ .get(proxyKey));
+ assertTrue("Failed to find proxy key", hm.containsKey(proxyKey));
+ assertEquals("Failed to remove proxy object key", val,
+ hm.remove(proxyKey));
+ assertFalse("Should not have found proxy key", hm.containsKey(proxyKey));
+
+ // Proxy value
+ Object k = new Object();
+ hm.put(k, proxyValue);
+
+ assertTrue("Failed to find proxy object as value", hm.containsValue(proxyValue));
+
+ // Proxy key and value
+ HashMap map = new HashMap();
+ map.put(proxyKey, proxyValue);
+ assertTrue("Failed to find proxy key", map.containsKey(proxyKey));
+ assertEquals(1, map.size());
+ Object[] entries = map.entrySet().toArray();
+ Map.Entry entry = (Map.Entry)entries[0];
+ assertTrue("Failed to find proxy association", map.entrySet().contains(entry));
+ }
+
+ /**
+ * @tests java.util.HashMap#isEmpty()
+ */
+ 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()
+ */
+ 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)
+ */
+ public void test_putLjava_lang_ObjectLjava_lang_Object() {
+ hm.put("KEY", "VALUE");
+ assertEquals("Failed to install key/value pair", "VALUE", hm.get("KEY"));
+
+ HashMap<Object,Object> m = new HashMap<Object,Object>();
+ 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)));
+
+ // Check my actual key instance is returned
+ HashMap<Integer, String> map = new HashMap<Integer, String>();
+ for (int i = -32767; i < 32768; i++) {
+ map.put(i, "foobar");
+ }
+ Integer myKey = new Integer(0);
+ // Put a new value at the old key position
+ map.put(myKey, "myValue");
+ assertTrue(map.containsKey(myKey));
+ assertEquals("myValue", map.get(myKey));
+ boolean found = false;
+ for (Iterator<Integer> itr = map.keySet().iterator(); itr.hasNext();) {
+ Integer key = itr.next();
+ if (found = key == myKey) {
+ break;
+ }
+ }
+ assertFalse("Should not find new key instance in hashmap", found);
+
+ // Add a new key instance and check it is returned
+ assertNotNull(map.remove(myKey));
+ map.put(myKey, "myValue");
+ assertTrue(map.containsKey(myKey));
+ assertEquals("myValue", map.get(myKey));
+ for (Iterator<Integer> itr = map.keySet().iterator(); itr.hasNext();) {
+ Integer key = itr.next();
+ if (found = key == myKey) {
+ break;
+ }
+ }
+ assertTrue("Did not find new key instance in hashmap", found);
+
+ // Ensure keys with identical hashcode are stored separately
+ HashMap<Object,Object> objmap = new HashMap<Object, Object>();
+ for (int i = 0; i < 32768; i++) {
+ objmap.put(i, "foobar");
+ }
+ // Put non-equal object with same hashcode
+ MyKey aKey = new MyKey();
+ assertNull(objmap.put(aKey, "value"));
+ assertNull(objmap.remove(new MyKey()));
+ assertEquals("foobar", objmap.get(0));
+ assertEquals("value", objmap.get(aKey));
+ }
+
+ static class MyKey {
+ public MyKey() {
+ super();
+ }
+
+ public int hashCode() {
+ return 0;
+ }
+ }
+ /**
+ * @tests java.util.HashMap#putAll(java.util.Map)
+ */
+ 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)
+ */
+ 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)
+ */
+ public void test_removeLjava_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));
+
+ HashMap<Integer, Object> map = new HashMap<Integer, Object>();
+ for (int i = 0; i < 32768; i++) {
+ map.put(i, "const");
+ }
+ Object[] values = new Object[32768];
+ for (int i = 0; i < 32768; i++) {
+ values[i] = new Object();
+ map.put(i, values[i]);
+ }
+ for (int i = 32767; i >= 0; i--) {
+ assertEquals("Failed to remove same value", values[i], map.remove(i));
+ }
+
+ // Ensure keys with identical hashcode are removed properly
+ map = new HashMap<Integer, Object>();
+ for (int i = -32767; i < 32768; i++) {
+ map.put(i, "foobar");
+ }
+ // Remove non equal object with same hashcode
+ assertNull(map.remove(new MyKey()));
+ assertEquals("foobar", map.get(0));
+ map.remove(0);
+ assertNull(map.get(0));
+ }
+
+ /**
+ * @tests java.util.HashMap#size()
+ */
+ 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()
+ */
+ 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)));
+
+ }
+
+ /**
+ * @tests java.util.AbstractMap#toString()
+ */
+ public void test_toString() {
+
+ HashMap m = new HashMap();
+ m.put(m, m);
+ String result = m.toString();
+ assertTrue("should contain self ref", result.indexOf("(this") > -1);
+ }
+
+ 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;
+ }
+ }
+
+ 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);
+ }
+ }
+
+ /*
+ * Regression test for HY-4750
+ */
+ public void test_EntrySet() {
+ HashMap map = new HashMap();
+ map.put(new Integer(1), "ONE");
+
+ Set entrySet = map.entrySet();
+ Iterator e = entrySet.iterator();
+ Object real = e.next();
+ Map.Entry copyEntry = new MockEntry();
+ assertEquals(real, copyEntry);
+ assertTrue(entrySet.contains(copyEntry));
+
+ entrySet.remove(copyEntry);
+ assertFalse(entrySet.contains(copyEntry));
+
+
+ }
+
+ private static class MockEntry implements Map.Entry {
+
+ public Object getKey() {
+ return new Integer(1);
+ }
+
+ public Object getValue() {
+ return "ONE";
+ }
+
+ public Object setValue(Object object) {
+ return null;
+ }
+ }
+
+ /**
+ * 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");
+ }
+
+
+ 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 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");
@@ -80,16 +763,11 @@ public class HashMapTest extends TestCase {
/**
* @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
index 43bb856..83ef5e0 100644
--- 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
@@ -17,11 +17,6 @@
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;
@@ -34,102 +29,69 @@ 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#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)
+ */
+ 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>();
@@ -144,41 +106,29 @@ public class IdentityHashMapTest extends junit.framework.TestCase {
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.IdentityHashMap#remove(java.lang.Object)
+ * @tests java.util.IdentityHashMap#keySet()
+ */
+ 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>();
@@ -195,288 +145,269 @@ public class IdentityHashMapTest extends junit.framework.TestCase {
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#entrySet()
+ * @tests java.util.IdentityHashMap#keySet()
+ * @tests java.util.IdentityHashMap#values()
+ */
+ 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)
+ */
+ 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()
+ */
+ 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()
+ */
+ 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)
+ */
+ 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()
+ */
+ 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)
+ */
+ 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));
+ }
+
+ public void test_clone_scenario1() {
+ IdentityHashMap hashMap = new IdentityHashMap();
+ assertEquals(0, hashMap.hashCode());
+ Object cloneHashMap = hashMap.clone();
+ ((IdentityHashMap) cloneHashMap).put("key", "value");
+ assertEquals(0, hashMap.hashCode());
+ assertTrue(0 != cloneHashMap.hashCode());
}
- /**
- * @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());
+ public void test_clone_scenario2() {
+ IdentityHashMap hashMap = new IdentityHashMap();
+ assertEquals(0, hashMap.hashCode());
+ Object cloneHashMap = hashMap.clone();
+ hashMap.put("key", "value");
+ assertEquals(1, hashMap.size());
+ assertEquals(0, ((IdentityHashMap) cloneHashMap).size());
+ assertEquals("value", hashMap.get("key"));
+ assertNull(((IdentityHashMap) cloneHashMap).get("key"));
+ assertTrue(0 != hashMap.hashCode());
+ assertEquals(0, cloneHashMap.hashCode());
}
- /**
- * @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());
+ public void test_clone_scenario3() {
+ IdentityHashMap hashMap = new IdentityHashMap();
+ assertEquals(0, hashMap.hashCode());
+ hashMap.put("key", "value");
+ Object cloneHashMap = hashMap.clone();
+ assertEquals(1, hashMap.size());
+ assertEquals(1, ((IdentityHashMap) cloneHashMap).size());
+ assertEquals("value", hashMap.get("key"));
+ assertEquals("value", ((IdentityHashMap) cloneHashMap).get("key"));
+ assertEquals(hashMap.hashCode(), cloneHashMap.hashCode());
}
- /**
- * @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());
+ public void test_clone_scenario4() {
+ IdentityHashMap hashMap = new IdentityHashMap();
+ Object cloneHashMap = hashMap.clone();
+ assertNull(((IdentityHashMap) cloneHashMap).get((Object) null));
+ hashMap.put((Object) null, cloneHashMap);
+ assertNull(((IdentityHashMap) cloneHashMap).get((Object) null));
+ assertEquals(cloneHashMap, hashMap.get((Object) null));
}
- /**
- * @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));
+ public void test_clone_scenario5() throws Exception {
+ IdentityHashMap hashMap = new IdentityHashMap();
+ Object cloneHashMap = hashMap.clone();
+ assertNull(hashMap.remove((Object) null));
+ ((IdentityHashMap) cloneHashMap).put((Object) null, cloneHashMap);
+ assertNull(hashMap.remove((Object) null));
+ assertEquals(cloneHashMap, ((IdentityHashMap) cloneHashMap)
+ .get((Object) null));
}
// comparator for IdentityHashMap objects
@@ -494,12 +425,6 @@ public class IdentityHashMapTest extends junit.framework.TestCase {
/**
* @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");
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
index 602d1db..7ef9715 100644
--- 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
@@ -16,31 +16,19 @@
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 junit.framework.TestCase;
+
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);
@@ -50,12 +38,6 @@ public class IllegalFormatCodePointExceptionTest extends TestCase {
/**
* @tests java.util.IllegalFormatCodePointException.getCodePoint()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCodePoint",
- args = {}
- )
public void test_getCodePoint() {
int codePoint = 12345;
IllegalFormatCodePointException illegalFormatCodePointException = new IllegalFormatCodePointException(
@@ -66,12 +48,6 @@ public class IllegalFormatCodePointExceptionTest extends TestCase {
/**
* @tests java.util.IllegalFormatCodePointException.getMessage()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
public void test_getMessage() {
int codePoint = 12345;
IllegalFormatCodePointException illegalFormatCodePointException = new IllegalFormatCodePointException(
@@ -98,12 +74,6 @@ public class IllegalFormatCodePointExceptionTest extends TestCase {
/**
* @tests serialization/deserialization.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(
@@ -113,12 +83,6 @@ public class IllegalFormatCodePointExceptionTest extends TestCase {
/**
* @tests serialization/deserialization compatibility with RI.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
public void testSerializationCompatibility() throws Exception {
SerializationTest.verifyGolden(this,
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
index 22a845d..4d5c37d 100644
--- 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
@@ -16,32 +16,20 @@
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 junit.framework.TestCase;
+
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);
@@ -49,19 +37,11 @@ public class IllegalFormatConversionExceptionTest extends TestCase {
} 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;
@@ -75,12 +55,6 @@ public class IllegalFormatConversionExceptionTest extends TestCase {
/**
* @tests java.util.IllegalFormatConversionException#getConversion()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getConversion",
- args = {}
- )
public void test_getConversion() {
char c = '*';
Class<String> argClass = String.class;
@@ -93,12 +67,6 @@ public class IllegalFormatConversionExceptionTest extends TestCase {
/**
* @tests java.util.IllegalFormatConversionException#getMessage()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
public void test_getMessage() {
char c = '*';
Class<String> argClass = String.class;
@@ -129,12 +97,6 @@ public class IllegalFormatConversionExceptionTest extends TestCase {
/**
* @tests serialization/deserialization.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(new IllegalFormatConversionException('*',
@@ -144,12 +106,6 @@ public class IllegalFormatConversionExceptionTest extends TestCase {
/**
* @tests serialization/deserialization compatibility with RI.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
public void testSerializationCompatibility() throws Exception {
SerializationTest.verifyGolden(this,
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
index 8ae825c..530f281 100644
--- 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
@@ -16,31 +16,19 @@
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 junit.framework.TestCase;
+
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);
@@ -48,19 +36,11 @@ public class IllegalFormatFlagsExceptionTest extends TestCase {
} 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(
@@ -71,12 +51,6 @@ public class IllegalFormatFlagsExceptionTest extends TestCase {
/**
* @tests java.util.IllegalFormatFlagsException.getMessage()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
public void test_getMessage() {
String flags = "TESTFLAGS";
IllegalFormatFlagsException illegalFormatFlagsException = new IllegalFormatFlagsException(
@@ -103,12 +77,6 @@ public class IllegalFormatFlagsExceptionTest extends TestCase {
/**
* @tests serialization/deserialization.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(new IllegalFormatFlagsException(
@@ -118,12 +86,6 @@ public class IllegalFormatFlagsExceptionTest extends TestCase {
/**
* @tests serialization/deserialization compatibility with RI.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
public void testSerializationCompatibility() throws Exception {
SerializationTest.verifyGolden(this, new IllegalFormatFlagsException(
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
index 823473e..f7c60ea 100644
--- 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
@@ -15,31 +15,19 @@
*/
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 junit.framework.TestCase;
+
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);
@@ -50,12 +38,6 @@ public class IllegalFormatPrecisionExceptionTest extends TestCase {
/**
* @tests java.util.IllegalFormatPrecisionException#getPrecision()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPrecision",
- args = {}
- )
public void test_getPrecision() {
int precision = 12345;
IllegalFormatPrecisionException illegalFormatPrecisionException = new IllegalFormatPrecisionException(
@@ -66,12 +48,6 @@ public class IllegalFormatPrecisionExceptionTest extends TestCase {
/**
* @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(
@@ -99,12 +75,6 @@ public class IllegalFormatPrecisionExceptionTest extends TestCase {
/**
* @tests serialization/deserialization.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(
@@ -114,12 +84,6 @@ public class IllegalFormatPrecisionExceptionTest extends TestCase {
/**
* @tests serialization/deserialization compatibility with RI.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
public void testSerializationCompatibility() throws Exception {
SerializationTest.verifyGolden(this,
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
index 6885a4e..4262aa0 100644
--- 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
@@ -15,31 +15,19 @@
*/
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 junit.framework.TestCase;
+
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(
@@ -51,12 +39,6 @@ public class IllegalFormatWidthExceptionTest extends TestCase {
/**
* @tests java.util.IllegalFormatWidthException#getWidth()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getWidth",
- args = {}
- )
public void test_getWidth() {
int width = 12345;
IllegalFormatWidthException illegalFormatWidthException = new IllegalFormatWidthException(
@@ -68,12 +50,6 @@ public class IllegalFormatWidthExceptionTest extends TestCase {
/**
* @tests java.util.IllegalFormatWidthException#getMessage()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
public void test_getMessage() {
int width = 12345;
IllegalFormatWidthException illegalFormatWidthException = new IllegalFormatWidthException(
@@ -100,12 +76,6 @@ public class IllegalFormatWidthExceptionTest extends TestCase {
/**
* @tests serialization/deserialization.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(new IllegalFormatWidthException(12345),
@@ -115,12 +85,6 @@ public class IllegalFormatWidthExceptionTest extends TestCase {
/**
* @tests serialization/deserialization compatibility with RI.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
public void testSerializationCompatibility() throws Exception {
SerializationTest.verifyGolden(this, new IllegalFormatWidthException(
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
index e14987e..60c5dc7 100644
--- 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
@@ -15,20 +15,14 @@
*/
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 junit.framework.TestCase;
+
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$
@@ -36,12 +30,6 @@ public class InputMismatchExceptionTest extends TestCase {
/**
* @tests java.util.InputMismatchException#InputMismatchException()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InputMismatchException",
- args = {}
- )
@SuppressWarnings("cast")
public void test_Constructor() {
InputMismatchException exception = new InputMismatchException();
@@ -53,12 +41,6 @@ public class InputMismatchExceptionTest extends TestCase {
/**
* @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);
@@ -69,12 +51,6 @@ public class InputMismatchExceptionTest extends TestCase {
/**
* @tests serialization/deserialization.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(new InputMismatchException(ERROR_MESSAGE));
@@ -83,12 +59,6 @@ public class InputMismatchExceptionTest extends TestCase {
/**
* @tests serialization/deserialization compatibility with RI.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
public void testSerializationCompatibility() throws Exception {
SerializationTest.verifyGolden(this, new InputMismatchException(
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
index 0996a24..63ab11e 100644
--- 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
@@ -1,53 +1,50 @@
-/*
- * 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
- *
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.NotSerializableException;
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));
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class InvalidPropertiesFormatExceptionTest extends
+ junit.framework.TestCase {
+
+ /**
+ * @tests java.util.InvalidPropertiesFormatException#SerializationTest()
+ */
+ public void test_Serialization() throws Exception {
+ InvalidPropertiesFormatException ipfe = new InvalidPropertiesFormatException(
+ "Hey, this is InvalidPropertiesFormatException");
+ try {
+ SerializationTest.verifySelf(ipfe);
+ } catch (NotSerializableException e) {
+ // expected
+ }
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "InvalidPropertiesFormatException",
- args = {java.lang.String.class}
- )
- public void testInvalidPropertiesFormatExceptionString() {
- assertNotNull(new InvalidPropertiesFormatException("String"));
- assertNotNull(new InvalidPropertiesFormatException((String)null));
+ /**
+ * @tests {@link java.util.InvalidPropertiesFormatException#InvalidPropertiesFormatException(Throwable)}
+ */
+ public void test_Constructor_Ljava_lang_Throwable() {
+ Throwable throwable = new Throwable();
+ InvalidPropertiesFormatException exception = new InvalidPropertiesFormatException(
+ throwable);
+ assertEquals("the casue did not equals argument passed in constructor",
+ throwable, exception.getCause());
}
}
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
index 5acb81c..1abfc49 100644
--- 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
@@ -1,49 +1,408 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
-import junit.framework.TestCase;
+public class LocaleTest extends junit.framework.TestCase {
-import java.util.Locale;
+ Locale testLocale;
+
+ Locale l;
+
+ Locale defaultLocale;
+
+ /**
+ * @tests java.util.Locale#Locale(java.lang.String, java.lang.String)
+ */
+ 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(""));
+ }
+
+ /**
+ * @tests java.util.Locale#Locale(java.lang.String, java.lang.String,
+ * java.lang.String)
+ */
+ 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) {
+ }
-@TestTargetClass(Locale.class)
-public class LocaleTest extends TestCase {
+ 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()
+ */
+ 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)
+ */
+ 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() {
+ // Test for method java.util.Locale []
+ // java.util.Locale.getAvailableLocales()
+ // Assumes there will generally be about 100+ available locales...
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
+ assertTrue("Wrong number of locales: ", locales.length > 100);
+ // regression test for HARMONY-1514
+ // HashSet can filter duplicate locales
+ Set<Locale> localesSet = new HashSet<Locale>(Arrays.asList(locales));
+ // Non-bug difference for HARMONY-5442
+ assertTrue(localesSet.size() <= locales.length);
}
+
+ /**
+ * @tests java.util.Locale#getCountry()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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
+ // Non-bug difference for HARMONY-5442
+ Locale l_countryCD = new Locale("", "CD"); //$NON-NLS-1$ //$NON-NLS-2$
+ assertEquals("Congo - Kinshasa", //$NON-NLS-1$
+ l_countryCD.getDisplayCountry());
+ }
+
+ /**
+ * @tests java.util.Locale#getDisplayCountry(java.util.Locale)
+ */
+ 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()
+ */
+ 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$
+
+ // Regression for HARMONY-4402
+ Locale defaultLocale = Locale.getDefault();
+ try {
+ Locale locale = new Locale("no", "NO");
+ Locale.setDefault(locale);
+ assertEquals("norsk", locale.getDisplayLanguage()); //$NON-NLS-1$
+ } finally {
+ Locale.setDefault(defaultLocale);
+ }
+ }
+
+ /**
+ * @tests java.util.Locale#getDisplayLanguage(java.util.Locale)
+ */
+ 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()
+ */
+ 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)
+ */
+ 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()
+ */
+ 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)
+ */
+ 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()
+ */
+ 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());
+ }
+
+ /**
+ * @tests java.util.Locale#getISO3Language()
+ */
+ 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
+
+ // Non-bug difference for HARMONY-5442
+ 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$
+ }
+
+ /**
+ * @tests java.util.Locale#getISOCountries()
+ */
+ 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()
+ */
+ 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;
+
+ // Non-bug difference for HARMONY-5442
+ assertTrue(isoLang[length / 2].length() == 3);
+ assertTrue(isoLang[length / 2].toLowerCase().equals(isoLang[length / 2]));
+ assertTrue("Wrong number of ISOLanguages.", length > 130);
+ }
+
+ /**
+ * @tests java.util.Locale#getLanguage()
+ */
+ 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()
+ */
+ public void test_getVariant() {
+ // Test for method java.lang.String java.util.Locale.getVariant()
+ assertTrue("Returned incorrect variant: " + testLocale.getVariant(),
+ testLocale.getVariant().equals("WIN32"));
+ }
+
+ /**
+ * @tests java.util.Locale#setDefault(java.util.Locale)
+ */
+ 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);
+ }
+
+ /**
+ * @tests java.util.Locale#toString()
+ */
+ 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());
+
+ // Non-bug difference for HARMONY-5442
+ 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());
+
+ }
+
+ // 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"));
+
+ // Non-bug difference for HARMONY-5442
+ List<String> countries = Arrays.asList(Locale.getISOCountries());
+ assertFalse(countries.contains("CS"));
+ }
+
+ /**
+ * 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/org/apache/harmony/luni/tests/java/util/MissingFormatArgumentExceptionTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/MissingFormatArgumentExceptionTest.java
index d93b069..705b597 100644
--- 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
@@ -16,33 +16,20 @@
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 junit.framework.TestCase;
+
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);
@@ -55,12 +42,6 @@ public class MissingFormatArgumentExceptionTest extends TestCase {
/**
* @tests java.util.MissingFormatArgumentException#getFormatSpecifier()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFormatSpecifier",
- args = {}
- )
public void test_getFormatSpecifier() {
String s = "MYTESTSTRING";
MissingFormatArgumentException missingFormatArgumentException = new MissingFormatArgumentException(
@@ -71,12 +52,6 @@ public class MissingFormatArgumentExceptionTest extends TestCase {
/**
* @tests java.util.MissingFormatArgumentException#getMessage()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
public void test_getMessage() {
String s = "MYTESTSTRING";
MissingFormatArgumentException missingFormatArgumentException = new MissingFormatArgumentException(
@@ -104,12 +79,6 @@ public class MissingFormatArgumentExceptionTest extends TestCase {
/**
* @tests serialization/deserialization.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(new MissingFormatArgumentException(
@@ -119,12 +88,6 @@ public class MissingFormatArgumentExceptionTest extends TestCase {
/**
* @tests serialization/deserialization compatibility with RI.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
public void testSerializationCompatibility() throws Exception {
SerializationTest.verifyGolden(this,
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
index be94d1c..81fa2d7 100644
--- 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
@@ -15,33 +15,20 @@
*/
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 junit.framework.TestCase;
+
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");
@@ -53,12 +40,6 @@ public class MissingFormatWidthExceptionTest extends TestCase {
/**
* @tests java.util.MissingFormatWidthException#getFormatSpecifier()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFormatSpecifier",
- args = {}
- )
public void test_getFormatSpecifier() {
String s = "MYTESTSTRING";
MissingFormatWidthException missingFormatWidthException = new MissingFormatWidthException(
@@ -70,12 +51,6 @@ public class MissingFormatWidthExceptionTest extends TestCase {
/**
* @tests java.util.MissingFormatWidthException#getMessage()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
public void test_getMessage() {
String s = "MYTESTSTRING";
MissingFormatWidthException missingFormatWidthException = new MissingFormatWidthException(
@@ -103,12 +78,6 @@ public class MissingFormatWidthExceptionTest extends TestCase {
/**
* @tests serialization/deserialization.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(new MissingFormatWidthException(
@@ -118,12 +87,6 @@ public class MissingFormatWidthExceptionTest extends TestCase {
/**
* @tests serialization/deserialization compatibility with RI.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
public void testSerializationCompatibility() throws Exception {
SerializationTest.verifyGolden(this, new MissingFormatWidthException(
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
index 562da42..d8f4cc4 100644
--- 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
@@ -17,30 +17,18 @@
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)
+import junit.framework.TestCase;
+
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() {
+ public void test_ConstructorJJ() {
UUID uuid = new UUID(0xf81d4fae7dec11d0L, 0xa76500a0c91e6bf6L);
assertEquals(2, uuid.variant());
assertEquals(1, uuid.version());
@@ -53,12 +41,6 @@ public class UUIDTest extends TestCase {
/**
* @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());
@@ -71,12 +53,6 @@ public class UUIDTest extends TestCase {
/**
* @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());
@@ -89,12 +65,6 @@ public class UUIDTest extends TestCase {
/**
* @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());
@@ -113,12 +83,6 @@ public class UUIDTest extends TestCase {
/**
* @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());
@@ -152,12 +116,6 @@ public class UUIDTest extends TestCase {
/**
* @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());
@@ -181,12 +139,6 @@ public class UUIDTest extends TestCase {
/**
* @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());
@@ -213,12 +165,6 @@ public class UUIDTest extends TestCase {
/**
* @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());
@@ -242,12 +188,6 @@ public class UUIDTest extends TestCase {
/**
* @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));
@@ -263,12 +203,6 @@ public class UUIDTest extends TestCase {
/**
* @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());
@@ -280,12 +214,6 @@ public class UUIDTest extends TestCase {
/**
* @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);
@@ -308,12 +236,6 @@ public class UUIDTest extends TestCase {
/**
* @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();
@@ -327,12 +249,6 @@ public class UUIDTest extends TestCase {
/**
* @tests serialization/deserialization.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(new UUID(0xf81d4fae7dec11d0L,
0xa76500a0c91e6bf6L));
@@ -341,12 +257,6 @@ public class UUIDTest extends TestCase {
/**
* @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));
@@ -355,12 +265,6 @@ public class UUIDTest extends TestCase {
/**
* @see UUID#randomUUID()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "randomUUID",
- args = {}
- )
public void test_randomUUID() {
UUID uuid = UUID.randomUUID();
assertEquals(2, uuid.variant());
@@ -370,12 +274,6 @@ public class UUIDTest extends TestCase {
/**
* @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,
@@ -406,12 +304,6 @@ public class UUIDTest extends TestCase {
/**
* @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);
@@ -464,108 +356,102 @@ public class UUIDTest extends TestCase {
} 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
- }
- }
+ /**
+ * @tests java.util.UUID#fromString(String)
+ */
+ 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
index 14ed171..262db4d 100644
--- 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
@@ -15,31 +15,19 @@
*/
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 junit.framework.TestCase;
+
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
@@ -54,12 +42,6 @@ public class UnknownFormatConversionExceptionTest extends TestCase {
/**
* @tests java.util.UnknownFormatConversionException#getConversion()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getConversion",
- args = {}
- )
public void test_getConversion() {
String s = "MYTESTSTRING";
UnknownFormatConversionException UnknownFormatConversionException = new UnknownFormatConversionException(
@@ -70,12 +52,6 @@ public class UnknownFormatConversionExceptionTest extends TestCase {
/**
* @tests java.util.UnknownFormatConversionException#getMessage()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
public void test_getMessage() {
String s = "MYTESTSTRING";
UnknownFormatConversionException UnknownFormatConversionException = new UnknownFormatConversionException(
@@ -102,12 +78,6 @@ public class UnknownFormatConversionExceptionTest extends TestCase {
/**
* @tests serialization/deserialization.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(new UnknownFormatConversionException(
@@ -117,12 +87,6 @@ public class UnknownFormatConversionExceptionTest extends TestCase {
/**
* @tests serialization/deserialization compatibility with RI.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
public void testSerializationCompatibility() throws Exception {
SerializationTest.verifyGolden(this,
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
index c14cdee..3221cc5 100644
--- 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
@@ -16,31 +16,19 @@
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 junit.framework.TestCase;
+
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 {
@@ -49,18 +37,11 @@ public class UnknownFormatFlagsExceptionTest extends TestCase {
} 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(
@@ -71,12 +52,6 @@ public class UnknownFormatFlagsExceptionTest extends TestCase {
/**
* @tests java.util.UnknownFormatFlagsException#getMessage()
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
public void test_getMessage() {
String s = "MYTESTSTRING";
UnknownFormatFlagsException UnknownFormatFlagsException = new UnknownFormatFlagsException(
@@ -102,12 +77,6 @@ public class UnknownFormatFlagsExceptionTest extends TestCase {
/**
* @tests serialization/deserialization.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationSelf",
- args = {}
- )
public void testSerializationSelf() throws Exception {
SerializationTest.verifySelf(new UnknownFormatFlagsException(
@@ -117,12 +86,6 @@ public class UnknownFormatFlagsExceptionTest extends TestCase {
/**
* @tests serialization/deserialization compatibility with RI.
*/
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!SerializationGolden",
- args = {}
- )
public void testSerializationCompatibility() throws Exception {
SerializationTest.verifyGolden(this, new UnknownFormatFlagsException(
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
index 18cb550..82592b1 100644
--- 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
@@ -1,42 +1,1230 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.Arrays;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Vector;
-import junit.framework.TestCase;
+import tests.support.Support_ListTest;
-import java.util.Vector;
+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()
+ */
+ 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)
+ */
+ 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());
+ }
+
+ /**
+ * @tests java.util.Vector#Vector(int, int)
+ */
+ 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());
+
+ Vector emptyVector = new Vector(0, 0);
+ emptyVector.addElement("one");
+ assertEquals("Wrong size", 1, emptyVector.size());
+ emptyVector.addElement("two");
+ emptyVector.addElement("three");
+ assertEquals("Wrong size", 3, emptyVector.size());
+
+ try {
+ Vector negativeVector = new Vector(-1, 0);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * @tests java.util.Vector#Vector(java.util.Collection)
+ */
+ 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)));
+ }
+
+ /**
+ * @tests java.util.Vector#add(int, java.lang.Object)
+ */
+ 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());
+ }
+
+ /**
+ * @tests java.util.Vector#add(java.lang.Object)
+ */
+ 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)
+ */
+ 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 {
+ v.addAll(0, null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Excepted
+ }
+
+ try {
+ v.addAll(-1, null);
+ fail("Should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * @tests java.util.Vector#addAll(java.util.Collection)
+ */
+ 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 {
+ v.addAll(null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * @tests java.util.Vector#addElement(java.lang.Object)
+ */
+ 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)
+ */
+ 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()
+ */
+ 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()
+ */
+ 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()
+ */
+ 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)
+ */
+ 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)
+ */
+ 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));
+ }
+
+ /**
+ * @tests java.util.Vector#copyInto(java.lang.Object[])
+ */
+ 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));
+ }
+
+ /**
+ * @tests java.util.Vector#elementAt(int)
+ */
+ 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));
+
+ }
+
+ /**
+ * @tests java.util.Vector#elements()
+ */
+ 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()
+ */
+ 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)
+ */
+ 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());
+
+ v.ensureCapacity(150);
+ assertEquals(
+ "ensuieCapacity failed to set to be twice the old capacity",
+ 200, v.capacity());
+
+ v = new Vector(9, -1);
+ v.ensureCapacity(20);
+ assertEquals("ensureCapacity failed to set to be minCapacity", 20, v
+ .capacity());
+ v.ensureCapacity(15);
+ assertEquals("ensureCapacity reduced capacity", 20, v.capacity());
+ v.ensureCapacity(35);
+ assertEquals(
+ "ensuieCapacity failed to set to be twice the old capacity",
+ 40, v.capacity());
+
+ v = new Vector(9, 4);
+ v.ensureCapacity(11);
+ assertEquals("ensureCapacity failed to set correct capacity", 13, v
+ .capacity());
+ v.ensureCapacity(5);
+ assertEquals("ensureCapacity reduced capacity", 13, v.capacity());
+ v.ensureCapacity(20);
+ assertEquals(
+ "ensuieCapacity failed to set to be twice the old capacity",
+ 20, v.capacity());
+ }
+
+ /**
+ * @tests java.util.Vector#equals(java.lang.Object)
+ */
+ 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));
+ assertTrue("e) Equal vectors returned false", tVector.equals(tVector));
+ assertFalse("f) UnEqual vectors returned true", tVector
+ .equals(new Object()));
+ assertFalse("g) Unequal vectors returned true", tVector.equals(null));
+ }
+
+ /**
+ * @tests java.util.Vector#firstElement()
+ */
+ 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());
+
+ Vector v = new Vector();
+ try {
+ v.firstElement();
+ fail("Should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * @tests java.util.Vector#get(int)
+ */
+ 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));
+ }
+
+ /**
+ * @tests java.util.Vector#hashCode()
+ */
+ 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)
+ */
+ 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)
+ */
+ public void test_indexOfLjava_lang_ObjectI() {
+ // Test for method int java.util.Vector.indexOf(java.lang.Object, int)
+ assertEquals("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("Test 98", -1);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+
+ }
+ assertEquals(-1, tVector.indexOf("Test 98", 1000));
+ assertEquals(-1, tVector.indexOf("Test 98", Integer.MAX_VALUE));
+ assertEquals(-1, tVector.indexOf("Test 98", tVector.size()));
+ assertEquals(98, tVector.indexOf("Test 98", 0));
+ try {
+ tVector.indexOf("Test 98", Integer.MIN_VALUE);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+
+ }
+ }
+
+ /**
+ * @tests java.util.Vector#insertElementAt(java.lang.Object, int)
+ */
+ 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("Inserted Element", -1);
+ fail("Should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Excepted
+ }
+
+ try {
+ tVector.insertElementAt(null, -1);
+ fail("Should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Excepted
+ }
+
+ try {
+ tVector.insertElementAt("Inserted Element", tVector.size() + 1);
+ fail("Should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Excepted
+ }
+
+ try {
+ tVector.insertElementAt(null, tVector.size() + 1);
+ fail("Should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * @tests java.util.Vector#isEmpty()
+ */
+ 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()
+ */
+ 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);
+ }
-@TestTargetClass(Vector.class)
-public class VectorTest extends TestCase {
+ /**
+ * @tests java.util.Vector#lastElement()
+ */
+ 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());
+
+ Vector vector = new Vector();
+ try {
+ vector.lastElement();
+ fail("Should throw NoSuchElementException");
+ } catch (NoSuchElementException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * @tests java.util.Vector#lastIndexOf(java.lang.Object)
+ */
+ 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)
+ */
+ 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);
+
+ assertEquals(-1, tVector.lastIndexOf("Test 98", -1));
+ assertEquals(-1, tVector.lastIndexOf("Test 98", 0));
+ try {
+ assertEquals(-1, tVector.lastIndexOf("Test 98", 1000));
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ try {
+ assertEquals(-1, tVector.lastIndexOf("Test 98", Integer.MAX_VALUE));
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ try {
+ tVector.lastIndexOf("Test 98", tVector.size());
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ }
+ try {
+ tVector.indexOf("Test 98", Integer.MIN_VALUE);
+ fail("should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ }
+ }
+
+ /**
+ * @tests java.util.Vector#remove(int)
+ */
+ public void test_removeI() {
+ // Test for method java.lang.Object java.util.Vector.remove(int)
+ Object removeElement = tVector.get(36);
+ Object result = tVector.remove(36);
+ assertFalse("Contained element after remove", tVector
+ .contains("Test 36"));
+ assertEquals("Should return the element that was removed",
+ removeElement, result);
+ assertEquals("Failed to decrement size after remove",
+ 99, tVector.size());
+ tVector.add(20, null);
+ removeElement = tVector.get(19);
+ result = tVector.remove(19);
+ assertNull("Didn't move null element over", tVector.get(19));
+ assertEquals("Should return the element that was removed",
+ removeElement, result);
+ removeElement = tVector.get(19);
+ result = tVector.remove(19);
+ assertNotNull("Didn't remove null element", tVector.get(19));
+ assertEquals("Should return the element that was removed",
+ removeElement, result);
+ assertEquals("Failed to decrement size after removing null", 98, tVector
+ .size());
+
+ try {
+ tVector.remove(-1);
+ fail("Should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Excepted
+ }
+
+ try {
+ tVector.remove(tVector.size());
+ fail("Should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * @tests java.util.Vector#remove(java.lang.Object)
+ */
+ 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)
+ */
+ 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());
+ }
+
+ /**
+ * @tests java.util.Vector#removeAllElements()
+ */
+ 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)
+ */
+ 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)
+ */
+ public void test_removeElementAtI() {
+ // Test for method void java.util.Vector.removeElementAt(int)
+ Vector v = vectorClone(tVector);
+ int size = v.size();
+ v.removeElementAt(50);
+ assertEquals("Failed to remove element", -1, v.indexOf("Test 50", 0));
+ assertEquals("Test 51", v.get(50));
+ assertEquals(size - 1, v.size());
+
+ tVector.insertElementAt(null, 60);
+ assertNull(tVector.get(60));
+ size = tVector.size();
+ tVector.removeElementAt(60);
+ assertNotNull("Element at 60 should not be null after removal", tVector
+ .elementAt(60));
+ assertEquals(size - 1, tVector.size());
+
+ try {
+ tVector.removeElementAt(-1);
+ fail("Should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Excepted
+ }
+
+ try {
+ tVector.removeElementAt(tVector.size());
+ fail("Should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * @tests {@link java.util.Vector#removeRange(int, int)}
+ */
+ public void test_removeRange() {
+ MockVector myVector = new MockVector();
+ myVector.removeRange(0, 0);
+
+ try {
+ myVector.removeRange(0, 1);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Excepted
+ }
+
+ int[] data = { 1, 2, 3, 4 };
+ for (int i = 0; i < data.length; i++) {
+ myVector.add(i, data[i]);
+ }
+
+ myVector.removeRange(0, 2);
+ assertEquals(data[2], myVector.get(0));
+ assertEquals(data[3], myVector.get(1));
+
+ try {
+ myVector.removeRange(-1, 1);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Excepted
+ }
+
+ try {
+ myVector.removeRange(0, -1);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Excepted
+ }
+
+ try {
+ myVector.removeRange(1, 0);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Excepted
+ }
+
+ try {
+ myVector.removeRange(2, 1);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * @tests java.util.Vector#retainAll(java.util.Collection)
+ */
+ 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));
+ }
+
+ /**
+ * @tests java.util.Vector#set(int, java.lang.Object)
+ */
+ public void test_setILjava_lang_Object() {
+ // Test for method java.lang.Object java.util.Vector.set(int,
+ // java.lang.Object)
+ Object o = new Object();
+ Object previous = tVector.get(23);
+ Object result = tVector.set(23, o);
+ assertEquals(
+ "Should return the element previously at the specified position",
+ previous, result);
+ assertTrue("Failed to set Object", tVector.get(23) == o);
+
+ previous = tVector.get(0);
+ result = tVector.set(0, null);
+ assertEquals(
+ "Should return the element previously at the specified position",
+ previous, result);
+ assertNull("Failed to set Object", tVector.get(0));
+
+ try {
+ tVector.set(-1, o);
+ fail("Should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Excepted
+ }
+
+ try {
+ tVector.set(-1, null);
+ fail("Should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Excepted
+ }
+
+ try {
+ tVector.set(tVector.size(), o);
+ fail("Should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Excepted
+ }
+
+ try {
+ tVector.set(tVector.size(), null);
+ fail("Should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * @tests java.util.Vector#setElementAt(java.lang.Object, int)
+ */
+ 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))
+ );
+
+ v.setElementAt(null, 0);
+ assertNull("Null element not set", v.elementAt(0));
+
+ try {
+ v.setElementAt("Inserted Element", -1);
+ fail("Should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Excepted
+ }
+
+ try {
+ v.setElementAt(null, -1);
+ fail("Should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Excepted
+ }
+
+ try {
+ v.setElementAt("Inserted Element", v.size());
+ fail("Should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Excepted
+ }
+
+ try {
+ v.setElementAt(null, v.size());
+ fail("Should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * @tests java.util.Vector#setSize(int)
+ */
+ public void test_setSizeI() {
+ // Test for method void java.util.Vector.setSize(int)
+ Vector v = vectorClone(tVector);
+ int oldSize = v.size();
+ Object preElement = v.get(10);
+ v.setSize(10);
+ assertEquals("Failed to set size", 10, v.size());
+ assertEquals(
+ "All components at index newSize and greater should be discarded",
+ -1, v.indexOf(preElement));
+ try {
+ v.get(oldSize - 1);
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Excepted;
+ }
+
+ oldSize = v.size();
+ v.setSize(20);
+ assertEquals("Failed to set size", 20, v.size());
+ for (int i = oldSize; i < v.size(); i++) {
+ assertNull(v.get(i));
+ }
+
+ try {
+ v.setSize(-1);
+ fail("Should throw ArrayIndexOutOfBoundsException");
+ } catch (ArrayIndexOutOfBoundsException e) {
+ // Excepted
+ }
+ }
+
+ /**
+ * @tests java.util.Vector#size()
+ */
+ 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)
+ */
+ 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()
+ );
+
+ }
+
+ /**
+ * @tests java.util.Vector#toArray()
+ */
+ 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[])
+ */
+ 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]);
+ }
+
+
+
+ class SubVector<E> extends Vector<E> {
+
+ private static final long serialVersionUID = 1L;
+
+ public SubVector() {
+ super();
+ }
+
+ public synchronized boolean add(E obj) {
+ super.addElement(obj);
+ return true;
+ }
+
+ public synchronized void addElement(E obj) {
+ super.add(obj);
+ }
+
+ /**
+ * @tests java.util.Vector#add(Object)
+ */
+ @SuppressWarnings("nls")
+ public void test_add() {
+ SubVector<String> subvector = new SubVector<String>();
+ subvector.add("foo");
+ subvector.addElement("bar");
+ assertEquals("Expected two elements in vector", 2, subvector.size());
+ }
+
+ }
/**
* @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);
@@ -44,5 +1232,81 @@ public class VectorTest extends TestCase {
vec.add(new Object());
vec.add(vec);
assertNotNull(vec.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);
+ }
+
+ public void test_override_size() throws Exception {
+ Vector v = new Vector();
+ Vector testv = new MockVector();
+ // though size is overriden, it should passed without exception
+ testv.add(1);
+ testv.add(2);
+ testv.clear();
+
+ testv.add(1);
+ testv.add(2);
+ v.add(1);
+ v.add(2);
+ // RI's bug here
+ assertTrue(testv.equals(v));
}
+
+ /**
+ * @tests java.util.Vector#trimToSize()
+ */
+ 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());
+ }
+
+ protected Vector vectorClone(Vector s) {
+ return (Vector) s.clone();
+ }
+
+ public class MockVector extends Vector{
+ @Override
+ public synchronized int size() {
+ return 0;
+ }
+
+ public void removeRange(int start, int end) {
+ super.removeRange(start, end);
+ }
+ }
+
+ /**
+ * 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/org/apache/harmony/luni/tests/java/util/WeakHashMapTest.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/util/WeakHashMapTest.java
index 9521641..02f0409 100644
--- 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
@@ -1,51 +1,163 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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.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;
-@TestTargetClass(WeakHashMap.class)
-public class WeakHashMapTest extends TestCase {
+import tests.support.Support_MapTest2;
+
+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;
+
Object[] KEY_ARRAY;
Object[] VALUE_ARRAY;
+ /**
+ * @tests java.util.WeakHashMap#WeakHashMap()
+ */
+ 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)
+ */
+ 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");
+ }
+
+ /**
+ * @tests java.util.WeakHashMap#WeakHashMap(int, float)
+ */
+ 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");
+ }
+
+ /**
+ * @tests java.util.WeakHashMap#WeakHashMap(java.util.Map)
+ */
+ public void test_ConstructorLjava_util_Map() {
+ Map mockMap = new MockMap();
+ WeakHashMap map = new WeakHashMap(mockMap);
+ assertEquals("Size should be 0", 0, map.size());
+ }
+
+ /**
+ * @tests java.util.WeakHashMap#clear()
+ */
+ 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)
+ */
+ 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)
+ */
+ 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() {
WeakHashMap<Object, Object> weakMap = new WeakHashMap<Object, Object>();
KEY_ARRAY = new Object[100];
@@ -131,4 +243,240 @@ public class WeakHashMapTest extends TestCase {
assertTrue("Assert 8: iterator not empty", !entrySet.iterator()
.hasNext());
}
+
+ /**
+ * @tests java.util.WeakHashMap#entrySet()
+ */
+ public void test_entrySet_2() {
+ // 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#get(java.lang.Object)
+ */
+ public void test_getLjava_lang_Object() {
+ // Test for method java.lang.Object
+ // java.util.WeakHashMap.get(java.lang.Object)
+ assertTrue("Used to test", true);
+ }
+
+ /**
+ * @tests java.util.WeakHashMap#isEmpty()
+ */
+ 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)
+ */
+ 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)
+ */
+ 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());
+ }
+
+ /**
+ * @tests java.util.WeakHashMap#remove(java.lang.Object)
+ */
+ 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()
+ */
+ public void test_size() {
+ // Test for method int java.util.WeakHashMap.size()
+ assertTrue("Used to test", true);
+ }
+
+ /**
+ * @tests java.util.WeakHashMap#keySet()
+ */
+ 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());
+ }
+
+ /**
+ * Regression test for HARMONY-3883
+ * @tests java.util.WeakHashMap#keySet()
+ */
+ public void test_keySet_hasNext() {
+ WeakHashMap map = new WeakHashMap();
+ ConstantHashClass cl = new ConstantHashClass(2);
+ map.put(new ConstantHashClass(1), null);
+ map.put(cl, null);
+ map.put(new ConstantHashClass(3), null);
+ Iterator iter = map.keySet().iterator();
+ iter.next();
+ iter.next();
+ System.gc();
+ assertFalse("Wrong hasNext() value", iter.hasNext());
+ }
+
+ static class ConstantHashClass {
+ private int id = 0;
+
+ public ConstantHashClass(int id) {
+ this.id = id;
+ }
+
+ public int hashCode() {
+ return 0;
+ }
+
+ public String toString() {
+ return "ConstantHashClass[id=" + id + "]";
+ }
+ }
+
+
+ /**
+ * @tests java.util.WeakHashMap#values()
+ */
+ 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/org/apache/harmony/luni/tests/util/Base64Test.java b/luni/src/test/java/org/apache/harmony/luni/tests/util/Base64Test.java
index 1795745..70318ed 100644
--- 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
@@ -15,12 +15,7 @@
* 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;
+package org.apache.harmony.luni.tests.util;
import org.apache.harmony.luni.util.Base64;
@@ -30,19 +25,12 @@ 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]);
@@ -53,9 +41,5 @@ public class Base64Test extends TestCase {
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/NYITest.java b/luni/src/test/java/org/apache/harmony/luni/tests/util/NYITest.java
index b30501e..2c8d450 100644
--- 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
@@ -17,11 +17,6 @@
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;
@@ -33,16 +28,8 @@ 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");
diff --git a/luni/src/test/java/tests/AllTests.java b/luni/src/test/java/tests/AllTests.java
index 950156e..0eab77e 100644
--- a/luni/src/test/java/tests/AllTests.java
+++ b/luni/src/test/java/tests/AllTests.java
@@ -30,7 +30,7 @@ public class AllTests
}
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite();
+ TestSuite suite = new TestSuite();
// Harmony-written test suites (often with Android tests added in).
suite.addTest(tests.annotation.AllTests.suite());
diff --git a/luni/src/test/java/tests/TestSuiteFactory.java b/luni/src/test/java/tests/TestSuiteFactory.java
deleted file mode 100644
index 98f998c..0000000
--- a/luni/src/test/java/tests/TestSuiteFactory.java
+++ /dev/null
@@ -1,34 +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 junit.framework.TestSuite;
-
-/**
- * This is about to go away...
- */
-public class TestSuiteFactory {
-
- public static TestSuite createTestSuite(String name) {
- return new TestSuite(name);
- }
-
- public static TestSuite createTestSuite() {
- return new TestSuite();
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/io/AllTests.java b/luni/src/test/java/tests/api/java/io/AllTests.java
index 2747ab2..0bc062d 100644
--- a/luni/src/test/java/tests/api/java/io/AllTests.java
+++ b/luni/src/test/java/tests/api/java/io/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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;");
+ TestSuite suite = new TestSuite("All tests for package tests.api.java.io;");
// $JUnit-BEGIN$
suite.addTestSuite(BufferedInputStreamTest.class);
diff --git a/luni/src/test/java/tests/api/java/lang/AllTests.java b/luni/src/test/java/tests/api/java/lang/AllTests.java
index 5a70224..26e313c 100644
--- a/luni/src/test/java/tests/api/java/lang/AllTests.java
+++ b/luni/src/test/java/tests/api/java/lang/AllTests.java
@@ -24,13 +24,8 @@ 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");
+ TestSuite suite = new TestSuite("Test for java.lang");
// $JUnit-BEGIN$
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
index 75b7b9f..a21d3d8 100644
--- a/luni/src/test/java/tests/api/java/lang/ref/AllTests.java
+++ b/luni/src/test/java/tests/api/java/lang/ref/AllTests.java
@@ -24,13 +24,8 @@ 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");
+ TestSuite suite = new TestSuite("Test for java.lang.ref");
// $JUnit-BEGIN$
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
index bba0915..dd427e1 100644
--- a/luni/src/test/java/tests/api/java/lang/reflect/AllTests.java
+++ b/luni/src/test/java/tests/api/java/lang/reflect/AllTests.java
@@ -24,13 +24,8 @@ 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");
+ TestSuite suite = new TestSuite("Test for java.lang.reflect");
// $JUnit-BEGIN$
suite.addTestSuite(AccessibleObjectTest.class);
diff --git a/luni/src/test/java/tests/api/java/net/AllTests.java b/luni/src/test/java/tests/api/java/net/AllTests.java
index 10dd9d8..2d9921d 100644
--- a/luni/src/test/java/tests/api/java/net/AllTests.java
+++ b/luni/src/test/java/tests/api/java/net/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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;");
+ TestSuite suite = new TestSuite("All tests for package tests.api.java.net;");
// $JUnit-BEGIN$
suite.addTestSuite(AuthenticatorRequestorTypeTest.class);
diff --git a/luni/src/test/java/tests/api/java/util/AllTests.java b/luni/src/test/java/tests/api/java/util/AllTests.java
index c2651d9..2d9c422 100644
--- a/luni/src/test/java/tests/api/java/util/AllTests.java
+++ b/luni/src/test/java/tests/api/java/util/AllTests.java
@@ -24,13 +24,8 @@ 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");
+ TestSuite suite = new TestSuite("Test for java.util");
// $JUnit-BEGIN$
suite.addTestSuite(AbstractListTest.class);
diff --git a/luni/src/test/java/tests/luni/AllTestsIo.java b/luni/src/test/java/tests/luni/AllTestsIo.java
index d135244..010916c 100644
--- a/luni/src/test/java/tests/luni/AllTestsIo.java
+++ b/luni/src/test/java/tests/luni/AllTestsIo.java
@@ -31,7 +31,7 @@ public class AllTestsIo
}
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.io");
+ TestSuite suite = new TestSuite("Tests for java.io");
suite.addTest(tests.api.java.io.AllTests.suite());
diff --git a/luni/src/test/java/tests/luni/AllTestsLang.java b/luni/src/test/java/tests/luni/AllTestsLang.java
index 418571e..1a3b240 100644
--- a/luni/src/test/java/tests/luni/AllTestsLang.java
+++ b/luni/src/test/java/tests/luni/AllTestsLang.java
@@ -31,7 +31,7 @@ public class AllTestsLang
}
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.lang");
+ TestSuite suite = new TestSuite("Tests for java.lang");
suite.addTest(org.apache.harmony.luni.tests.java.lang.AllTests.suite());
diff --git a/luni/src/test/java/tests/luni/AllTestsNet.java b/luni/src/test/java/tests/luni/AllTestsNet.java
index c61cb5f..835cfc7 100644
--- a/luni/src/test/java/tests/luni/AllTestsNet.java
+++ b/luni/src/test/java/tests/luni/AllTestsNet.java
@@ -31,7 +31,7 @@ public class AllTestsNet
}
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.net");
+ TestSuite suite = new TestSuite("Tests for java.net");
suite.addTest(org.apache.harmony.luni.tests.java.net.AllTests.suite());
diff --git a/luni/src/test/java/tests/luni/AllTestsUtil.java b/luni/src/test/java/tests/luni/AllTestsUtil.java
index a157a95..102093e 100644
--- a/luni/src/test/java/tests/luni/AllTestsUtil.java
+++ b/luni/src/test/java/tests/luni/AllTestsUtil.java
@@ -31,7 +31,7 @@ public class AllTestsUtil
}
public static final Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.util");
+ TestSuite suite = new TestSuite("Tests for java.util");
suite.addTest(tests.api.java.util.AllTests.suite());
suite.addTest(org.apache.harmony.luni.tests.java.util.AllTests.suite());
diff --git a/math/src/test/java/org/apache/harmony/math/tests/java/math/AllTests.java b/math/src/test/java/org/apache/harmony/math/tests/java/math/AllTests.java
index 318e4b6..21f2ec5 100644
--- a/math/src/test/java/org/apache/harmony/math/tests/java/math/AllTests.java
+++ b/math/src/test/java/org/apache/harmony/math/tests/java/math/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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 org.apache.harmony.tests.java.math;");
+ TestSuite suite = new TestSuite("All tests for package org.apache.harmony.tests.java.math;");
// $JUnit-BEGIN$
suite.addTestSuite(BigDecimalArithmeticTest.class);
diff --git a/math/src/test/java/tests/api/java/math/AllTests.java b/math/src/test/java/tests/api/java/math/AllTests.java
index 483e08a..a3fb664 100644
--- a/math/src/test/java/tests/api/java/math/AllTests.java
+++ b/math/src/test/java/tests/api/java/math/AllTests.java
@@ -23,13 +23,8 @@ import junit.framework.TestSuite;
* Test suite that includes all tests for the Math project.
*/
public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
-
public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.math");
+ TestSuite suite = new TestSuite("Tests for java.math");
// $JUnit-BEGIN$
suite.addTestSuite(BigDecimalTest.class);
suite.addTestSuite(BigIntegerTest.class);
diff --git a/math/src/test/java/tests/math/AllTests.java b/math/src/test/java/tests/math/AllTests.java
index 2773ad6..64fb60d 100644
--- a/math/src/test/java/tests/math/AllTests.java
+++ b/math/src/test/java/tests/math/AllTests.java
@@ -23,13 +23,8 @@ import junit.framework.TestSuite;
* Test suite that includes all tests for the Math project.
*/
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 Math test suites");
+ TestSuite suite = new TestSuite("All Math test suites");
suite.addTest(tests.api.java.math.AllTests.suite());
suite.addTest(org.apache.harmony.math.tests.java.math.AllTests.suite());
diff --git a/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/AllTests.java b/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/AllTests.java
index 6bf13f1..e88de9a 100644
--- a/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/AllTests.java
+++ b/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/AllTests.java
@@ -25,13 +25,8 @@ import junit.framework.TestSuite;
*
*/
public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
-
public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.nio");
+ TestSuite suite = new TestSuite("Tests for java.nio");
//$JUnit-BEGIN$
suite.addTestSuite(BufferOverflowExceptionTest.class);
suite.addTestSuite(BufferUnderflowExceptionTest.class);
diff --git a/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java b/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java
index 069b056..d348c3d 100644
--- a/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java
+++ b/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java
@@ -32,10 +32,6 @@ import junit.framework.TestCase;
@TestTargetClass(ByteOrder.class)
public class ByteOrderTest extends TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run(ByteOrderTest.class);
- }
-
@TestTargetNew(
level = TestLevel.COMPLETE,
notes = "",
diff --git a/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AllTests.java b/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AllTests.java
index 8031c5f..29cd201 100644
--- a/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AllTests.java
+++ b/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AllTests.java
@@ -20,13 +20,8 @@ import junit.framework.Test;
import junit.framework.TestSuite;
public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
-
public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite(AllTests.class.getName());
+ TestSuite suite = new TestSuite(AllTests.class.getName());
//$JUnit-BEGIN$
suite.addTestSuite(AlreadyConnectedExceptionTest.class);
suite.addTestSuite(AsynchronousCloseExceptionTest.class);
diff --git a/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AllTests.java b/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AllTests.java
index 1b5e12e..bd94f8d 100644
--- a/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AllTests.java
+++ b/nio/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AllTests.java
@@ -22,8 +22,7 @@ import junit.framework.TestSuite;
public class AllTests {
public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite(
- "Test for tests.api.java.nio.channels.spi");
+ TestSuite suite = new TestSuite("Test for tests.api.java.nio.channels.spi");
//$JUnit-BEGIN$
suite.addTestSuite(AbstractInterruptibleChannelTest.class);
suite.addTestSuite(AbstractSelectorTest.class);
diff --git a/nio/src/test/java/tests/nio/AllTests.java b/nio/src/test/java/tests/nio/AllTests.java
index ff50aa5..07f0491 100644
--- a/nio/src/test/java/tests/nio/AllTests.java
+++ b/nio/src/test/java/tests/nio/AllTests.java
@@ -23,13 +23,8 @@ import junit.framework.TestSuite;
* Test suite that includes all tests for the Math project.
*/
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 Math test suites");
+ TestSuite suite = new TestSuite("All Math test suites");
// $JUnit-BEGIN$
suite.addTest(org.apache.harmony.nio.tests.java.nio.AllTests.suite());
suite.addTest(org.apache.harmony.nio.tests.java.nio.channels.AllTests.suite());
diff --git a/nio_char/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/AllTests.java b/nio_char/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/AllTests.java
index 2bc537b..9c56d76 100644
--- a/nio_char/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/AllTests.java
+++ b/nio_char/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/AllTests.java
@@ -20,14 +20,8 @@ import junit.framework.Test;
import junit.framework.TestSuite;
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 org.apache.harmony.nio_char.tests.java.nio.charset");
+ TestSuite suite = new TestSuite("Test for org.apache.harmony.nio_char.tests.java.nio.charset");
//$JUnit-BEGIN$
suite.addTestSuite(ASCIICharsetEncoderTest.class);
suite.addTestSuite(CharacterCodingExceptionTest.class);
diff --git a/nio_char/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/spi/AllTests.java b/nio_char/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/spi/AllTests.java
index 3e5f3a9..00ed64b 100644
--- a/nio_char/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/spi/AllTests.java
+++ b/nio_char/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/spi/AllTests.java
@@ -20,14 +20,8 @@ import junit.framework.Test;
import junit.framework.TestSuite;
public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(AllTests.suite());
- }
-
public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite(
- "Suite of tests for the java.nio.charset.spi package.");
+ TestSuite suite = new TestSuite("Suite of tests for the java.nio.charset.spi package.");
// $JUnit-BEGIN$
suite.addTestSuite(CharsetProviderTest.class);
// $JUnit-END$
diff --git a/nio_char/src/test/java/tests/api/java/nio/charset/AllTests.java b/nio_char/src/test/java/tests/api/java/nio/charset/AllTests.java
index f318960..933f341 100644
--- a/nio_char/src/test/java/tests/api/java/nio/charset/AllTests.java
+++ b/nio_char/src/test/java/tests/api/java/nio/charset/AllTests.java
@@ -20,13 +20,8 @@ import junit.framework.Test;
import junit.framework.TestSuite;
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.nio.charset;");
+ TestSuite suite = new TestSuite("All tests for package tests.api.java.nio.charset;");
suite.addTestSuite(CharsetProviderTest.class);
suite.addTestSuite(CharsetTest.class);
diff --git a/nio_char/src/test/java/tests/nio_char/AllTests.java b/nio_char/src/test/java/tests/nio_char/AllTests.java
index 19a003c..4ab9247 100644
--- a/nio_char/src/test/java/tests/nio_char/AllTests.java
+++ b/nio_char/src/test/java/tests/nio_char/AllTests.java
@@ -23,13 +23,8 @@ import junit.framework.TestSuite;
* Test suite that includes all tests for the NIO_Char project.
*/
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 NIO_Char test suites");
+ TestSuite suite = new TestSuite("All NIO_Char test suites");
// $JUnit-BEGIN$
suite.addTest(org.apache.harmony.nio_char.tests.java.nio.charset.AllTests.suite());
suite.addTest(org.apache.harmony.nio_char.tests.java.nio.charset.spi.AllTests.suite());
diff --git a/prefs/src/test/java/org/apache/harmony/prefs/tests/java/util/prefs/AllTests.java b/prefs/src/test/java/org/apache/harmony/prefs/tests/java/util/prefs/AllTests.java
index 29ff362..d2dd841 100644
--- a/prefs/src/test/java/org/apache/harmony/prefs/tests/java/util/prefs/AllTests.java
+++ b/prefs/src/test/java/org/apache/harmony/prefs/tests/java/util/prefs/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*
*/
public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(AllTests.suite());
- }
-
public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Suite for org.apache.harmony.prefs.tests.java.util.prefs");
+ TestSuite suite = new TestSuite("Suite for org.apache.harmony.prefs.tests.java.util.prefs");
// $JUnit-BEGIN$
suite.addTestSuite(NodeChangeListenerTest.class);
suite.addTestSuite(PreferenceChangeListenerTest.class);
diff --git a/prefs/src/test/java/tests/prefs/AllTests.java b/prefs/src/test/java/tests/prefs/AllTests.java
index b3f2ed6..4d99023 100644
--- a/prefs/src/test/java/tests/prefs/AllTests.java
+++ b/prefs/src/test/java/tests/prefs/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*
*/
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 Prefs test suites");
+ TestSuite suite = new TestSuite("All Prefs test suites");
// $JUnit-BEGIN$
suite.addTest(org.apache.harmony.prefs.tests.java.util.prefs.AllTests.suite());
// $JUnit-END$
diff --git a/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/AllTests.java b/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/AllTests.java
index b69c401..55d3bf0 100644
--- a/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/AllTests.java
+++ b/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
* Provides a test suite for java.util.regex package.
*/
public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
-
public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for java.util.regex");
+ TestSuite suite = new TestSuite("Tests for java.util.regex");
//$JUnit-BEGIN$
suite.addTestSuite(Matcher2Test.class);
diff --git a/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/MatcherTest.java b/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/MatcherTest.java
index 5e9137b..adb3bc7 100644
--- a/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/MatcherTest.java
+++ b/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/MatcherTest.java
@@ -1464,8 +1464,4 @@ public class MatcherTest extends TestCase {
assertTrue(pattern.matcher("14pt").matches());
}
- public static void main(String[] args) {
- junit.textui.TestRunner.run(MatcherTest.class);
- }
-
}
diff --git a/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java b/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java
index c21a81d..5b979cf 100644
--- a/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java
+++ b/regex/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java
@@ -2377,10 +2377,6 @@ public void testRestoreFlagsAfterGroup() {
assertTrue(matcher.find());
}
- public static void main(String[] args) {
- junit.textui.TestRunner.run(PatternTest.class);
- }
-
@TestTargetNew(
level = TestLevel.PARTIAL_COMPLETE,
notes = "The test doesn't verify Matcher and should be moved to PatterTest.",
diff --git a/regex/src/test/java/tests/regex/AllTests.java b/regex/src/test/java/tests/regex/AllTests.java
index d590d08..07feebc 100644
--- a/regex/src/test/java/tests/regex/AllTests.java
+++ b/regex/src/test/java/tests/regex/AllTests.java
@@ -23,13 +23,8 @@ import junit.framework.TestSuite;
* Test suite that includes all tests for the regex project.
*/
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 regex test suites");
+ TestSuite suite = new TestSuite("All regex test suites");
// $JUnit-BEGIN$
suite.addTest(org.apache.harmony.regex.tests.java.util.regex.AllTests.suite());
// $JUnit-END$
diff --git a/run-core-tests b/run-core-tests
index 3359dde..ba858f2 100755
--- a/run-core-tests
+++ b/run-core-tests
@@ -25,12 +25,20 @@ tmp=/data/core-tests.tmp
mkdir $tmp
chmod 777 $tmp
+modules="annotation archive concurrent crypto dom icu logging luni-kernel \
+ luni math nio nio_char prefs regex security sql suncompat support \
+ text x-net xml"
+classpath=""
+for module in $modules; do
+ classpath="$classpath:/system/framework/core-tests-$module.jar"
+done
+
exec dalvikvm \
-Duser.name=root \
-Duser.language=en \
-Duser.region=US \
-Djava.io.tmpdir=$tmp \
-Djavax.net.ssl.trustStore=/system/etc/security/cacerts.bks \
- -classpath /system/framework/core-tests.jar \
+ -classpath $classpath \
-Xcheck:jni \
-Xmx64M com.google.coretests.Main "$@"
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/AccessControlExceptionTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/AccessControlExceptionTest.java
index a2008de..9825291 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/AccessControlExceptionTest.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/AccessControlExceptionTest.java
@@ -41,14 +41,6 @@ import junit.framework.TestCase;
public class AccessControlExceptionTest extends TestCase {
/**
- * Entry point for standalone run.
- * @param args command line arguments
- */
- public static void main(String[] args) {
- junit.textui.TestRunner.run(AccessControlExceptionTest.class);
- }
-
- /**
* Tests AccessControlException(String)
*/
@TestTargetNew(
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParameterGenerator1Test.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParameterGenerator1Test.java
index 1ff236a..69c994d 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParameterGenerator1Test.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParameterGenerator1Test.java
@@ -478,10 +478,6 @@ public class AlgorithmParameterGenerator1Test extends TestCase {
} catch (NullPointerException e) {
}
}
-
- public static void main(String args[]) {
- junit.textui.TestRunner.run(AlgorithmParameterGenerator1Test.class);
- }
}
/**
* Additional class to verify AlgorithmParameterGenerator constructor
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParametersSpiTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParametersSpiTest.java
index 5ec3d96..f65cc80 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParametersSpiTest.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParametersSpiTest.java
@@ -126,9 +126,5 @@ public class AlgorithmParametersSpiTest extends TestCase {
}
}
- public static void main(String args[]) {
- junit.textui.TestRunner.run(AlgorithmParametersSpiTest.class);
- }
-
class MyAlgorithmParameterSpec implements AlgorithmParameterSpec {}
}
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/AllTests.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/AllTests.java
index 089a7db..c0d5640 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/AllTests.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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 org.apache.harmony.security.tests.java.security;");
+ TestSuite suite = new TestSuite("All tests for package org.apache.harmony.security.tests.java.security;");
// $JUnit-BEGIN$
suite.addTestSuite(AccessControlException2Test.class);
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/CodeSignerTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/CodeSignerTest.java
index e29d9ac..f94cb27 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/CodeSignerTest.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/CodeSignerTest.java
@@ -41,15 +41,6 @@ import junit.framework.TestCase;
*/
public class CodeSignerTest extends TestCase {
-
- /**
- * Entry point for standalone runs.
- * @param args command line arguments
- */
- public static void main(String[] args) {
- junit.textui.TestRunner.run(CodeSignerTest.class);
- }
-
private CertPath cpath = TestCertUtils.genCertPath(3, 0);
private Date now = new Date();
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/CodeSourceTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/CodeSourceTest.java
index 276dfd7..eeef8ac 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/CodeSourceTest.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/CodeSourceTest.java
@@ -47,16 +47,6 @@ import junit.framework.TestCase;
*/
public class CodeSourceTest extends TestCase {
- /**
- *
- * Entry point for standalone runs.
- *
- * @param args command line arguments
- */
- public static void main(String[] args) throws Exception {
- junit.textui.TestRunner.run(CodeSourceTest.class);
- }
-
private java.security.cert.Certificate[] chain = null;
/* Below are various URLs used during the testing */
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/GuardedObjectTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/GuardedObjectTest.java
index a1b0365..e717747 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/GuardedObjectTest.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/GuardedObjectTest.java
@@ -39,10 +39,6 @@ import junit.framework.TestCase;
public class GuardedObjectTest extends TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run(GuardedObjectTest.class);
- }
-
/** Null guard imposes no restriction. */
@TestTargets({
@TestTargetNew(
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/IdentityScopeTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/IdentityScopeTest.java
index 5b1ea7f..c11f90a 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/IdentityScopeTest.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/IdentityScopeTest.java
@@ -51,10 +51,6 @@ public class IdentityScopeTest extends TestCase {
}
}
- public static void main(String[] args) {
- junit.textui.TestRunner.run(IdentityScopeTest.class);
- }
-
IdentityScope is;
/**
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/KSPrivateKeyEntryTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/KSPrivateKeyEntryTest.java
index dc7880f..0cb1400 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/KSPrivateKeyEntryTest.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/KSPrivateKeyEntryTest.java
@@ -231,10 +231,6 @@ public class KSPrivateKeyEntryTest extends TestCase {
return new TestSuite(KSPrivateKeyEntryTest.class);
}
- public static void main(String args[]) {
- junit.textui.TestRunner.run(suite());
- }
-
private static class tmpPrivateKey implements PrivateKey {
private String alg = "My algorithm";
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator1Test.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator1Test.java
index 742cc13..efa9bf0 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator1Test.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator1Test.java
@@ -650,8 +650,4 @@ public class KeyPairGenerator1Test extends TestCase {
fail("Unexpected InvalidAlgorithmParameterException was thrown");
}
}
-
- public static void main(String args[]) {
- junit.textui.TestRunner.run(KeyPairGenerator1Test.class);
- }
}
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator2Test.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator2Test.java
index 9a8c5c5..5fe110c 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator2Test.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator2Test.java
@@ -505,7 +505,4 @@ public class KeyPairGenerator2Test extends TestCase {
setProv();
GetInstance03(4);
}
- public static void main(String args[]) {
- junit.textui.TestRunner.run(KeyPairGenerator2Test.class);
- }
}
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator3Test.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator3Test.java
index 69ec7a7..24867e7 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator3Test.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGenerator3Test.java
@@ -191,10 +191,6 @@ public class KeyPairGenerator3Test extends TestCase {
}
}
- public static void main(String args[]) {
- junit.textui.TestRunner.run(KeyPairGenerator3Test.class);
- }
-
/**
* Additional class to verify KeyPairGenerator constructor
*/
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGeneratorSpiTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGeneratorSpiTest.java
index 8d75921..689e6ce 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGeneratorSpiTest.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyPairGeneratorSpiTest.java
@@ -104,9 +104,6 @@ public class KeyPairGeneratorSpiTest extends TestCase {
KeyPair kp = keyPairGen.generateKeyPair();
assertNull("Not null KeyPair", kp);
}
- public static void main(String args[]) {
- junit.textui.TestRunner.run(KeyPairGeneratorSpiTest.class);
- }
class MyAlgorithmParameterSpec implements AlgorithmParameterSpec {}
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyStoreSpiTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyStoreSpiTest.java
index 2ccca0e..9f25a7b 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyStoreSpiTest.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/KeyStoreSpiTest.java
@@ -424,12 +424,6 @@ public class KeyStoreSpiTest extends TestCase {
} catch (UnsupportedOperationException e) {
}
}
-
- public static void main(String args[]) {
- junit.textui.TestRunner.run(KeyStoreSpiTest.class);
- }
-
-
}
/**
@@ -487,4 +481,4 @@ class MyCertificate extends Certificate {
}
};
}
-} \ No newline at end of file
+}
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/PermissionTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/PermissionTest.java
index 13d4d62..f1a3cf3 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/PermissionTest.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/PermissionTest.java
@@ -36,11 +36,6 @@ import dalvik.annotation.TestTargetNew;
*/
public class PermissionTest extends TestCase {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(PermissionTest.class);
- }
-
// Bare extension to instantiate abstract Permission class
static final class RealPermission extends Permission {
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/PermissionsTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/PermissionsTest.java
index 5680e2e..99d39f3 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/PermissionsTest.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/PermissionsTest.java
@@ -49,11 +49,6 @@ import junit.framework.TestCase;
*/
public class PermissionsTest extends TestCase {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(PermissionsTest.class);
- }
-
/**
* Can add any type of permissions. Cannot add if collection is read-only.
*/
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/PolicyTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/PolicyTest.java
index ce57328..1f64d34 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/PolicyTest.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/PolicyTest.java
@@ -57,10 +57,6 @@ public class PolicyTest extends TestCase {
public static final String JAVA_SECURITY_POLICY = "java.security.policy";
- public static void main(String[] args) {
- junit.textui.TestRunner.run(PolicyTest.class);
- }
-
@Override protected void tearDown() throws Exception {
TestEnvironment.reset();
super.tearDown();
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/PrivilegedActionExceptionTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/PrivilegedActionExceptionTest.java
index 99fce26..f1e1b42 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/PrivilegedActionExceptionTest.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/PrivilegedActionExceptionTest.java
@@ -38,14 +38,6 @@ import junit.framework.TestCase;
public class PrivilegedActionExceptionTest extends TestCase {
/**
- * Entry point for standalone runs.
- * @param args command line arguments
- */
- public static void main(String[] args) {
- junit.textui.TestRunner.run(PrivilegedActionExceptionTest.class);
- }
-
- /**
* Tests PrivilegedActionException(Exception)
*/
@TestTargetNew(
@@ -89,4 +81,4 @@ public class PrivilegedActionExceptionTest extends TestCase {
assertNotNull(new PrivilegedActionException(new Exception()).toString());
}
-} \ No newline at end of file
+}
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/ProtectionDomainTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/ProtectionDomainTest.java
index 451cad4..7397a08 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/ProtectionDomainTest.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/ProtectionDomainTest.java
@@ -48,14 +48,6 @@ import junit.framework.TestCase;
public class ProtectionDomainTest extends TestCase {
- /**
- * Entry point for standalone runs.
- * @param args command line arguments
- */
- public static void main(String[] args) {
- junit.textui.TestRunner.run(ProtectionDomainTest.class);
- }
-
private final AllPermission allperm = new AllPermission();
private URL url = null;
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/SecurityPermissionTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/SecurityPermissionTest.java
index 2531c81..fcda610 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/SecurityPermissionTest.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/SecurityPermissionTest.java
@@ -36,11 +36,6 @@ import junit.framework.TestCase;
*
*/
public class SecurityPermissionTest extends TestCase {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(SecurityPermissionTest.class);
- }
-
/**
* Check all constructors: an object is created with the specified valid name.
* If name equal null then NPE should be thrown.
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/SignerTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/SignerTest.java
index 898ab17..267221c 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/SignerTest.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/SignerTest.java
@@ -57,10 +57,6 @@ public class SignerTest extends TestCase {
if (denied!=null && denied.implies(permission)) throw new SecurityException();
}
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(SignerTest.class);
- }
/**
* @tests java.security.Signer#toString()
diff --git a/security/src/test/java/org/apache/harmony/security/tests/java/security/TimestampTest.java b/security/src/test/java/org/apache/harmony/security/tests/java/security/TimestampTest.java
index 1015521..f965337 100644
--- a/security/src/test/java/org/apache/harmony/security/tests/java/security/TimestampTest.java
+++ b/security/src/test/java/org/apache/harmony/security/tests/java/security/TimestampTest.java
@@ -41,11 +41,6 @@ import junit.framework.TestCase;
*/
public class TimestampTest extends TestCase {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(TimestampTest.class);
- }
-
private Date now = new Date();
private static final byte[] encoding = { 1, 2, 3 };
diff --git a/security/src/test/java/org/bouncycastle/jce/provider/AllTests.java b/security/src/test/java/org/bouncycastle/jce/provider/AllTests.java
index e9fbdb0..f9bf52f 100644
--- a/security/src/test/java/org/bouncycastle/jce/provider/AllTests.java
+++ b/security/src/test/java/org/bouncycastle/jce/provider/AllTests.java
@@ -20,14 +20,8 @@ import junit.framework.Test;
import junit.framework.TestSuite;
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 " + AllTests.class.getPackage());
+ TestSuite suite = new TestSuite("All tests for " + AllTests.class.getPackage());
suite.addTestSuite(PKIXCertPathValidatorSpiTest.class);
return suite;
}
diff --git a/security/src/test/java/tests/api/java/security/AllTests.java b/security/src/test/java/tests/api/java/security/AllTests.java
index 679f860..7f83780 100644
--- a/security/src/test/java/tests/api/java/security/AllTests.java
+++ b/security/src/test/java/tests/api/java/security/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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.security;");
+ TestSuite suite = new TestSuite("All tests for package tests.api.java.security;");
// $JUnit-BEGIN$
suite.addTestSuite(AccessControlContextTest.class);
diff --git a/security/src/test/java/tests/api/javax/security/auth/AllTests.java b/security/src/test/java/tests/api/javax/security/auth/AllTests.java
index b5b7f18..bd4ae74 100644
--- a/security/src/test/java/tests/api/javax/security/auth/AllTests.java
+++ b/security/src/test/java/tests/api/javax/security/auth/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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.javax.security.auth;");
+ TestSuite suite = new TestSuite("All tests for package tests.api.javax.security.auth;");
// $JUnit-BEGIN$
suite.addTestSuite(AuthPermissionTest.class);
diff --git a/security/src/test/java/tests/api/javax/security/cert/AllTests.java b/security/src/test/java/tests/api/javax/security/cert/AllTests.java
index 4516bc1..30921bd 100644
--- a/security/src/test/java/tests/api/javax/security/cert/AllTests.java
+++ b/security/src/test/java/tests/api/javax/security/cert/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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.javax.security.cert;");
+ TestSuite suite = new TestSuite("All tests for package tests.api.javax.security.cert;");
// $JUnit-BEGIN$
suite.addTestSuite(CertificateEncodingExceptionTest.class);
diff --git a/security/src/test/java/tests/api/javax/security/cert/CertificateTest.java b/security/src/test/java/tests/api/javax/security/cert/CertificateTest.java
index c4d10f6..38afce6 100644
--- a/security/src/test/java/tests/api/javax/security/cert/CertificateTest.java
+++ b/security/src/test/java/tests/api/javax/security/cert/CertificateTest.java
@@ -191,8 +191,4 @@ public class CertificateTest extends TestCase {
public static Test suite() {
return new TestSuite(CertificateTest.class);
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
}
diff --git a/security/src/test/java/tests/api/javax/security/cert/X509CertificateTest.java b/security/src/test/java/tests/api/javax/security/cert/X509CertificateTest.java
index 4af8dc8..79b7b00 100644
--- a/security/src/test/java/tests/api/javax/security/cert/X509CertificateTest.java
+++ b/security/src/test/java/tests/api/javax/security/cert/X509CertificateTest.java
@@ -904,8 +904,4 @@ public class X509CertificateTest extends TestCase {
public static Test suite() {
return new TestSuite(X509CertificateTest.class);
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
}
diff --git a/security/src/test/java/tests/java/security/AllPermissionTest.java b/security/src/test/java/tests/java/security/AllPermissionTest.java
index e9668ad..2db54b0 100644
--- a/security/src/test/java/tests/java/security/AllPermissionTest.java
+++ b/security/src/test/java/tests/java/security/AllPermissionTest.java
@@ -40,10 +40,6 @@ import junit.framework.TestCase;
*/
public class AllPermissionTest extends TestCase {
- public static void main(String[] args) {
- junit.textui.TestRunner.run(AllPermissionTest.class);
- }
-
/**
* Test all constructors: an object is created, name and actions are ignored
*/
diff --git a/security/src/test/java/tests/java/security/AllTests.java b/security/src/test/java/tests/java/security/AllTests.java
index 61396df..6dadd07 100644
--- a/security/src/test/java/tests/java/security/AllTests.java
+++ b/security/src/test/java/tests/java/security/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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.java.security;");
+ TestSuite suite = new TestSuite("All tests for package tests.java.security;");
// $JUnit-BEGIN$
suite.addTestSuite(AlgorithmParameterGeneratorSpiTest.class);
diff --git a/security/src/test/java/tests/java/security/BasicPermissionTest.java b/security/src/test/java/tests/java/security/BasicPermissionTest.java
index 4987ab4..75661ae 100644
--- a/security/src/test/java/tests/java/security/BasicPermissionTest.java
+++ b/security/src/test/java/tests/java/security/BasicPermissionTest.java
@@ -38,11 +38,6 @@ import junit.framework.TestCase;
*/
@TestTargetClass(BasicPermission.class)
public class BasicPermissionTest extends TestCase {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(BasicPermissionTest.class);
- }
-
/**
* Check all constructors: an object is created with the specified valid name.
* If name equal null then NPE should be thrown.
diff --git a/security/src/test/java/tests/java/security/IdentityTest.java b/security/src/test/java/tests/java/security/IdentityTest.java
index 3566ecf..470936e 100644
--- a/security/src/test/java/tests/java/security/IdentityTest.java
+++ b/security/src/test/java/tests/java/security/IdentityTest.java
@@ -56,10 +56,6 @@ public class IdentityTest extends TestCase {
}
}
- public static void main(String[] args) {
- junit.textui.TestRunner.run(IdentityTest.class);
- }
-
@TestTargetNew(
level = TestLevel.PARTIAL,
notes = "Method's returned variable is not checked",
diff --git a/security/src/test/java/tests/java/security/SecureClassLoaderTest.java b/security/src/test/java/tests/java/security/SecureClassLoaderTest.java
index 1dfaae6..6ce1659 100644
--- a/security/src/test/java/tests/java/security/SecureClassLoaderTest.java
+++ b/security/src/test/java/tests/java/security/SecureClassLoaderTest.java
@@ -64,16 +64,6 @@ import java.security.cert.Certificate;
public class SecureClassLoaderTest extends TestCase {
/**
- * Entry point for stand alone runs.
- *
- * @param args
- * command line parameters
- */
- public static void main(String[] args) {
- junit.textui.TestRunner.run(SecureClassLoaderTest.class);
- }
-
- /**
* A class name for the class presented as {@link #klassData bytecode below}
*/
private static final String klassName = "HiWorld";
diff --git a/security/src/test/java/tests/security/AllTests.java b/security/src/test/java/tests/security/AllTests.java
index a88cc0e..7a790c9 100644
--- a/security/src/test/java/tests/security/AllTests.java
+++ b/security/src/test/java/tests/security/AllTests.java
@@ -23,13 +23,8 @@ import junit.framework.TestSuite;
* Test suite that includes all tests for the security project.
*/
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 security test suites");
+ TestSuite suite = new TestSuite("All security test suites");
// $JUnit-BEGIN$
suite.addTest(org.apache.harmony.security.tests.java.security.AllTests.suite());
suite.addTest(org.bouncycastle.jce.provider.AllTests.suite());
diff --git a/security/src/test/java/tests/security/acl/AclNotFoundExceptionTest.java b/security/src/test/java/tests/security/acl/AclNotFoundExceptionTest.java
index cfd0bb0..cbee130 100644
--- a/security/src/test/java/tests/security/acl/AclNotFoundExceptionTest.java
+++ b/security/src/test/java/tests/security/acl/AclNotFoundExceptionTest.java
@@ -37,11 +37,6 @@ import java.security.acl.AclNotFoundException;
*/
@TestTargetClass(AclNotFoundException.class)
public class AclNotFoundExceptionTest extends TestCase {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(AclNotFoundExceptionTest.class);
- }
-
/**
* check default constructor
*/
diff --git a/security/src/test/java/tests/security/acl/AllTests.java b/security/src/test/java/tests/security/acl/AllTests.java
index 4b93980..9a6f2b4 100644
--- a/security/src/test/java/tests/security/acl/AllTests.java
+++ b/security/src/test/java/tests/security/acl/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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.security.acl;");
+ TestSuite suite = new TestSuite("All tests for package tests.api.java.security.acl;");
// $JUnit-BEGIN$
suite.addTestSuite(AclNotFoundException2Test.class);
diff --git a/security/src/test/java/tests/security/acl/LastOwnerExceptionTest.java b/security/src/test/java/tests/security/acl/LastOwnerExceptionTest.java
index b76f456..3cd14ff 100644
--- a/security/src/test/java/tests/security/acl/LastOwnerExceptionTest.java
+++ b/security/src/test/java/tests/security/acl/LastOwnerExceptionTest.java
@@ -22,11 +22,6 @@
package tests.security.acl;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
import junit.framework.TestCase;
import java.security.acl.LastOwnerException;
@@ -35,18 +30,7 @@ import java.security.acl.LastOwnerException;
* Unit test for LastOwnerException.
*
*/
-@TestTargetClass(LastOwnerException.class)
public class LastOwnerExceptionTest extends TestCase {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(LastOwnerExceptionTest.class);
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "LastOwnerException",
- args = {}
- )
public void testLastOwnerException() {
assertNotNull(new LastOwnerException());
assertNull(new LastOwnerException().getMessage());
diff --git a/security/src/test/java/tests/security/acl/NotOwnerExceptionTest.java b/security/src/test/java/tests/security/acl/NotOwnerExceptionTest.java
index c3dfe34..67ef38b 100644
--- a/security/src/test/java/tests/security/acl/NotOwnerExceptionTest.java
+++ b/security/src/test/java/tests/security/acl/NotOwnerExceptionTest.java
@@ -22,11 +22,6 @@
package tests.security.acl;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
import junit.framework.TestCase;
import java.security.acl.NotOwnerException;
@@ -35,18 +30,7 @@ import java.security.acl.NotOwnerException;
* Unit test for NotOwnerException.
*
*/
-@TestTargetClass(NotOwnerException.class)
public class NotOwnerExceptionTest extends TestCase {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(NotOwnerExceptionTest.class);
- }
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NotOwnerException",
- args = {}
- )
public void testNotOwnerException() {
assertNotNull(new NotOwnerException());
assertNull(new NotOwnerException().getMessage());
diff --git a/security/src/test/java/tests/security/cert/AllTests.java b/security/src/test/java/tests/security/cert/AllTests.java
index 749a5ab..e5b9d47 100644
--- a/security/src/test/java/tests/security/cert/AllTests.java
+++ b/security/src/test/java/tests/security/cert/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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.security.cert;");
+ TestSuite suite = new TestSuite("All tests for package tests.api.java.security.cert;");
// $JUnit-BEGIN$
suite.addTestSuite(CRLExceptionTest.class);
diff --git a/security/src/test/java/tests/security/cert/CertPathBuilder1Test.java b/security/src/test/java/tests/security/cert/CertPathBuilder1Test.java
index 1c45e57..d472bc4 100644
--- a/security/src/test/java/tests/security/cert/CertPathBuilder1Test.java
+++ b/security/src/test/java/tests/security/cert/CertPathBuilder1Test.java
@@ -522,11 +522,6 @@ public class CertPathBuilder1Test extends TestCase {
}
}
-
- public static void main(String args[]) {
- junit.textui.TestRunner.run(CertPathBuilder1Test.class);
- }
-
}
/**
* Additional class to verify CertPathBuilder constructor
diff --git a/security/src/test/java/tests/security/cert/CertPathBuilder2Test.java b/security/src/test/java/tests/security/cert/CertPathBuilder2Test.java
index fcf235e..af9de90 100644
--- a/security/src/test/java/tests/security/cert/CertPathBuilder2Test.java
+++ b/security/src/test/java/tests/security/cert/CertPathBuilder2Test.java
@@ -265,9 +265,4 @@ public class CertPathBuilder2Test extends TestCase {
checkResult(cerPB);
}
}
- public static void main(String args[]) {
- junit.textui.TestRunner.run(CertPathBuilder2Test.class);
- }
-
-
}
diff --git a/security/src/test/java/tests/security/cert/CertPathValidator1Test.java b/security/src/test/java/tests/security/cert/CertPathValidator1Test.java
index a76af78..101644d 100644
--- a/security/src/test/java/tests/security/cert/CertPathValidator1Test.java
+++ b/security/src/test/java/tests/security/cert/CertPathValidator1Test.java
@@ -526,10 +526,6 @@ public class CertPathValidator1Test extends TestCase {
defaultProvider);
}
}
-
- public static void main(String args[]) {
- junit.textui.TestRunner.run(CertPathValidator1Test.class);
- }
}
/**
* Additional class to verify CertPathValidator constructor
diff --git a/security/src/test/java/tests/security/cert/CertStoreSpiTest.java b/security/src/test/java/tests/security/cert/CertStoreSpiTest.java
index 3cac01f..4760871 100644
--- a/security/src/test/java/tests/security/cert/CertStoreSpiTest.java
+++ b/security/src/test/java/tests/security/cert/CertStoreSpiTest.java
@@ -97,10 +97,6 @@ public class CertStoreSpiTest extends TestCase {
return new TestSuite(CertStoreSpiTest.class);
}
- public static void main(String args[]) {
- junit.textui.TestRunner.run(suite());
- }
-
/**
* Additional classes for verification CertStoreSpi class
*/
diff --git a/security/src/test/java/tests/security/cert/CertificateFactory1Test.java b/security/src/test/java/tests/security/cert/CertificateFactory1Test.java
index 42677eb..04112a2 100644
--- a/security/src/test/java/tests/security/cert/CertificateFactory1Test.java
+++ b/security/src/test/java/tests/security/cert/CertificateFactory1Test.java
@@ -887,10 +887,6 @@ public class CertificateFactory1Test extends TestCase {
fail("Unexpected exception" + e);
}
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(CertificateFactory1Test.class);
- }
}
/**
* Additional class to verify CertificateFactory constructor
diff --git a/security/src/test/java/tests/security/cert/X509CRLEntryTest.java b/security/src/test/java/tests/security/cert/X509CRLEntryTest.java
index 1eec127..3f82f67 100644
--- a/security/src/test/java/tests/security/cert/X509CRLEntryTest.java
+++ b/security/src/test/java/tests/security/cert/X509CRLEntryTest.java
@@ -266,9 +266,5 @@ public class X509CRLEntryTest extends TestCase {
public static Test suite() {
return new TestSuite(X509CRLEntryTest.class);
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
}
diff --git a/security/src/test/java/tests/security/cert/X509CRLTest.java b/security/src/test/java/tests/security/cert/X509CRLTest.java
index c10494e..4dd98cb 100644
--- a/security/src/test/java/tests/security/cert/X509CRLTest.java
+++ b/security/src/test/java/tests/security/cert/X509CRLTest.java
@@ -457,9 +457,5 @@ public class X509CRLTest extends TestCase {
public static Test suite() {
return new TestSuite(X509CRLTest.class);
}
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(suite());
- }
}
diff --git a/security/src/test/java/tests/security/interfaces/AllTests.java b/security/src/test/java/tests/security/interfaces/AllTests.java
index e665119..e180408 100644
--- a/security/src/test/java/tests/security/interfaces/AllTests.java
+++ b/security/src/test/java/tests/security/interfaces/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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.security.interfaces;");
+ TestSuite suite = new TestSuite("All tests for package tests.security.interfaces;");
// $JUnit-BEGIN$
suite.addTestSuite(DSAKeyTest.class);
diff --git a/security/src/test/java/tests/security/spec/AllTests.java b/security/src/test/java/tests/security/spec/AllTests.java
index f643618..151e0a7 100644
--- a/security/src/test/java/tests/security/spec/AllTests.java
+++ b/security/src/test/java/tests/security/spec/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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.security.spec;");
+ TestSuite suite = new TestSuite("All tests for package tests.security.spec;");
// $JUnit-BEGIN$
suite.addTestSuite(DSAParameterSpecTest.class);
diff --git a/security/src/test/java/tests/targets/security/AllTests.java b/security/src/test/java/tests/targets/security/AllTests.java
index 6bd6d05..7d5802d 100644
--- a/security/src/test/java/tests/targets/security/AllTests.java
+++ b/security/src/test/java/tests/targets/security/AllTests.java
@@ -20,13 +20,8 @@ import junit.framework.Test;
import junit.framework.TestSuite;
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.targets.security;");
+ TestSuite suite = new TestSuite("All tests for package tests.targets.security;");
// $JUnit-BEGIN$
suite.addTestSuite(MessageDigestTestMD2.class);
@@ -75,4 +70,4 @@ public class AllTests {
// $JUnit-END$
return suite;
}
-} \ No newline at end of file
+}
diff --git a/security/src/test/java/tests/targets/security/cert/AllTests.java b/security/src/test/java/tests/targets/security/cert/AllTests.java
index 50292e2..c0c411d 100644
--- a/security/src/test/java/tests/targets/security/cert/AllTests.java
+++ b/security/src/test/java/tests/targets/security/cert/AllTests.java
@@ -19,13 +19,8 @@ import junit.framework.Test;
import junit.framework.TestSuite;
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.targets.security.certs;");
+ TestSuite suite = new TestSuite("All tests for package tests.targets.security.certs;");
// $JUnit-BEGIN$
suite.addTestSuite(CertificateTest.class);
@@ -36,4 +31,4 @@ public class AllTests {
// $JUnit-END$
return suite;
}
-} \ No newline at end of file
+}
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/AllTests.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/AllTests.java
index 58c670a..1b0bb59 100644
--- a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/AllTests.java
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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 org.apache.harmony.sql.tests.java.sql;");
+ TestSuite suite = new TestSuite("All tests for package org.apache.harmony.sql.tests.java.sql;");
// $JUnit-BEGIN$
suite.addTestSuite(BatchUpdateExceptionTest.class);
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/AllTests.java b/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/AllTests.java
index abbb8b0..8183bbf 100644
--- a/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/AllTests.java
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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 org.apache.harmony.sql.tests.javax.sql;");
+ TestSuite suite = new TestSuite("All tests for package org.apache.harmony.sql.tests.javax.sql;");
// $JUnit-BEGIN$
suite.addTestSuite(ConnectionEventTest.class);
diff --git a/sql/src/test/java/tests/SQLite/AllTests.java b/sql/src/test/java/tests/SQLite/AllTests.java
index 2cf0f61..e2aa55c 100644
--- a/sql/src/test/java/tests/SQLite/AllTests.java
+++ b/sql/src/test/java/tests/SQLite/AllTests.java
@@ -23,7 +23,7 @@ public class AllTests {
//All tests executed with sqlite3 only
public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for SQLite");
+ TestSuite suite = new TestSuite("Tests for SQLite");
//$JUnit-BEGIN$
suite.addTestSuite(DatabaseTest.class);
suite.addTestSuite(JDBCDriverFunctionalTest.class);
diff --git a/sql/src/test/java/tests/java/sql/AllTests.java b/sql/src/test/java/tests/java/sql/AllTests.java
index c6a2bff..5c9345b 100644
--- a/sql/src/test/java/tests/java/sql/AllTests.java
+++ b/sql/src/test/java/tests/java/sql/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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.java.sql;");
+ TestSuite suite = new TestSuite("All tests for package tests.java.sql;");
// $JUnit-BEGIN$
suite.addTestSuite(MultiThreadAccessTest.class);
diff --git a/sql/src/test/java/tests/sql/AllTests.java b/sql/src/test/java/tests/sql/AllTests.java
index 4d59cd4..6eda690 100644
--- a/sql/src/test/java/tests/sql/AllTests.java
+++ b/sql/src/test/java/tests/sql/AllTests.java
@@ -23,13 +23,8 @@ import junit.framework.TestSuite;
* Test suite that includes all tests for the Math project.
*/
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 SQL test suites");
+ TestSuite suite = new TestSuite("All SQL test suites");
// $JUnit-BEGIN$
suite.addTest(org.apache.harmony.sql.tests.java.sql.AllTests.suite());
suite.addTest(org.apache.harmony.sql.tests.javax.sql.AllTests.suite());
diff --git a/suncompat/src/test/java/sun/misc/AllTests.java b/suncompat/src/test/java/sun/misc/AllTests.java
index 8ea3bcf..f2c4277 100644
--- a/suncompat/src/test/java/sun/misc/AllTests.java
+++ b/suncompat/src/test/java/sun/misc/AllTests.java
@@ -20,13 +20,8 @@ import junit.framework.Test;
import junit.framework.TestSuite;
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 sun.misc");
+ TestSuite suite = new TestSuite("Test for sun.misc");
// $JUnit-BEGIN$
diff --git a/suncompat/src/test/java/tests/suncompat/AllTests.java b/suncompat/src/test/java/tests/suncompat/AllTests.java
index 0884517..e86889c 100644
--- a/suncompat/src/test/java/tests/suncompat/AllTests.java
+++ b/suncompat/src/test/java/tests/suncompat/AllTests.java
@@ -23,13 +23,8 @@ import junit.framework.TestSuite;
* Test suite that includes all tests for the suncompat project.
*/
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 suncompat test suites");
+ TestSuite suite = new TestSuite("All suncompat test suites");
// $JUnit-BEGIN$
suite.addTest(sun.misc.AllTests.suite());
// $JUnit-END$
diff --git a/text/src/test/java/org/apache/harmony/text/tests/java/text/AllTests.java b/text/src/test/java/org/apache/harmony/text/tests/java/text/AllTests.java
index c2cfbb2..0c3d61d 100644
--- a/text/src/test/java/org/apache/harmony/text/tests/java/text/AllTests.java
+++ b/text/src/test/java/org/apache/harmony/text/tests/java/text/AllTests.java
@@ -21,14 +21,8 @@ import junit.framework.Test;
import junit.framework.TestSuite;
public class AllTests {
-
- public static void main(String[] args) {
- junit.textui.TestRunner.run(AllTests.suite());
- }
-
public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite(
- "Suite org.apache.harmony.text.tests.java.text");
+ TestSuite suite = new TestSuite("Suite org.apache.harmony.text.tests.java.text");
//$JUnit-BEGIN$
suite.addTestSuite(AnnotationTest.class);
suite.addTestSuite(AttributedCharacterIteratorAttributeTest.class);
diff --git a/text/src/test/java/tests/text/AllTests.java b/text/src/test/java/tests/text/AllTests.java
index a3eb66d..25066fb 100644
--- a/text/src/test/java/tests/text/AllTests.java
+++ b/text/src/test/java/tests/text/AllTests.java
@@ -25,13 +25,8 @@ import junit.framework.TestSuite;
*
*/
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 Text test suites");
+ TestSuite suite = new TestSuite("All Text test suites");
// $JUnit-BEGIN$
suite.addTest(org.apache.harmony.text.tests.java.text.AllTests.suite());
// $JUnit-END$
diff --git a/x-net/src/test/java/tests/api/javax/net/AllTests.java b/x-net/src/test/java/tests/api/javax/net/AllTests.java
index 90c2a6a..35cd6f5 100644
--- a/x-net/src/test/java/tests/api/javax/net/AllTests.java
+++ b/x-net/src/test/java/tests/api/javax/net/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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.javax.net;");
+ TestSuite suite = new TestSuite("All tests for package tests.api.javax.net;");
// $JUnit-BEGIN$
suite.addTestSuite(ServerSocketFactoryTest.class);
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/AllTests.java b/x-net/src/test/java/tests/api/javax/net/ssl/AllTests.java
index ecfe83f..5f9c32d 100644
--- a/x-net/src/test/java/tests/api/javax/net/ssl/AllTests.java
+++ b/x-net/src/test/java/tests/api/javax/net/ssl/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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.javax.net.ssl;");
+ TestSuite suite = new TestSuite("All tests for package tests.api.javax.net.ssl;");
// $JUnit-BEGIN$
suite.addTestSuite(CertPathTrustManagerParametersTest.class);
diff --git a/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java b/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java
index f659919..8205059 100644
--- a/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java
+++ b/x-net/src/test/java/tests/api/javax/net/ssl/SSLEngineTest.java
@@ -62,10 +62,6 @@ public class SSLEngineTest extends TestCase {
private HandshakeHandler clientEngine;
private HandshakeHandler serverEngine;
- public static void main(String[] args) {
- junit.textui.TestRunner.run(SSLEngineTest.class);
- }
-
@Override protected void setUp() throws Exception {
super.setUp();
TestEnvironment.reset();
diff --git a/x-net/src/test/java/tests/xnet/AllTests.java b/x-net/src/test/java/tests/xnet/AllTests.java
index 53b11dc..04a2ed6 100644
--- a/x-net/src/test/java/tests/xnet/AllTests.java
+++ b/x-net/src/test/java/tests/xnet/AllTests.java
@@ -23,14 +23,8 @@ import junit.framework.TestSuite;
* Test suite that includes all tests for the Math project.
*/
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 javax.net and javax.net.ssl test suites");
+ TestSuite suite = new TestSuite("All javax.net and javax.net.ssl test suites");
// $JUnit-BEGIN$
suite.addTest(tests.api.javax.net.AllTests.suite());
suite.addTest(tests.api.javax.net.ssl.AllTests.suite());
diff --git a/xml/src/test/java/org/apache/harmony/xml/AllTests.java b/xml/src/test/java/org/apache/harmony/xml/AllTests.java
index f7fac7c..c04c1b5 100644
--- a/xml/src/test/java/org/apache/harmony/xml/AllTests.java
+++ b/xml/src/test/java/org/apache/harmony/xml/AllTests.java
@@ -21,7 +21,7 @@ import junit.framework.TestSuite;
public class AllTests {
public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite();
+ TestSuite suite = new TestSuite();
suite.addTestSuite(ExpatParserTest.class);
return suite;
}
diff --git a/xml/src/test/java/org/apache/harmony/xml/XsltXPathConformanceTestSuite.java b/xml/src/test/java/org/apache/harmony/xml/XsltXPathConformanceTestSuite.java
index 7773814..da37c45 100644
--- a/xml/src/test/java/org/apache/harmony/xml/XsltXPathConformanceTestSuite.java
+++ b/xml/src/test/java/org/apache/harmony/xml/XsltXPathConformanceTestSuite.java
@@ -21,7 +21,6 @@ import junit.framework.AssertionFailedError;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
-import junit.textui.TestRunner;
import org.w3c.dom.Attr;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
@@ -116,7 +115,7 @@ public class XsltXPathConformanceTestSuite {
}
File catalogXml = new File(args[0]);
- TestRunner.run(suite(catalogXml));
+ // TestRunner.run(suite(catalogXml)); android-changed
}
public static Test suite() throws Exception {
diff --git a/xml/src/test/java/org/kxml2/io/AllTests.java b/xml/src/test/java/org/kxml2/io/AllTests.java
index f996d25..4fcc44a 100644
--- a/xml/src/test/java/org/kxml2/io/AllTests.java
+++ b/xml/src/test/java/org/kxml2/io/AllTests.java
@@ -21,7 +21,7 @@ import junit.framework.TestSuite;
public class AllTests {
public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite();
+ TestSuite suite = new TestSuite();
suite.addTestSuite(KXmlSerializerTest.class);
return suite;
}
diff --git a/xml/src/test/java/tests/api/javax/xml/parsers/AllTests.java b/xml/src/test/java/tests/api/javax/xml/parsers/AllTests.java
index 6a22109..aecc746 100644
--- a/xml/src/test/java/tests/api/javax/xml/parsers/AllTests.java
+++ b/xml/src/test/java/tests/api/javax/xml/parsers/AllTests.java
@@ -25,13 +25,8 @@ import org.apache.harmony.xml.ExpatParserTest;
*/
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.javax.xml.parsers;");
+ TestSuite suite = new TestSuite("All tests for package tests.api.javax.xml.parsers;");
// $JUnit-BEGIN$
suite.addTestSuite(DocumentBuilderFactoryTest.class);
diff --git a/xml/src/test/java/tests/api/org/xml/sax/AllTests.java b/xml/src/test/java/tests/api/org/xml/sax/AllTests.java
index 9c29178..f7643e9 100644
--- a/xml/src/test/java/tests/api/org/xml/sax/AllTests.java
+++ b/xml/src/test/java/tests/api/org/xml/sax/AllTests.java
@@ -20,13 +20,8 @@ import junit.framework.Test;
import junit.framework.TestSuite;
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 org.xml.sax package");
+ TestSuite suite = new TestSuite("Tests for org.xml.sax package");
// $JUnit-BEGIN$
suite.addTestSuite(HandlerBaseTest.class);
diff --git a/xml/src/test/java/tests/api/org/xml/sax/ext/AllTests.java b/xml/src/test/java/tests/api/org/xml/sax/ext/AllTests.java
index f4b34b8..1334780 100644
--- a/xml/src/test/java/tests/api/org/xml/sax/ext/AllTests.java
+++ b/xml/src/test/java/tests/api/org/xml/sax/ext/AllTests.java
@@ -20,13 +20,8 @@ import junit.framework.Test;
import junit.framework.TestSuite;
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 org.xml.sax.ext package");
+ TestSuite suite = new TestSuite("Tests for org.xml.sax.ext package");
// $JUnit-BEGIN$
suite.addTestSuite(Attributes2ImplTest.class);
diff --git a/xml/src/test/java/tests/api/org/xml/sax/helpers/AllTests.java b/xml/src/test/java/tests/api/org/xml/sax/helpers/AllTests.java
index 5bf63bf..135496c 100644
--- a/xml/src/test/java/tests/api/org/xml/sax/helpers/AllTests.java
+++ b/xml/src/test/java/tests/api/org/xml/sax/helpers/AllTests.java
@@ -20,13 +20,8 @@ import junit.framework.Test;
import junit.framework.TestSuite;
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 org.xml.sax.helpers package");
+ TestSuite suite = new TestSuite("Tests for org.xml.sax.helpers package");
// $JUnit-BEGIN$
suite.addTestSuite(AttributeListImplTest.class);
diff --git a/xml/src/test/java/tests/org/w3c/dom/AllTests.java b/xml/src/test/java/tests/org/w3c/dom/AllTests.java
index a4299a7..5dba844 100644
--- a/xml/src/test/java/tests/org/w3c/dom/AllTests.java
+++ b/xml/src/test/java/tests/org/w3c/dom/AllTests.java
@@ -24,13 +24,8 @@ import junit.framework.TestSuite;
*/
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 org.w3c.dom;");
+ TestSuite suite = new TestSuite("All tests for package org.w3c.dom;");
// $JUnit-BEGIN$
suite.addTestSuite(AttrGetOwnerElement.class);
diff --git a/xml/src/test/java/tests/xml/AllTests.java b/xml/src/test/java/tests/xml/AllTests.java
index 45ca18e..8a4b4a9 100644
--- a/xml/src/test/java/tests/xml/AllTests.java
+++ b/xml/src/test/java/tests/xml/AllTests.java
@@ -22,7 +22,7 @@ import junit.framework.TestSuite;
public class AllTests {
public static Test suite() {
- TestSuite suite = tests.TestSuiteFactory.createTestSuite();
+ TestSuite suite = new TestSuite();
suite.addTestSuite(SimpleParserTest.class);
suite.addTestSuite(SimpleBuilderTest.class);
@@ -32,7 +32,9 @@ public class AllTests {
suite.addTest(tests.api.javax.xml.parsers.AllTests.suite());
suite.addTest(tests.api.org.xml.sax.AllTests.suite());
- suite.addTest(tests.api.org.w3c.dom.AllTests.suite());
+ // BEGIN android-changed: this is in the dom module!
+ // suite.addTest(tests.api.org.w3c.dom.AllTests.suite());
+ // END android-changed
suite.addTest(tests.org.w3c.dom.AllTests.suite());
suite.addTest(org.apache.harmony.xml.AllTests.suite());
suite.addTest(org.kxml2.io.AllTests.suite());