current position:Home>Python testing - the patches in Python
Python testing - the patches in Python
2022-02-02 01:11:48 【jingliang】
What is? Patch
Mock It can be seen everywhere in unit testing . stay Python In unit testing , Common are unittest and pytest.unittest Corresponding Mock Kuo is unittest.mock,pytest The corresponding is pytest-mock. these two items. Mock All exist in the library Patchers,Patchers And Mock Interwovenness
Pytest-mock Essentially with unittest.mock It's the same API, So let's start with unittest.mock Speaking of
A simple example
When the test goal is BubbleTeaShop
Of make_milk_tea
Method , But I don't want to actually call Kitchen
Of make_milk_tea
When the method is used , You can use the @patch()
Method pair class Conduct patch, And use instance.make_milk_tea.return_value
Specifies the return value of the method
The above example bubbleteashop.py
Medium Kitchen
By @patch
Replaced by ,@patch
What is returned is a unittst.mock
Medium MagicMock
object
Where to Patch
Tell in official documents Patch Mentioned before using
Note: The key is to do the patching in the right namespace. See the section where to patch.
The basic principle is that you patch where an object is looked up, which is not necessarily the same place as where it is defined.
That is to say object Found ( By using ) The place where patch, Not defined places . And the document also mentions a premise :object It's through from import
Imported
In the above example , We go through from src.kitchen import Kitchen
How to import Kitchen
,
therefore patch Yes. src.bubbleteashop.Kitchen
, Instead of src.kictchen.Kitchen
The reasons are related to python The assignment mechanism is directly related to ( The picture is quoted from Ned Batchelder - Python Names and Values)
Ned Batchelder stay Pycon 2015 When sharing in ,Python The variable in is the name of the reference value . If you assign a second name , These names do not refer to each other , They all refer to the same value (x And y All point to 23). If you then assign one of the names again (x=12), The other name is not affected (y Still 23)
In the previous example ,from src.kitchen import Kitchen
It is equivalent to importing src.kitchen
, And then you do the assignment kitchen = src.kitchen.Kitchen
,kitchen Like y,src.kitchen.Kitchen Like x.
If the src.bubbleteashop.Kitchen
Conduct patch when ,bubbleteashop.py
Of Kitchen
Will be replaced with MagicMock, This is exactly what you want to achieve in the test
If the src.kictchen.Kitchen
Conduct patch when ,kitchen.py
Of Kitchen
Will be replaced with MagicMock, and bubbleteashop.py
Of Kitchen
Unaffected , Not by mock
If we import src.kitchen
Import ?
import src.kitchen
It's equivalent to being in bubbleteashop.py
Chinese envoy src.kitchen
Refers to the whole kitchen modular , visit src.kitchen.make_milk_tea
Will enter the kitchen in , find make_milk_tea
, And execute it .
If the src.kictchen.Kitchen
Conduct patch when ,kitchen.py
Of Kitchen
Will be replaced with MagicMock, because bubbleteashop.py
Of src.kitchen
Refers to the whole kitchen modular , therefore mock It will also affect bubbleteashop.py
Patch scope
Patch There are three main ways , In every way scope Different , Different use scenarios
Context manager
Use with Make a statement patch,patch The scope of is limited to with The body of a statement
Function decorator
As in the above example, the created on the test method @patch(‘src.bubbleteashop.Kitchen’)
It's just one. function decorator, Applies only to the current test method
Class decorator
Same use @pathch()
Method to create , It's just created in class On , Act on this test class Every method of , It is applicable to multiple test methods sharing the same patcher
The Patchers in Python It's rich in content , You can refer to unittest and py-test Official documents of , Have the opportunity to continue sorting patchers More to use
copyright notice
author[jingliang],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202020111458130.html
The sidebar is recommended
- How IOS developers learn Python Programming 22 - Supplement 1
- Python can meet any API you need
- Python 3 process control statement
- The 20th of 120 Python crawlers, 1637. All the way business opportunity network joined in data collection
- Datetime of pandas time series preamble
- How to send payslips in Python
- [Python] closure and scope
- Application of Python Matplotlib color
- leetcode 1627. Graph Connectivity With Threshold (python)
- Python thread 08 uses queues to transform the transfer scenario
guess what you like
-
Python: simple single player strange game (text)
-
Daily python, chapter 27, Django template
-
TCP / UDP communication based on Python socket
-
Use of pandas timestamp index
-
leetcode 148. Sort List(python)
-
Confucius old book network data collection, take one anti three learning crawler, python crawler 120 cases, the 21st case
-
[HTB] cap (datagram analysis, setuid capability: Python)
-
How IOS developers learn Python Programming 23 - Supplement 2
-
How to automatically identify n + 1 queries in Django applications (2)?
-
Data analysis starts from scratch. Pandas reads HTML pages + data processing and analysis
Random recommended
- 1313. Unzip the coding list (Java / C / C + + / Python / go / trust)
- Python Office - Python edit word
- Collect it quickly so that you can use the 30 Python tips for taking off
- Strange Python strip
- Python crawler actual combat, pyecharts module, python realizes China Metro data visualization
- DOM breakpoint of Python crawler reverse
- Django admin custom field stores links in the database after uploading files to the cloud
- Who has powder? Just climb who! If he has too much powder, climb him! Python multi-threaded collection of 260000 + fan data
- Python Matplotlib drawing streamline diagram
- The game comprehensively "invades" life: Python releases the "cool run +" plan!
- Python crawler notes: use proxy to prevent local IP from being blocked
- Python batch PPT to picture, PDF to picture, word to picture script
- Advanced face detection: use Dlib, opencv and python to detect face markers
- "Python 3 web crawler development practice (Second Edition)" is finally here!!!!
- Python and Bloom filters
- Python - singleton pattern of software design pattern
- Lazy listening network, audio novel category data collection, multi-threaded fast mining cases, 23 of 120 Python crawlers
- Troubleshooting ideas and summary of Django connecting redis cluster
- Python interface automation test framework (tools) -- interface test tool requests
- Implementation of Morse cipher translator using Python program
- [Python] numpy notes
- 24 useful Python tips
- Pandas table beauty skills
- Python tiktok character video, CV2 module, Python implementation
- I used Python to climb my wechat friends. They are like this
- 20000 words take you into the python crawler requests library, the most complete in history!!
- Answer 2: why can you delete the table but not update the data with the same Python code
- [pandas learning notes 02] - advanced usage of data processing
- How to implement association rule algorithm? Python code and powerbi visualization are explained to you in detail (Part 2 - actual combat)
- Python adds list element append() method, extend() method and insert() method [details]
- python wsgi
- Introduction to Python gunicorn
- Python dictionary query key value pair methods and examples
- Opencv Python reads video, processes and saves it frame by frame
- Python learning process and bug
- Imitate the up master and realize a live broadcast room controlled by barrage with Python!
- Essence! Configuration skills of 12 pandas
- [Python automated operation and maintenance road] path inventory
- Daily automatic health punch in (Python + Tencent cloud server)
- [Python] variables, comments, basic data types