Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test python with threading and callback function?

Tags:

python

pytest

I want to test async_who function by pytest.

How do I test callback is called and the return value is 'Bob'

import threading


def async_who(callback):
    t = threading.Thread(target=_who, args=(callback,))
    t.start()


def _who(callback):
    return callback('Bob')


def callback(name):
    print(name)
    return name


async_who(callback)

Because the async_who didn't return value. I can't do this,

def test_async_who():
    res = async_who(callback)
    assert res == 'Bob'
like image 225
foxiris Avatar asked Mar 16 '26 16:03

foxiris


1 Answers

ThreadPool from multiprocessing module or ThreadPoolExecutor (for python version >= 3.2) are ways to get the return value of a thread.

With concurrent.futures.ThreadPoolExecutor

from concurrent.futures import ThreadPoolExecutor

def async_who(callback):
    executor = ThreadPoolExecutor(max_workers=2)
    res = executor.submit(_who, callback)

    return res.result()

def _who(callback):
    return callback('Bob')


def callback(name):
    print(name)
    return name

def test_async_who():
    res = async_who(callback)
    assert res == 'Bob'

With multiprocessing.pool.ThreadPool

from multiprocessing.pool import ThreadPool
pool = ThreadPool(processes=2)


def async_who(callback):
    res = pool.apply_async(_who, args=(callback,))
    return res.get()


def _who(callback):
    return callback('Bob')


def callback(name):
    print(name)
    return name


def test_async_who():
    res = async_who(callback)
    assert res == 'Bob'
like image 165
attdona Avatar answered Mar 18 '26 06:03

attdona



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!