简体   繁体   中英

Mock a function in a Python whl file

I'm trying to write a test for a function that calls a function in a .whl file, but I'm struggling to mock the function in the wheel. I have the wheel installed in my virtual environment - I installed the wheel with pip install my_wheel.whl while in the environment. The package that's in the wheel is called my_package .

The function I want to test looks something like this:

from my_package import wheel_function

def my_func():
   x = wheel_function()
   return x + 5 

I want to mock wheel_function so the test just looks at my_func .

My test script :

import pytest

def mock_wheel_function():
    return 5

def test_my_func(mocker):
   my_mock = mocker.patch("src.wheels.my_wheel.path.to.wheel_function", 
                          side_effect=mock_wheel_function)
   # (Do stuff)

I get the following error: AttributeError: module 'src.wheels' has no attribute 'my_wheel' .

My directory structure is like this.

src
| wheels
|........ my_wheel.whl
| modules
|........ my_module

tests
| - test_modules
|........ test_my_module


If I try to pass in the path to the module in the virtual environment (ie /Users/me/venv/lib/python3.7/site-packages/.... ), I get ModuleNotFoundError: module '/Users/me/venv/lib/python3' not found .

Any ideas? Thank you

When using mocker.patch , you must provide the Python import path to the object you are mocking, not the relative filesystem path.

Since wheel_function is contained in the module my_package , you will want to setup your mocker as

my_mock = mocker.patch(
    "my_package.wheel_function", 
    side_effect=mock_wheel_function
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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