久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

在 Python 中模擬套接字連接

mocking a socket connection in Python(在 Python 中模擬套接字連接)
本文介紹了在 Python 中模擬套接字連接的處理方法,對大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!

問題描述

我正在嘗試為 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)!

【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!

相關(guān)文檔推薦

Python 3 Float Decimal Points/Precision(Python 3 浮點(diǎn)小數(shù)點(diǎn)/精度)
Converting Float to Dollars and Cents(將浮點(diǎn)數(shù)轉(zhuǎn)換為美元和美分)
What are some possible calculations with numpy or scipy that can return a NaN?(numpy 或 scipy 有哪些可能的計(jì)算可以返回 NaN?)
Python float to ratio(Python浮動比率)
How to manage division of huge numbers in Python?(如何在 Python 中管理大量數(shù)字的除法?)
mean from pandas and numpy differ(pandas 和 numpy 的意思不同)
主站蜘蛛池模板: 情侣av | 欧美黑人国产人伦爽爽爽 | 久久大陆| 欧美精品1区 | 黄色中文字幕 | 在线观看精品视频网站 | 亚洲一区二区欧美 | 亚洲成人国产综合 | 国产精品久久久久久久久久久久冷 | 成人免费视频网站在线观看 | 四虎精品在线 | 国产午夜精品一区二区三区四区 | 天天综合国产 | 神马久久久久久久久久 | 一区二区高清不卡 | 日韩欧美精品在线 | 日韩中文字幕免费在线 | 精品一区二区三区在线观看 | 亚洲一二三区在线观看 | 看片91 | 2023亚洲天堂 | 欧美激情视频一区二区三区在线播放 | 成人在线一区二区 | 精品国产一区二区三区av片 | www免费视频 | 黄色在线网站 | 少妇一区二区三区 | 欧美.com | 日韩视频一区二区 | 精品国产99 | www.色午夜.com | 国产日韩精品一区 | av二区三区 | 午夜视频在线免费观看 | 久久久久久免费观看 | 性色的免费视频 | 精品国产91亚洲一区二区三区www | 视频一区 国产精品 | 国产免费av网 | 亚洲视频中文字幕 | 欧美日韩国产不卡 |