2016-10-05 20 views
1

嘲笑非测试方法我有一个测试类,就像下面这样:需要在Django

@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,有扫描API,那里是post方法,它调用芹菜任务像:

def post("""some args"""): 
    """ here there is a celery task that gets called""" 
    image_processing.apply_async(
     args=[img_data], queue='image', countdown=10 
    ) 

芹菜任务打印出来时,它在一定程度上被称为像下面的消息

@shared_task 
def image_processing(img_data): 
    if os.isfile(img_file): 
     print "File Not Present" 

因此,只要img_file不存在,它将打印出File Not Present。当测试结果(使用模拟)发布到Scan API时,由于模拟,此打印消息不会在控制台上打印。但是当发布到Scan API时,这个消息会被打印出来,因为芹菜任务不会被嘲弄。我可以嘲笑hit_scan中的芹菜任务吗?

所以,当我运行测试时,是否有办法防止打印语句在控制台中出现?

顺便说一句,所有的测试案例通过。从这个角度来看没有问题。我只想让控制台看起来更好,只有....而不是芹菜任务的打印语句也显示出来。

编辑:解决了这个问题。这是我做的

@mock.patch('myapp.apps.mytask1.views.image_processing.apply_async') 
def hit_scan(self, mock_obj, """some args"""): 

回答

0

这与测试之外的方法没有关系; Python没有这样的区别。然而,你的模拟语法是错误的:你需要通过Python模块路径引用你想要模拟的东西,而不是文件路径。

@mock.patch('path.something.file.apply_async') 
+0

我已经用实际的'mock.patch()'编辑了这个问题。当'hit_scan()'在'test_'函数中被调用时,它不会在芹菜任务中打印语句。我检查过.. –

+0

你提到的事情不是问题。希望你已经看到我编辑的问题..谢谢 –

+0

谢谢...我解决了这个问题。检查了它 –