在 Python 中模拟套接字连接

mocking a socket connection in Python(在 Python 中模拟套接字连接)
本文介绍了在 Python 中模拟套接字连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试为 python 中的一个类编写单元测试.该类在 init 上打开一个 tcp 套接字.我试图对此进行模拟,以便我可以断言使用正确的值调用连接,但显然在单元测试中实际上并没有发生.我已经厌倦了 MagicMock、补丁等,但我还没有找到解决方案.

I am trying to write unit tests for a class in python. The class opens a tcp socket on init. I am trying to mock this out so that I can assert that connecting is called with the correct values but obviously doesn't actually happen in unit tests. I have tired MagicMock, patch, etc but I have not found a solution.

到目前为止,我的班级看起来像这样

My class so far looks like this

import socket

class MyClass(object):

    def __init__(self):
        self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcp_socket.connect('0.0.0.0', '6767')

推荐答案

如果只想断言 connect 被正确调用,那么简单的 as

If you just want to assert that connect is called correctly, it's a simple as

import mock
import socket

class MyClass(object):

    def __init__(self):
        self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcp_socket.connect('0.0.0.0', '6767')

with mock.patch('socket.socket'):
    c = MyClass()
    c.tcp_socket.connect.assert_called_with('0.0.0.0', '6767')

如果您必须先导入模块才能访问 MyClass,则需要稍微调整补丁:

If you have to import a module first to access MyClass, you'll need to adjust the patch slightly:

from mymodule import MyClass
import mock

with mock.patch('mymodule.socket.socket'):
    c = MyClass()
    c.tcp_socket.connect.assert_called_with('0.0.0.0', '6767')

这篇关于在 Python 中模拟套接字连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)