简体   繁体   English

Python:知道从单元测试调用函数吗?

[英]Python: know function is called from a unittest?

Is there a way to know in Python if a function is called from the context of a unittest execution or a debugging run? 在Python中是否有一种方法可以知道是否从单元测试执行或调试运行的上下文中调用了函数?

For the context, I am trying to unittest a code where I use functions that perform a database call. 对于上下文,我试图在使用执行数据库调用的函数的情况下对代码进行单元测试。 In order to avoid database calls during the test of that function (DB calls are tested separately), I am trying to make the DB IO functions aware of their environement and to mock when they are called within a unittest and log additional variables during a debug run. 为了避免在对该函数进行测试期间对数据库进行调用(分别对DB调用进行了测试),我试图使DB IO函数了解其环境,并在单元测试中模拟它们在调用时的状态,并在调试期间记录其他变量跑。

My current aproach is to read/write environment variables, but it seems a little bit of an overkill and I think Python must have a better mechanism for that. 我目前的方法是读取/写入环境变量,但这似乎有点过头了,我认为Python必须为此提供更好的机制。

Edit: Here is the example of a function I am trying to unittest: 编辑:这是我尝试进行单元测试的功能的示例:

from Database_IO import Database_read

def some_function(significance_level, time_range)
    data = Database_read(time_range)
    significant_data = data > significance_level
    return significant_data

In my opinion, if you write your function to behave in a different way when tested, you are not really testing it. 我认为,如果您编写的函数在测试时以不同的方式运行,那么您实际上并不是在测试它。

To test the function I'd mock.patch() the database object, and then check it has used correctly in your function. 为了测试该函数,我mock.patch()数据库对象mock.patch() ,然后检查它是否在函数中正确使用。

The most difficult thing when you start using the mock library is to find the correct object to replace . 开始使用模拟库时,最困难的事情是找到要替换的正确对象

In your example, if in your_module you import the Database_read object from the Database_IO module, you can test it by using a code similar to the following 在您的示例中,如果在your_moduleDatabase_IO模块导入Database_read对象,则可以使用类似于以下代码的方式对其进行测试

with mock.patch('your_module.Database_read') as dbread_mock:
    # prepare the dbread_mock
    dbread_mock.return_value = 10
    # execute a test call
    retval = some_function(3, 'some range')
    # check the result
    dbread_mock.assert_called_with('some range')

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

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