Runtime assertions for Ruby
literal.fun
ruby
1# frozen_string_literal: true
2
3include Literal::Types
4
5test "===" do
6 enumerable_interface = _Interface(:each, :map, :select)
7
8 assert enumerable_interface === []
9 assert enumerable_interface === Set.new
10
11 refute enumerable_interface === 42
12 refute enumerable_interface === "string"
13 refute enumerable_interface === nil
14end
15
16test "hierarchy" do
17 assert_subtype _Interface(:a), _Interface(:a)
18 assert_subtype _Interface(:a, :b), _Interface(:a)
19 assert_subtype _Interface(:a, :b), _Interface(:a, :b)
20 assert_subtype _Callable, _Interface(:call)
21 assert_subtype _Procable, _Interface(:to_proc)
22
23 refute_subtype _Interface(:b), _Interface(:a)
24 refute_subtype _Interface(:a), _Interface(:a, :b)
25 refute_subtype Proc, _Interface(:to_proc, :random_method)
26
27 assert_subtype "Hello", _Interface(:to_s)
28 assert_subtype 1, _Interface(:+, :-)
29 assert_subtype Object.new, _Interface(:inspect)
30 assert_subtype 1.234, _Interface(:to_i)
31 assert_subtype nil, _Interface(:nil?)
32 assert_subtype true, _Interface(:to_s)
33 assert_subtype false, _Interface(:to_s)
34end
35
36test "error message" do
37 error = assert_raises Literal::TypeError do
38 Literal.check(nil, _Interface(:each, :map, :select))
39 end
40
41 assert_equal error.message, <<~MSG
42 Type mismatch
43
44 Expected: _Interface(:each, :map, :select)
45 Actual (NilClass): nil
46 MSG
47end