1 // 2016 and later: Unicode, Inc. and others. 2 // License & terms of use: http://www.unicode.org/copyright.html#License 3 /* 4 **************************************************************************** 5 * Copyright (C) 2004-2010, International Business Machines Corporation and * 6 * others. All Rights Reserved. * 7 **************************************************************************** 8 * 9 */ 10 11 package com.ibm.icu.dev.test.timescale; 12 13 import java.util.Random; 14 15 import org.junit.Test; 16 17 import com.ibm.icu.dev.test.TestFmwk; 18 import com.ibm.icu.math.BigDecimal; 19 import com.ibm.icu.util.UniversalTimeScale; 20 21 /** 22 * This class tests the UniversalTimeScale class by 23 * generating ramdon values in range and making sure 24 * that they round-trip correctly. 25 */ 26 public class TimeScaleMonkeyTest extends TestFmwk 27 { 28 29 /** 30 * The default constructor. 31 */ 32 public TimeScaleMonkeyTest() 33 { 34 } 35 36 private static final int LOOP_COUNT = 1000; 37 private static final BigDecimal longMax = new BigDecimal(Long.MAX_VALUE); 38 39 private Random ran = null; 40 41 private long ranInt; 42 private long ranMin; 43 private long ranMax; 44 45 private void initRandom(long min, long max) 46 { 47 BigDecimal interval = new BigDecimal(max).subtract(new BigDecimal(min)); 48 49 ranMin = min; 50 ranMax = max; 51 ranInt = 0; 52 53 if (ran == null) { 54 ran = createRandom(); 55 } 56 57 if (interval.compareTo(longMax) < 0) { 58 ranInt = interval.longValue(); 59 } 60 } 61 62 private final long randomInRange() 63 { 64 long value; 65 66 if (ranInt != 0) { 67 value = ran.nextLong() % ranInt; 68 69 if (value < 0) { 70 value = -value; 71 } 72 73 value += ranMin; 74 } else { 75 do { 76 value = ran.nextLong(); 77 } while (value < ranMin || value > ranMax); 78 } 79 80 return value; 81 } 82 83 @Test 84 public void TestRoundTrip() 85 { 86 for (int scale = 0; scale < UniversalTimeScale.MAX_SCALE; scale += 1) { 87 long fromMin = UniversalTimeScale.getTimeScaleValue(scale, UniversalTimeScale.FROM_MIN_VALUE); 88 long fromMax = UniversalTimeScale.getTimeScaleValue(scale, UniversalTimeScale.FROM_MAX_VALUE); 89 int i = 0; 90 91 initRandom(fromMin, fromMax); 92 93 while (i < LOOP_COUNT) { 94 long value = randomInRange(); 95 96 long rt = UniversalTimeScale.toLong(UniversalTimeScale.from(value, scale), scale); 97 98 if (rt != value) { 99 errln("Round-trip error: time scale = " + scale + ", value = " + value + ", round-trip = " + rt); 100 } 101 102 i += 1; 103 } 104 } 105 } 106 } 107