2017年8月25日 星期五

[ Python 常見問題 ] Using mock patch to mock an instance method

Source From Here 
Question 
I'm trying to mock something while testing a Django app using the imaginatively named Mock testing library. I can't seem to quite get it to work, I'm trying to do this: 
- models.py 
  1. #!/usr/bin/env python3  
  2. class Promotion(object):  
  3.     def __init__(self):  
  4.         pass  
  5.   
  6.     def bar(self):  
  7.         return "Do something I don't want!"  
How do I mock the method bar of the creating object of class Promotion

How-To 
Check below sample code: 
- test.py 
  1. import models  
  2. from unittest import TestCase  
  3. from unittest.mock import patch  
  4.   
  5. class ViewsDoSomething(TestCase):  
  6.     def setUp(self):  
  7.         self.mockMsg = 'Do what I want'  
  8.   
  9.   
  10.     @patch.object(models.Promotion, 'bar')  
  11.     def test_enter_promotion(self, mockObj):  
  12.         mockObj.return_value = self.mockMsg  
  13.   
  14.         p = models.Promotion()  
  15.         self.assertTrue(p.bar() == self.mockMsg)  
Then you can test it this way: 
# pytest -v test.py
...
test.py::ViewsDoSomething::test_enter_promotion PASSED
...


Supplement 
Python 文章收集 - 用 Mock 來做 Python Unit Test 
Python 文章收集 - pytest introduction

沒有留言:

張貼留言

[ Python 文章收集 ] SQLAlchemy quick start with PostgreSQL

Source From   Here   Preface   This is a quick tutorial for getting started with   SQLAlchemy Core API .   Prerequisites   In this quick st...