1
|
|
|
from unittest import TestCase |
2
|
|
|
|
3
|
|
|
from typish import ClsDict |
4
|
|
|
from typish._classes import ClsFunction |
5
|
|
|
|
6
|
|
|
|
7
|
|
|
class TestClsFunction(TestCase): |
8
|
|
|
def test_invalid_initialization(self): |
9
|
|
|
# Only ClsDict or dict is allowed |
10
|
|
|
with self.assertRaises(TypeError): |
11
|
|
|
ClsFunction(123) |
12
|
|
|
|
13
|
|
|
def test_with_dict(self): |
14
|
|
|
function = ClsFunction({ |
15
|
|
|
int: lambda x: x * 2, |
16
|
|
|
str: lambda x: '{}_'.format(x), |
17
|
|
|
}) |
18
|
|
|
|
19
|
|
|
self.assertEqual(4, function(2)) |
20
|
|
|
self.assertEqual('2_', function('2')) |
21
|
|
|
|
22
|
|
|
def test_with_cls_dict(self): |
23
|
|
|
function = ClsFunction(ClsDict({ |
24
|
|
|
int: lambda x: x * 2, |
25
|
|
|
str: lambda x: '{}_'.format(x), |
26
|
|
|
})) |
27
|
|
|
|
28
|
|
|
self.assertEqual(4, function(2)) |
29
|
|
|
self.assertEqual('2_', function('2')) |
30
|
|
|
|
31
|
|
|
def test_multiple_args(self): |
32
|
|
|
function = ClsFunction({ |
33
|
|
|
int: lambda x, y: x * y, |
34
|
|
|
str: lambda x, y: '{}{}'.format(x, y), |
35
|
|
|
}) |
36
|
|
|
|
37
|
|
|
self.assertEqual(6, function(2, 3)) |
38
|
|
|
self.assertEqual('23', function('2', 3)) |
39
|
|
|
|
40
|
|
|
def test_understands(self): |
41
|
|
|
function = ClsFunction({ |
42
|
|
|
int: lambda _: ..., |
43
|
|
|
str: lambda _: ..., |
44
|
|
|
}) |
45
|
|
|
self.assertTrue(function.understands(1)) |
46
|
|
|
self.assertTrue(function.understands('2')) |
47
|
|
|
self.assertTrue(not function.understands(3.0)) |
48
|
|
|
|
49
|
|
|
def test_call_no_args(self): |
50
|
|
|
function = ClsFunction({ |
51
|
|
|
int: lambda x: 1, |
52
|
|
|
}) |
53
|
|
|
|
54
|
|
|
with self.assertRaises(TypeError): |
55
|
|
|
function() |
56
|
|
|
|
57
|
|
|
def test_call_invalid_args(self): |
58
|
|
|
function = ClsFunction({ |
59
|
|
|
int: lambda x: 1, |
60
|
|
|
}) |
61
|
|
|
|
62
|
|
|
with self.assertRaises(TypeError): |
63
|
|
|
function(1, 2) # The lambda expects only 1 argument. |
64
|
|
|
|