Mock map_async函数参数生成PicklingE

2024-04-23 10:41:46 发布

您现在位置:Python中文网/ 问答频道 /正文

试图围绕执行map_async()操作的函数编写一些单元测试。更具体地说,我想确认在某个进程中发生异常时,是否清理了一些文件。具有以下意图的示例伪代码。在

在食品在

def write_chunk(chunk):
    ... create file from chunk
    return created_filename

class Foo:
    def write_parallel(chunks):
        filenames = set()
        try:
            pool = Pool(processes=2)
            pool.map_async(write_chunk, chunks, callback=filenames.add)
        except Exception:
            //handle exception
        finally:
            cleanup_files(filenames)

试验_食品在

^{pr2}$

但是,当我去执行测试时,我得到以下PicklingError:PicklingError: Can't pickle <class 'mock.MagicMock'>: it's not the same object as mock.MagicMock。在

有什么想法来实现用我自己的模拟函数替换映射函数的期望结果吗?在


Tags: 函数食品mapasyncdef单元测试mockchunks
1条回答
网友
1楼 · 发布于 2024-04-23 10:41:46

因此,由于这个问题源于试图模拟和Pickle函数,所以我决定将该功能拉到一个单独的函数中,Mock该函数,同时允许原始函数被Pickle。见下文:

在食品在

def write_chunk(chunk):
    return write_chunk_wrapped(chunk)

def write_chunk_wrapped(chunk)
    ... create file from chunk
    return created_filename

class Foo:
    def write_parallel(chunks):
        filenames = set()
        try:
            pool = Pool(processes=2)
            pool.map_async(write_chunk, chunks, callback=filenames.add)
        except Exception:
            //handle exception
        finally:
            cleanup_files(filenames)

试验_食品在

^{pr2}$

相关问题 更多 >