1 5 package org.h2.test.unit; 6 7 import java.math.BigInteger ; 8 import java.sql.SQLException ; 9 import java.util.ArrayList ; 10 import java.util.Random ; 11 12 import org.h2.engine.Constants; 13 import org.h2.test.TestBase; 14 import org.h2.value.Value; 15 import org.h2.value.ValueString; 16 17 public class TestOverflow extends TestBase { 18 19 public void test() throws Exception { 20 test(Value.BYTE, Byte.MIN_VALUE, Byte.MAX_VALUE); 21 test(Value.INT, Integer.MIN_VALUE, Integer.MAX_VALUE); 22 test(Value.LONG, Long.MIN_VALUE, Long.MAX_VALUE); 23 test(Value.SHORT, Short.MIN_VALUE, Short.MAX_VALUE); 24 } 25 26 private ArrayList values; 27 private int type; 28 private BigInteger min, max; 29 private boolean successExpected; 30 31 private void test(int type, long min, long max) throws Exception { 32 values = new ArrayList (); 33 this.type = type; 34 this.min = new BigInteger (""+min); 35 this.max = new BigInteger (""+max); 36 add(0); 37 add(min); 38 add(max); 39 add(max-1); 40 add(min+1); 41 add(1); 42 add(-1); 43 Random random = new Random (1); 44 for(int i=0; i<40; i++) { 45 if(max > Integer.MAX_VALUE) { 46 add(random.nextLong()); 47 } else { 48 add((random.nextBoolean() ? 1 : -1) * random.nextInt((int)max)); 49 } 50 } 51 for(int a=0; a<values.size(); a++) { 52 for(int b=0; b<values.size(); b++) { 53 Value va = (Value) values.get(a); 54 Value vb = (Value) values.get(b); 55 testValues(va, vb); 56 } 57 } 58 } 59 60 void checkIfExpected(String a, String b) throws Exception { 61 if(successExpected) { 62 check(a, b); 63 } 64 } 65 66 void onSuccess() throws Exception { 67 if(!successExpected && Constants.OVERFLOW_EXCEPTIONS) { 68 error("unexpected success"); 69 } 70 } 71 72 void onError() throws Exception { 73 if(successExpected) { 74 error("unexpected error"); 75 } 76 } 77 78 private void testValues(Value va, Value vb) throws Exception { 79 BigInteger a = new BigInteger (va.getString()); 80 BigInteger b = new BigInteger (vb.getString()); 81 successExpected = inRange(a.negate()); 82 try { 83 checkIfExpected(va.negate().getString(), a.negate().toString()); 84 onSuccess(); 85 } catch(SQLException e) { 86 onError(); 87 } 88 successExpected = inRange(a.add(b)); 89 try { 90 checkIfExpected(va.add(vb).getString(), a.add(b).toString()); 91 onSuccess(); 92 } catch(SQLException e) { 93 onError(); 94 } 95 successExpected = inRange(a.subtract(b)); 96 try { 97 checkIfExpected(va.subtract(vb).getString(), a.subtract(b).toString()); 98 onSuccess(); 99 } catch(SQLException e) { 100 onError(); 101 } 102 successExpected = inRange(a.multiply(b)); 103 try { 104 checkIfExpected(va.multiply(vb).getString(), a.multiply(b).toString()); 105 onSuccess(); 106 } catch(SQLException e) { 107 onError(); 108 } 109 } 110 111 private boolean inRange(BigInteger v) { 112 return v.compareTo(min) >= 0 && v.compareTo(max) <= 0; 113 } 114 115 private void add(long l) throws SQLException { 116 values.add(ValueString.get("" + l).convertTo(type)); 117 } 118 119 } 120 | Popular Tags |