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
89
90
|
# Copyright (C) 2007, 2008 Jelmer Vernooij <jelmer@samba.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
__all__ = [
'load_tests',
'MockMethod',
'MockProperty',
]
import os
def discover_test_names(module_or_name):
if isinstance(module_or_name, basestring):
match = module_or_name
else:
match = ''
file_names = os.listdir(os.path.dirname(__file__))
test_names = set()
for file_name in file_names:
name, ext = os.path.splitext(file_name)
if name.startswith('test_') and ext == '.py' and match in name:
test_names.add("%s.%s" % (__name__, name))
return test_names
def load_tests(basic_tests, module, loader):
test_names = discover_test_names(module)
basic_tests.addTest(loader.loadTestsFromModuleNames(test_names))
return basic_tests
class MockMethod(object):
@classmethod
def bind(klass, test_instance, obj, method_name,
return_value=None, raise_error=None, raise_on=1):
original_method = getattr(obj, method_name)
test_instance.addCleanup(setattr, obj, method_name, original_method)
setattr(obj, method_name, klass(return_value, raise_error, raise_on))
def __init__(self, return_value=None, raise_error=None, raise_on=1):
self.called = False
self.call_count = 0
self.args = None
self.kwargs = None
self.return_value = return_value
self.raise_error = raise_error
self.raise_on = raise_on
def __call__(self, *args, **kwargs):
self.called = True
self.call_count += 1
self.args = args
self.kwargs = kwargs
if self.raise_error is not None and self.call_count == self.raise_on:
raise self.raise_error
return self.return_value
class MockProperty(MockMethod):
@classmethod
def bind(klass, test_instance, obj, method_name, return_value=None):
original_method = getattr(obj, method_name)
test_instance.addCleanup(setattr, obj, method_name, original_method)
mock = klass(return_value)
setattr(obj, method_name, property(mock.get_value, mock.set_value))
return mock
def get_value(self, other):
self.called = True
return self.return_value
def set_value(self, other, value):
self.called = True
self.return_value = value
|