問題描述
我正在嘗試為 python 中的一個類編寫單元測試.該類在 init 上打開一個 tcp 套接字.我試圖對此進(jìn)行模擬,以便我可以斷言使用正確的值調(diào)用連接,但顯然在單元測試中實(shí)際上并沒有發(fā)生.我已經(jīng)厭倦了 MagicMock、補(bǔ)丁等,但我還沒有找到解決方案.
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
被正確調(diào)用,那么簡單的 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')
如果您必須先導(dǎo)入模塊才能訪問 MyClass
,則需要稍微調(diào)整補(bǔ)丁:
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')
這篇關(guān)于在 Python 中模擬套接字連接的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!