简体   繁体   English

如何在线程中模拟内置模块

[英]How to mock a builtin module in a Thread

Question is as in the heading, how can I mock select.select by example to test my thread run function.问题与标题一样,如何通过示例模拟 select.select 以测试我的线程运行功能。 the test function fails with测试功能失败

ready = select.select([self.sock], [], [], 5)
TypeError: fileno() returned a non-integer

and the type print gives和类型打印给出

type 'builtin_function_or_method'输入'builtin_function_or_method'

so clearly select.select is NOT mocked in the thread's scope while in the test it is...(assert isinstance)所以很明显 select.select 在线程的范围内没有被模拟,而在测试中它是......(assert isinstance)

import select
import threading

RECEIVE_BYTES = 256


class Bar(threading.Thread):
    def __init__(self, sock):
        threading.Thread.__init__(self)
        self.sock = sock

    def run(self):
        print type(select.select)
        ready = select.select([self.sock],[],[],5)
        if ready[0]:
            print self.sock.recv(RECEIVE_BYTES)

the test is as follows in another module在另一个模块中测试如下

def test_run(self):
    with patch("select.select"):
        select.select.return_value = [True]
        mock_sock = MagicMock()
        foo = Bar(mock_sock)
        assert isinstance(select.select, MagicMock)
        foo.start()

tests are run via nose测试通过鼻子运行

The short answer is to call foo.join() to wait for the thread to finish before leaving the with patch(...) block.简短的回答是在离开with patch(...)块之前调用foo.join()以等待线程完成。 The error was caused by removing the patch before the thread had finished.该错误是由于在线程完成之前删除补丁引起的。

By the way, it's much easier for people to help you if you post an example that can be run.顺便说一句,如果您发布一个可以运行的示例,人们会更容易帮助您。 Your example was incomplete and had syntax errors.您的示例不完整并且存在语法错误。

Here's the fixed up test.这是固定测试。 I added the loop to make it easier to reproduce the error.我添加了循环以更容易重现错误。

import select
from mock import patch, MagicMock
from time import sleep

from scratch import Bar

IS_FIXED = True

def test_run():
    for _ in range(20):
        with patch("select.select"):
            select.select.return_value = [True]
            mock_sock = MagicMock()
            foo = Bar(mock_sock)
            assert isinstance(select.select, MagicMock)
            foo.start()
            if IS_FIXED:
                foo.join()
        sleep(0.1)

And here's the Bar class with some syntax fixes.这是带有一些语法修复的Bar类。

import select
import threading

RECEIVE_BYTES = 256


class Bar(threading.Thread):
    def __init__(self, sock):
        threading.Thread.__init__(self)
        self.sock = sock

    def run(self):
        print type(select.select)
        ready = select.select([self.sock],[],[],5)
        if ready[0]:
            print self.sock.recv(RECEIVE_BYTES)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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