如何模拟 SMBConnection class 到 return 模拟连接对象

How to mock SMBConnection class to return mock connection object

我有一个 returns smb.SMBConnection 对象的函数。

my_module.py

from smb.SMBConnection import SMBConnection

def get_connection(user, pwd, server):
    return SMBConnection(user, pwd, socket.gethostname(), server, use_ntlm_v2=True)

我正在尝试使用 mock.patch

@mock.patch(‘smb.SMBConnection.SMBConnection’)

def test_get_connection(self, mock_class):
    self.assertEquals(mock_class, my_module.get_connection)

但这行不通

在这里试试这个例子,

#from mod1.conn import conn
# the import above won't work with patch !

# Make a folder mod1 and a sub-folder conn.
# Create a __init__.py inside both.
# Inside the __init__.py of sub-folder conn
# define conn = 100

import mod1

import unittest
from unittest import mock, main, TestCase
from unittest.mock import Mock

def func():
    return mod1.conn.conn

class MyTests(TestCase):
    @mock.patch('mod1.conn.conn')
    def test1(self, mock1):
        self.assertEqual(func(), mock1)
        self.assertIsInstance(func(), Mock)

print(func())  # prints 100
unittest.main() # runs test OK