python-3.x - 测试一个函数是否被调用

标签 python-3.x pytest

我正在我的应用程序中编写测试,以测试是否调用了一个方法。这是在 Python 3.4.3 和 pytest-2.9.2 中运行的。我是 PyTest 的新手,但对 RSpec 和 Jasmine 非常熟悉。我不确定如何设置测试以便它测试 imaplib.IMAP4_SSL 被调用。

我的应用程序结构:

/myApp
  __init__.py
  /shared
    __init__.py
    email_handler.py
  /tests
    __init__.py
    test_email_handler.py

email_handler.py
import imaplib
def email_conn(host):
    mail = imaplib.IMAP4_SSL(host)  
    return mail;

到目前为止我的测试:
test_email_handler.py
import sys   
sys.path.append('.')  

from shared import email_handler 

def test_email_handler():   
     email_handler.email_conn.imaplib.IMAP4_SSL.assert_called_once 

这显然失败了。如何设置此测试以测试 imaplib.IMAP4_SSL 是否被调用?或者有没有更好的方法在我的应用程序中设置测试套件,以便更有效地支持测试?

最佳答案

这是一个使用 unittest.mock 的示例来自 Python 3.5.2 标准库:

test_email_handler.py

import sys
from unittest import mock
sys.path.append('.')

from shared import email_handler

@mock.patch.object(email_handler.imaplib, 'IMAP4_SSL')
def test_email_handler(mock_IMAP4_SSL):
    host = 'somefakehost'
    email_handler.email_conn(host)
    mock_IMAP4_SSL.assert_called_once_with(host)

请注意 @mock.patch.object用模拟对象替换 IMAP4_SSL 的装饰器,该对象作为参数添加。 Mock 是一种强大的测试工具,可能会让新用户感到困惑。我推荐以下内容以供进一步阅读:

https://www.toptal.com/python/an-introduction-to-mocking-in-python

http://engineroom.trackmaven.com/blog/mocking-mistakes/

http://alexmarandon.com/articles/python_mock_gotchas/

关于python-3.x - 测试一个函数是否被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38362469/

相关文章:

python - 如何测试 Connexion/Flask 应用程序?

python - pytest hooks可以使用fixtures吗?

python-3.x - Visual Studio Code Python 调试 "Exception has occurred SystemExit"

testing - pytest : how to create and read a file inside a test

python-3.x - Python copy_expert 加载带有空值的数据时出现问题

python - 创建以文件名作为键的目录字典

ssh - 如何在整个 pytest 套件中重用 ssh 连接

Python 3 模块和包相对导入不起作用?

python - tkinter - wm 协议(protocol)不处理 WM_HELP 消息

python - 导入尚不存在的模块