|
1
|
|
|
# -*- coding: utf-8 -*- |
|
2
|
|
|
# Copyright (C) 2018 Greenbone Networks GmbH |
|
3
|
|
|
# |
|
4
|
|
|
# SPDX-License-Identifier: GPL-3.0-or-later |
|
5
|
|
|
# |
|
6
|
|
|
# This program is free software: you can redistribute it and/or modify |
|
7
|
|
|
# it under the terms of the GNU General Public License as published by |
|
8
|
|
|
# the Free Software Foundation, either version 3 of the License, or |
|
9
|
|
|
# (at your option) any later version. |
|
10
|
|
|
# |
|
11
|
|
|
# This program is distributed in the hope that it will be useful, |
|
12
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
13
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
14
|
|
|
# GNU General Public License for more details. |
|
15
|
|
|
# |
|
16
|
|
|
# You should have received a copy of the GNU General Public License |
|
17
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
18
|
|
|
|
|
19
|
|
|
import functools |
|
20
|
|
|
|
|
21
|
|
|
|
|
22
|
|
|
class CallableMock: |
|
23
|
|
|
|
|
24
|
|
|
def __init__(self, func): |
|
25
|
|
|
# look like the function we are wrapping |
|
26
|
|
|
functools.update_wrapper(self, func) |
|
27
|
|
|
self.calls = [] |
|
28
|
|
|
self.func = func |
|
29
|
|
|
self.result = None |
|
30
|
|
|
|
|
31
|
|
|
def __call__(self, *args, **kwargs): |
|
32
|
|
|
self.calls.append({'args': args, 'kwargs': kwargs}) |
|
33
|
|
|
|
|
34
|
|
|
if self.result is None and not self.func is None: |
|
35
|
|
|
return self.func(self, *args, **kwargs) |
|
36
|
|
|
|
|
37
|
|
|
return self.result |
|
38
|
|
|
|
|
39
|
|
|
def return_value(self, value): |
|
40
|
|
|
self.result = value |
|
41
|
|
|
|
|
42
|
|
|
def has_been_called(self): |
|
43
|
|
|
assert len(self.calls) > 0, "{0} havn't been called.".format( |
|
44
|
|
|
self.func.__name__) |
|
45
|
|
|
|
|
46
|
|
|
def has_been_called_times(self, times): |
|
47
|
|
|
assert len(self.calls) == times, "{name} haven't been called {times}" \ |
|
48
|
|
|
" times.".format(name=self.func.__name__, times=times) |
|
49
|
|
|
|
|
50
|
|
|
def has_been_called_with(self, *args, **kwargs): |
|
51
|
|
|
if len(self.calls) == 0: |
|
52
|
|
|
assert False |
|
53
|
|
|
|
|
54
|
|
|
lastcall = self.calls[-1] |
|
55
|
|
|
|
|
56
|
|
|
# not sure if this is correct |
|
57
|
|
|
assert lastcall['args'] == args and lastcall['kwargs'] == kwargs, \ |
|
58
|
|
|
"Expected arguments {eargs} {ekwargs} of {name} don't match." \ |
|
59
|
|
|
"Received: {rargs} {rkwargs}".format( |
|
60
|
|
|
name=self.func.__name__, |
|
61
|
|
|
eargs=args, |
|
62
|
|
|
ekwargs=kwargs, |
|
63
|
|
|
rargs=lastcall['args'], |
|
64
|
|
|
rkwargs=lastcall['kwargs'] |
|
65
|
|
|
) |
|
66
|
|
|
|