-
Notifications
You must be signed in to change notification settings - Fork 49
/
example.rb
executable file
·89 lines (77 loc) · 1.65 KB
/
example.rb
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
require 'stringio'
require 'pp'
def run_fragment(code, file=__FILE__)
out_io = $stdout = StringIO.new
result = ''
begin
result = eval(code, binding, file)
ensure
$stdout = STDOUT
end
[result, out_io.string]
end
def example(code, file=__FILE__)
run_example(0, code, file)
end
def example_trunc(code)
run_example(5, code)
end
def example_expected(expected_value, code)
result, output = run_fragment(code)
raise 'unexpected value' unless result == expected_value
puts code
end
def example_true(code)
result, output = run_fragment(code)
raise 'unexpected value' unless result
puts code
end
def example_false(code)
result, output = run_fragment(code)
raise 'unexpected value' if result
puts code
end
def run_example(max_output_lines, code, file=__FILE__)
result, output = run_fragment(code, file)
print_output(code, max_output_lines, output)
[result, output]
end
def print_output(code, max_output_lines, output)
puts "==========================="
puts code
puts
puts "==="
puts
if max_output_lines <= 0
puts output
else
count = 0
output.each_line do |line|
puts line
count += 1
break if count >= max_output_lines
end
puts("...")
end
puts
end
def assert(fact, mesg='assertion failed')
raise mesg unless fact
end
def assert_false(fact, mesg='assertion failed')
raise mesg if fact
end
def expect_error(code)
output = ''
result = ''
begin
result, output = run_fragment(code)
rescue Exception => e
output += "\n"
output += e.to_s
print_output(code, 0, output )
else
print_output(code, 0, output )
raise "*** No exception raised ***"
end
end