如何使用线程和回调函数测试python?

时间:2019-06-21 10:03:51

标签: python pytest

我想通过pytest测试1功能。

我如何测试调用了回调并且返回值为'Bob'

async_who

因为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) 没有返回值。我做不到,

async_who

1 个答案:

答案 0 :(得分:1)

ThreadPool来自多处理模块或ThreadPoolExecutor(对于python版本> = 3.2) 是获取线程返回值的方法。

使用current.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'

使用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'