需要在 Django 中模拟一个非测试方法
Need to mock a non test method in Django
我有一个测试 class 就像下面的测试:
@mock.patch('myapp.apps.mytask1.views.image_processing.apply_async')
class SortAPITestCase(APITestCase):
def hit_scan("""some args"""):
scan_uri = 'some url'
data = 'some data'
resp = self.client.post(scan_uri, data=data)
id = resp.data['id']
self.assertEqual(resp.status_code, 201)
return data, id
def setUp(self):
super(SortAPITestCase, self).setUp()
self.scan_data, self.id = self.hit_scan()
def test_1(self, mock_obj):
.....
def test_2(self, mock_obj):
.....
在 myapp.apps.mytask1.views
中,有 Scan API,其中有 post
调用 celery 任务的方法,例如:
def post("""some args"""):
""" here there is a celery task that gets called"""
image_processing.apply_async(
args=[img_data], queue='image', countdown=10
)
celery 任务在调用时会打印出一条消息,如下所示
@shared_task
def image_processing(img_data):
if os.isfile(img_file):
print "File Not Present"
因此,只要 img_file
不存在,它就会打印出 File Not Present
。当测试 fucntions(with mock) post 到 Scan API 时,由于模拟,此打印消息不会打印在控制台上。但是 hit_scan()
方法在 post 扫描 API 时,由于 celery 任务没有被模拟,所以会打印此消息。我可以在 hit_scan
中模拟 celery 任务吗??
那么,有什么办法可以防止在 运行 测试时打印语句出现在控制台中??
顺便说一句,所有的测试用例都通过了。从这个角度看没有问题。我只是想让控制台看起来更好,只有 ....
而不是 celery 任务的打印语句也出现了。
编辑:解决了问题。这是我所做的
@mock.patch('myapp.apps.mytask1.views.image_processing.apply_async')
def hit_scan(self, mock_obj, """some args"""):
这与测试之外的方法无关; Python 没有这样的区别。但是,您的模拟语法是错误的:您需要通过 Python 模块路径而不是文件路径来引用要模拟的内容。
@mock.patch('path.something.file.apply_async')
我有一个测试 class 就像下面的测试:
@mock.patch('myapp.apps.mytask1.views.image_processing.apply_async')
class SortAPITestCase(APITestCase):
def hit_scan("""some args"""):
scan_uri = 'some url'
data = 'some data'
resp = self.client.post(scan_uri, data=data)
id = resp.data['id']
self.assertEqual(resp.status_code, 201)
return data, id
def setUp(self):
super(SortAPITestCase, self).setUp()
self.scan_data, self.id = self.hit_scan()
def test_1(self, mock_obj):
.....
def test_2(self, mock_obj):
.....
在 myapp.apps.mytask1.views
中,有 Scan API,其中有 post
调用 celery 任务的方法,例如:
def post("""some args"""):
""" here there is a celery task that gets called"""
image_processing.apply_async(
args=[img_data], queue='image', countdown=10
)
celery 任务在调用时会打印出一条消息,如下所示
@shared_task
def image_processing(img_data):
if os.isfile(img_file):
print "File Not Present"
因此,只要 img_file
不存在,它就会打印出 File Not Present
。当测试 fucntions(with mock) post 到 Scan API 时,由于模拟,此打印消息不会打印在控制台上。但是 hit_scan()
方法在 post 扫描 API 时,由于 celery 任务没有被模拟,所以会打印此消息。我可以在 hit_scan
中模拟 celery 任务吗??
那么,有什么办法可以防止在 运行 测试时打印语句出现在控制台中??
顺便说一句,所有的测试用例都通过了。从这个角度看没有问题。我只是想让控制台看起来更好,只有 ....
而不是 celery 任务的打印语句也出现了。
编辑:解决了问题。这是我所做的
@mock.patch('myapp.apps.mytask1.views.image_processing.apply_async')
def hit_scan(self, mock_obj, """some args"""):
这与测试之外的方法无关; Python 没有这样的区别。但是,您的模拟语法是错误的:您需要通过 Python 模块路径而不是文件路径来引用要模拟的内容。
@mock.patch('path.something.file.apply_async')