简体   繁体   中英

Mock thread calls inside pytest-mock

I have a simple code base like below:

import threading
import time

class Demo:
    def __init__(self):
        self._run_thread = False

    def start(self):
        if not self._run_thread:
            print("Thread has not run")
            threading.Thread(target=self.counter, args=(20, )).start()
            return 20
        else:
            print("Thread has run")
            return None


    def counter(self, value):
        self._run_thread = True
        for i in range(value):
            print(f"Inside counter with value {i}")
            time.sleep(3)



if __name__ == "__main__":
    d = Demo()
    d.start()
    d.start()

The first time start function is called the thread would run and the next time it would be called it would not since the flag(_run_thread) is set.

The code runs very fine it itself.

However it does not work as expected when i try to run tests against this code. Below is my test code:

import app

def dummy_counter(self, value):
    self._run_thread = True

def test_app_start_function_runs_well(mocker):
    d = app.Demo()
    mocker.patch.object(
        d,
        "counter",
        dummy_counter
    )
    d.start()
    result = d.start()
    assert result is None

So since i do not want the loop to actually i just want to mock the counter function and then just set the flag inside it so that the actual thread does not run.

I am seeing the below error.

(roughwork) ➜  threads git:(master) ✗ pytest
============================================================ test session starts ============================================================
platform linux -- Python 3.7.6, pytest-5.4.3, py-1.8.1, pluggy-0.13.1
rootdir: /home/subhayan/Codes/Test/Python-remote/threads
plugins: mock-3.1.1
collected 1 item                                                                                                                            

test_app.py Exception in thread Thread-2:
Traceback (most recent call last):
  File "/home/subhayan/anaconda3/envs/roughwork/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/home/subhayan/anaconda3/envs/roughwork/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
TypeError: dummy_counter() missing 1 required positional argument: 'value'

F                                                                                                                         [100%]

================================================================= FAILURES ==================================================================
____________________________________________________________ test_app_runs_well _____________________________________________________________

mocker = <pytest_mock.plugin.MockFixture object at 0x7f922c05ee90>

    def test_app_runs_well(mocker):
        d = app.Demo()
        mocker.patch.object(
            d,
            "counter",
            dummy_counter
        )
        d.start()
        result = d.start()
>       assert result is None
E    assert 20 is None

test_app.py:15: AssertionError
----------------------------------------------------------- Captured stdout call ------------------------------------------------------------
Thread has not run
Thread has not run
----------------------------------------------------------- Captured stderr call ------------------------------------------------------------
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/home/subhayan/anaconda3/envs/roughwork/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/home/subhayan/anaconda3/envs/roughwork/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
TypeError: dummy_counter() missing 1 required positional argument: 'value'

========================================================== short test summary info ==========================================================
FAILED test_app.py::test_app_runs_well - assert 20 is None

I have no clue where i am going wrong. Any clue and i would be really grateful.

You did almost everything right. The only problem is that self.counter is a bound method to the instance, so self is filled with your right instance of d . However, dummy_counter is not bound - so it doesn't get the first parameter automatically, so you need to provide it.

One way of doing it is using partial functions like so:

from functools import partial

import app


def dummy_counter(self, value):
    self._run_thread = True


def test_app_start_function_runs_well(mocker):
    d = app.Demo()
    dummy_for_d = partial(dummy_counter, d)  # fills the first parameter with 'd'

    mocker.patch.object(
        d,
        "counter",
        dummy_for_d
    )
    d.start()
    result = d.start()
    assert result is None

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