db0575122dc07a10e14a1777405c422056a0fb8d
[packages/precise/mcollective.git] / spec / matchers / exception_matchers.rb
1 module MCollective
2   module Matchers
3     def raise_code(*args)
4       CodedExceptionMatcher.new(args)
5     end
6
7     class CodedExceptionMatcher
8       def initialize(args)
9         @args = args
10
11         raise "Need at least an exception to match" if args.size == 0
12
13         @expected_code = @args.shift
14         @expected_data = @args.shift
15
16         @failure_type = nil
17         @failure_expected = nil
18         @failure_got = nil
19       end
20
21       def matches?(actual)
22         begin
23           actual.call
24         rescue => e
25           unless e.is_a?(MCollective::CodedError)
26             @failure_type = :type
27             @failure_expected = "MCollective::CodedError"
28             @failure_got = e.class
29             return false
30           end
31
32           unless [e.code, e.default].include?(@expected_code)
33             @failure_type = :code
34             @failure_expected = @expected_code
35             @failure_got = e.code
36             return false
37           end
38
39           if @expected_data
40             unless e.args == @expected_data
41               @failure_type = :arguments
42               @failure_expected = @expected_data.inspect
43               @failure_got = e.args.inspect
44               return false
45             end
46           end
47         end
48
49         true
50       end
51
52       def failure_message
53         case @failure_type
54           when :type
55             "Expected an exception of type %s but got %s" % [@failure_expected, @failure_got]
56           when :code
57             "Expected a message code %s but got %s" % [@failure_expected, @failure_got]
58           when :arguments
59             "Expected arguments %s but got %s" % [@failure_expected, @failure_got]
60         end
61       end
62
63       def negative_failure_message
64         case @failure_type
65           when :type
66             "Expected an exception of type %s but got %s" % [@failure_got, @failure_expected]
67           when :code
68             "Expected a message code %s but got %s" % [@failure_got, @failure_expected]
69           when :arguments
70             "Expected arguments %s but got %s" % [@failure_got, @failure_expected]
71         end
72       end
73     end
74   end
75 end