python mockers和pytest对函数的补丁出错

0md85ypi  于 2023-04-04  发布在  Python
关注(0)|答案(1)|浏览(93)

我正在尝试使用pytest和mocker来测试我正在编写的一个python包。这是我的repo的大纲(假设包名为hoopla

hoopla
|- library
  |- __init__.py
  |- general
  |- exceptions
  |- bourhaha 
|- tests
  |- __init__.py
  |- test_brouhaha

general.py中,我有一些函数可以通过包和包中的文件使用。例如:

  • general.py包含函数validate_email_exists()
  • brouhaha.py包含一个名为create_username()的函数,它调用函数validate_email_exists()

test_brouhaha.py内部,我想在测试函数create_username()时模拟validate_email_exists()调用,因为它调用外部系统。
当我尝试使用pytest和pytst-mock模拟这个调用时,我得到一个错误,说No Module...(见下文)。
x一个一个一个一个x一个一个二个一个x一个一个三个一个
在我的代码中,我最初用

mock_email_exists = mocker.patch("library.brouhaha.general.validate_email_exists")
mock_email_exists.return_value = False

这会抛出错误

ModuleNotFoundError: No module named 'library.brouhaha.general'; 'library.brouhaha' is not a package

当我尝试

mock_email_exists = mocker.patch("library.general.validate_email_exists")
mock_email_exists.return_value = False

没有错误,但是测试失败,因为函数返回True

6ojccjat

6ojccjat1#

问题出在patch()函数使用的路径中。正确的路径是:

# CORRECT PATCHING
mock_email_exists = mocker.patch("library.bourhaha.validate_email_exists")

通过这种方式,您可以将mock_email_existsreturn_value设置为False,就像您在测试中正确做的那样。但是此时您必须更改assert指令,因为当函数validate_email_exists()返回False时,函数create_username()返回False
所以正确的测试函数是:

from library.bourhaha import *

def test_create_username(mocker):
    # WATCH to the path = 'library.bourhaha.validate_email_exists'
    mock_email_exists = mocker.patch("library.bourhaha.validate_email_exists")
    mock_email_exists.return_value = False
    # I have change the assert test (assert ---> assert not)
    assert not create_username("test")

您的模块general.pybourhaha.py非常完美。

相关问题