001: /*
002: **************************************************************************
003: * Copyright (C) 2004, International Business Machines Corporation and *
004: * others. All Rights Reserved. *
005: **************************************************************************
006: *
007: */
008:
009: package com.ibm.icu.dev.test.timescale;
010:
011: import com.ibm.icu.dev.test.TestFmwk;
012: import com.ibm.icu.util.UniversalTimeScale;
013: import com.ibm.icu.math.BigDecimal;
014: import java.util.Random;
015:
016: /**
017: * This class tests the UniversalTimeScale class by
018: * generating ramdon values in range and making sure
019: * that they round-trip correctly.
020: */
021: public class TimeScaleMonkeyTest extends TestFmwk {
022:
023: /**
024: * The default constructor.
025: */
026: public TimeScaleMonkeyTest() {
027: }
028:
029: private static final int LOOP_COUNT = 1000;
030: private static final BigDecimal longMax = new BigDecimal(
031: Long.MAX_VALUE);
032:
033: private Random ran = null;
034:
035: private long ranInt;
036: private long ranMin;
037: private long ranMax;
038:
039: private void initRandom(long min, long max) {
040: BigDecimal interval = new BigDecimal(max)
041: .subtract(new BigDecimal(min));
042:
043: ranMin = min;
044: ranMax = max;
045: ranInt = 0;
046:
047: if (ran == null) {
048: ran = createRandom();
049: }
050:
051: if (interval.compareTo(longMax) < 0) {
052: ranInt = interval.longValue();
053: }
054: }
055:
056: private final long randomInRange() {
057: long value;
058:
059: if (ranInt != 0) {
060: value = ran.nextLong() % ranInt;
061:
062: if (value < 0) {
063: value = -value;
064: }
065:
066: value += ranMin;
067: } else {
068: do {
069: value = ran.nextLong();
070: } while (value < ranMin || value > ranMax);
071: }
072:
073: return value;
074: }
075:
076: public void TestRoundTrip() {
077: for (int scale = 0; scale < UniversalTimeScale.MAX_SCALE; scale += 1) {
078: long fromMin = UniversalTimeScale.getTimeScaleValue(scale,
079: UniversalTimeScale.FROM_MIN_VALUE);
080: long fromMax = UniversalTimeScale.getTimeScaleValue(scale,
081: UniversalTimeScale.FROM_MAX_VALUE);
082: int i = 0;
083:
084: initRandom(fromMin, fromMax);
085:
086: while (i < LOOP_COUNT) {
087: long value = randomInRange();
088:
089: long rt = UniversalTimeScale.toLong(UniversalTimeScale
090: .from(value, scale), scale);
091:
092: if (rt != value) {
093: errln("Round-trip error: time scale = " + scale
094: + ", value = " + value + ", round-trip = "
095: + rt);
096: }
097:
098: i += 1;
099: }
100: }
101: }
102:
103: public static void main(String[] args) {
104: new TimeScaleMonkeyTest().run(args);
105: }
106: }
|