1 28 package org.jruby.test; 29 30 import java.io.ByteArrayOutputStream ; 31 import java.io.PrintStream ; 32 import java.util.ArrayList ; 33 import java.util.List ; 34 35 import junit.framework.TestCase; 36 37 import org.jruby.Ruby; 38 import org.jruby.RubyArray; 39 import org.jruby.RubyException; 40 import org.jruby.RubyString; 41 42 public class TestRubyException extends TestCase { 43 44 private Ruby interpreter; 45 private RubyException exception; 46 47 public void setUp() { 48 interpreter = Ruby.getDefaultInstance(); 49 exception = new RubyException(interpreter, interpreter.getClass("StandardError"), "test"); 50 } 51 52 public void testPrintBacktraceWithHiddenLevels() throws Exception { 53 setBackTrace(19); 54 55 String [] lines = printError(); 56 57 assertEquals(expectedTraceLine(1), lines[0]); 58 assertEquals("\t ... 7 levels...", lines[RubyException.TRACE_HEAD]); 59 assertEquals(expectedTraceLine(16), lines[RubyException.TRACE_HEAD + 1]); 60 } 61 62 public void testPrintBacktrace() throws Exception { 63 setBackTrace(18); 64 65 String [] lines = printError(); 66 67 assertEquals(expectedTraceLine(1), lines[0]); 68 assertEquals(expectedTraceLine(RubyException.TRACE_HEAD + 1), lines[RubyException.TRACE_HEAD]); 69 } 70 71 public void testPrintNilBacktrace() throws Exception { 72 exception.set_backtrace(interpreter.getNil()); 73 74 String [] lines = printError(); 75 76 assertEquals(0, lines.length); 77 } 78 79 private String [] printError() { 80 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream (2048); 81 PrintStream stream = new PrintStream (byteArrayOutputStream); 82 exception.printBacktrace(stream); 83 String output = new String (byteArrayOutputStream.toByteArray()); 84 if (output.trim().length() == 0) { 85 return new String [0]; 86 } else { 87 return output.split("\n"); 88 } 89 } 90 91 private void setBackTrace(int lineCount) { 92 List traceLines = new ArrayList (); 93 for (int i=0; i<lineCount; i++) 94 traceLines.add(RubyString.newString(interpreter, testLine(i))); 95 exception.set_backtrace(RubyArray.newArray(interpreter, traceLines)); 96 } 97 98 private String expectedTraceLine(int index) { 99 return "\tfrom " + testLine(index); 100 } 101 102 private String testLine(int i) { 103 return "Line " + i; 104 } 105 } 106 | Popular Tags |