我有一个返回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)
但这不起作用
答案 0 :(得分:0)
在此处尝试此示例,
#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