【发布时间】:2021-10-11 05:20:03
【问题描述】:
我有一个示例类,它读取保存的 Tensorflow 模型并运行预测
class Sample():
## all it does is creates a new column with predictions
def __init__(self, tf_model):
self.tf_model = tf_model
def tf_process(self, x):
##some other preprocessing
x["tf_predictions"] = self.tf_model.predict(x)
return x
def predict(self, x):
predictions = self.tf_process(x)
return predictions
无需加载模型的单元测试代码:
import unittest
import pandas as pd
from unittest import TestCase, mock
from my_package.sample_model import Sample
class TestSample(unittest.TestCase):
def test_predict(self):
with mock.patch("Sample.tf_process") as process:
process.return_value = pd.DataFrame("hardcoded_value")
#to check: process.return_value = Output (Sample.predict())
目标:
为了比较process.return_value 和Output of predict method in Sample,但要做到这一点,我仍然需要加载模型,我不明白mock 在这里有什么用,因为无论如何我都必须调用predict 方法将其与process.return_value 进行比较。任何建议都会有所帮助
【问题讨论】:
-
嗯,这取决于你在测试什么。如果你想测试预测,你不能模拟它,那会违背目的。如果您想在不测试
predict的情况下测试tf_process,请改为模拟predict。使用当前的模拟,您只能使用正确的参数测试predict调用tf_process。 -
@MrBeanBremen 我只想测试是否创建了
tf_predictions列?关于如何测试的任何建议。 -
正如我所写 - 在这种情况下,您可以模拟
predict(不确定它属于哪个类)以返回一些合理的东西。
标签: python mocking pytest python-unittest pytest-mock