1
|
|
|
from unittest import TestCase |
2
|
|
|
|
3
|
|
|
from coalib.misc.Annotations import typechain |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
class AnnotationsTest(TestCase): |
|
|
|
|
7
|
|
|
|
8
|
|
|
def test_empty(self): |
9
|
|
|
with self.assertRaises(TypeError) as ctx: |
|
|
|
|
10
|
|
|
typechain() |
11
|
|
|
self.assertEqual(str(ctx.exception), "No arguments were provided.") |
12
|
|
|
|
13
|
|
|
def test_with_lambda(self): |
14
|
|
|
function = typechain(lambda x: int(x) > 0) |
15
|
|
|
with self.assertRaises(ValueError): |
|
|
|
|
16
|
|
|
function("str") |
17
|
|
|
self.assertEqual(function("10"), True) |
18
|
|
|
|
19
|
|
View Code Duplication |
def test_with_function(self): |
|
|
|
|
20
|
|
|
def positive(val): |
21
|
|
|
val = int(val) |
22
|
|
|
if val > 0: |
23
|
|
|
return val |
24
|
|
|
raise ValueError |
|
|
|
|
25
|
|
|
function = typechain(positive, ord) |
|
|
|
|
26
|
|
|
with self.assertRaises(ValueError): |
27
|
|
|
function(0) |
28
|
|
|
with self.assertRaises(ValueError): |
29
|
|
|
function("str") |
30
|
|
|
self.assertEqual(function("10"), 10) |
31
|
|
|
self.assertEqual(function("0"), 48) |
32
|
|
|
|
33
|
|
|
def test_with_function_without_arguments(self): |
34
|
|
|
def dummy(): |
35
|
|
|
return 10 |
36
|
|
|
function = typechain(dummy) |
|
|
|
|
37
|
|
|
with self.assertRaises(ValueError): |
|
|
|
|
38
|
|
|
function(0) |
39
|
|
|
|
40
|
|
View Code Duplication |
def test_with_custom_type(self): |
|
|
|
|
41
|
|
|
class Positive: |
42
|
|
|
|
43
|
|
|
def __init__(self, val): |
44
|
|
|
val = int(val) |
|
|
|
|
45
|
|
|
if val > 0: |
46
|
|
|
self.val = val |
47
|
|
|
else: |
48
|
|
|
raise ValueError |
|
|
|
|
49
|
|
|
|
50
|
|
|
function = typechain(Positive, ord) |
|
|
|
|
51
|
|
|
with self.assertRaises(ValueError): |
52
|
|
|
function(0) |
53
|
|
|
obj = function("10") |
54
|
|
|
self.assertIsInstance(obj, Positive) |
|
|
|
|
55
|
|
|
self.assertEqual(obj.val, 10) |
56
|
|
|
self.assertEqual(function("0"), 48) |
57
|
|
|
|
58
|
|
|
def test_with_empty_class(self): |
59
|
|
|
class Dummy: |
60
|
|
|
pass |
61
|
|
|
|
62
|
|
|
function = typechain(Dummy) |
|
|
|
|
63
|
|
|
with self.assertRaises(ValueError): |
|
|
|
|
64
|
|
|
function("str") |
65
|
|
|
dummy = Dummy() |
66
|
|
|
self.assertEqual(function(dummy), dummy) |
|
|
|
|
67
|
|
|
|