为什么没有self参数
声明类时,您定义的function在实例中绑定为method。下面是一个实例:>>> def function():
... pass
...
>>> type(function)
>>> class A:
... def b(self):
... print(self)
>>> type(A.b)
>>> a = A()
>>> type(a.b)
# So you have the same behavior between the two following calls
>>> A.b(a)
<__main__.A object at 0x7f734511afd0>
>>> a.b()
<__main__.A object at 0x7f734511afd0>
解决方案
我可以提出一些解决方案,但并不都是有说服力的,取决于您的使用和需要。在
嘲笑全班同学
您可以模拟整个类来重写函数定义。
如前所述,这考虑到您不使用类的抽象。在
^{pr2}$
Wich将输出:>>> from test_mock import test_mock
>>> test_mock()
直接调用函数
我不喜欢这个,因为它会让你改变测试的代码。
您可以将调用从instance.method()转换为class.method(instance)。
这将按预期将参数发送到模拟函数。在# my_input.py
import tensorflow as tf
def data_generator():
for i in itertools.count(1):
yield (i, [1] * i)
def create_dataset():
_load_example = lambda x, y: x+y
buffer_size = 3
output_types = (tf.int64, tf.int64)
output_shapes = (tf.TensorShape([]), tf.TensorShape([None]))
raw_dataset = tf.data.Dataset.from_generator(data_generator, output_types, output_shapes)
shuffled_dataset = tf.data.Dataset.shuffle(raw_dataset, buffer_size)
assert raw_dataset == shuffled_dataset
assert raw_dataset is shuffled_dataset
dataset = shuffled_dataset.map(_load_example)
return dataset
# test_mock.py
import unittest.mock as mk
import my_input
def shuffle(self, buffer_size):
print("Shuffle! {}, {}".format(self, buffer_size))
return self
with mk.patch('my_input.tf.data.Dataset.shuffle') as shuffle_mock:
shuffle_mock.side_effect = shuffle
dataset = my_input.create_dataset()
运行时,将有以下输出:$ python test_mock.py
Shuffle! (, 3)
将使用的方法包装在函数中
这几乎与前面的答案相同,但您可以将其包装为以下内容,而不是从类中调用该方法:# my_input.py
import tensorflow as tf
def data_generator():
for i in itertools.count(1):
yield (i, [1] * i)
def shuffle(instance, buffer_size):
return instance.shuffle(buffer_size)
def create_dataset():
_load_example = lambda x, y: x+y
buffer_size = 3
output_types = (tf.int64, tf.int64)
output_shapes = (tf.TensorShape([]), tf.TensorShape([None]))
raw_dataset = tf.data.Dataset.from_generator(data_generator, output_types, output_shapes)
shuffled_dataset = tf.data.Dataset.shuffle(raw_dataset, buffer_size)
assert raw_dataset == shuffled_dataset
assert raw_dataset is shuffled_dataset
dataset = shuffled_dataset.map(_load_example)
return dataset
# test_mock.py
import unittest.mock as mk
import my_input
def shuffle(self, buffer_size):
print("Shuffle! {}, {}".format(self, buffer_size))
return self
with mk.patch('my_input.shuffle') as shuffle_mock:
shuffle_mock.side_effect = shuffle
dataset = my_input.create_dataset()