简体   繁体   English

使用 pytest 时装饰器中的 mocking 对象

[英]mocking objects within a decorator while using pytest

In the below example, I have a decorator.在下面的示例中,我有一个装饰器。 In the decorator, I am instantiating a DB connection class.在装饰器中,我正在实例化一个 DB 连接 class。 I have a test class below, where I want to mock the DB connection class within the decorator.我在下面有一个测试 class ,我想在装饰器中模拟数据库连接 class 。 How can I do that?我怎样才能做到这一点?

# importing libraries 
import time 
import math 

# decorator to calculate duration 
# taken by any function. 
def calculate_time(func): 

    # added arguments inside the inner1, 
    # if function takes any arguments, 
    # can be added like this. 
    def inner1(*args, **kwargs): 

        db_conn = DBConn()
        # storing time before function execution 
        begin = time.time() 

        func(*args, **kwargs) 

        # storing time after function execution 
        end = time.time() 
        db_conn.logTime(begin, end)
        print("Total time taken in : ", func.__name__, end - begin) 

    return inner1 



# this can be added to any function present, 
# in this case to calculate a factorial 
@calculate_time
def test_factorial(num): 

    # sleep 2 seconds because it takes very less time 
    # so that you can see the actual difference 
    time.sleep(2) 
    print(math.factorial(num)) 

# calling the function. 
factorial(10) 

Ok, to make this clearer:好的,为了更清楚:
Provided your modules live in the package mypackage , and your module calculate_time.py with the decorator looks like:假设您的模块位于 package mypackage中,并且您的模块calculate_time.py与装饰器看起来像:

from mypackage.dbconn import DBConn

def calculate_time(func):
    def inner1(*args, **kwargs):
        ...

And you have the module factorial.py with:你有模块factorial.py

from mypackage.calculate_time import calculate_time

@calculate_time
def factorial(num):
    time.sleep(2)
    print(math.factorial(num))

Then your test could look like this:然后您的测试可能如下所示:

from unittest.mock import patch    
from mypackage.factorial import factorial

class FakeConn:
    def logTime(self, begin, end):
        print(begin, end)

@patch('mypackage.calculate_time.DBConn', new=FakeConn)
def test_factorial():
    print(factorial(10))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM