1

I have a function that returns smb.SMBConnection object.

In 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)

I am trying to use mock.patch

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

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

But this doesn’t work

Ciasto piekarz
  • 7,853
  • 18
  • 101
  • 197

1 Answers1

0

Try this example here,

#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
progmatico
  • 4,714
  • 1
  • 16
  • 27
  • So mod1.con.con is fake mock ? – Ciasto piekarz Feb 20 '19 at 14:34
  • @Ciastopiekarz Yes. I changed the example a little bit to make it more clear. Just consider `mod1` is `smb`, and `mod1.conn.conn` is `smb.SMBConnection.SMBConnection` in your case. Yes when the test runs `mod1.conn.conn`, instead of having the value 100 from a normal run it is now a Mock object. That means the patch is working. The test still runs OK with the new second assert. – progmatico Feb 20 '19 at 21:04
  • I did the same but I get assertion error: ` != ` – Ciasto piekarz Feb 21 '19 at 09:58
  • @Ciastopiekarz can you please update your question by adding the code you are currently using and still does not work? – progmatico Feb 21 '19 at 14:03