I'm trying to assert the mock's methods are called once and expect it to pass. But somehow, the call count of mock_create_pool
, mock_insert
, and mock_close
is 0 and not 1 or more. How can I test that the functions run at least one time?
Directory Structure
- src
- logic
- main.py
- tests
- unit_test_main.py
- util
- db_connections.py
- logic
db_connections.py
class DbConnections:
. . .
def create_pool(self, pool_name="mypool", pool_size=5):
. . .
def close(self):
. . .
class dailyspecial(DbConnections):
. . .
def dbinsert(self, create_date, data_date, country, confirm_case, confrim_death, test=""):
. . .
logic/main.py
import util.db_connections as daily
def get_wm():
. . .
db = daily.dailyspecial()
db.create_pool(pool_name="wm_pool", pool_size=5)
try:
. . .
for record in res_table:
. . .
db.dbinsert(. . .)
except Exception as e:
print(e)
db.close()
tests/unit_test_main.py
import logic.main as main
class TestWorldMeter(unittest.TestCase):
@mock.patch("util.db_connections.dailyspecial.close")
@mock.patch("util.db_connections.dailyspecial.dbinsert")
@mock.patch("util.db_connections.dailyspecial.create_pool")
@mock.patch("util.db_connections.dailyspecial")
def test_get_wm(self, mock_dailyspecial, mock_create_pool, mock_insert, mock_close):
main.get_wm()
self.assertEqual(mock_dailyspecial.call_count, 1) # pass
self.assertEqual(mock_create_pool.call_count, 1) # fail, expect pass
self.assertTrue(mock_insert.call_count > 0) # fail, expect pass
self.assertEqual(mock_close.call_count, 1) # fail, expect pass
Alternatively, I've tried testing the methods by mocking the util.db_connections.dailyspecial
class only. And it still fails the assertions. Any idea on what went wrong in my mocking process?
Alternative tests/unit_test_main.py
class TestWorldMeter(unittest.TestCase):
@mock.patch("util.db_connections.dailyspecial")
def test_get_wm(self, mock_dailyspecial):
# mock_dailyspecial().return_value = mock.MagicMock()
mock_dailyspecial.return_value = mock.MagicMock()
main.get_wm()
self.assertEqual(mock_dailyspecial.call_count, 1) # pass
self.assertEqual(mock_dailyspecial.create_pool.call_count, 1) # fail, expect pass
self.assertTrue(mock_dailyspecial.dbinsert.call_count > 0) # fail, expect pass
self.assertEqual(mock_dailyspecial.close.call_count, 1) # fail, expect pass
CodePudding user response:
It's missing the ()
when trying to count the number of times, the mock's methods are called. It should be like this instead:
self.assertEqual(mock_dailyspecial.call_count, 1)
self.assertEqual(mock_dailyspecial().create_pool.call_count, 1)
self.assertTrue(mock_dailyspecial().dbinsert.call_count > 0)
self.assertEqual(mock_dailyspecial().close.call_count, 1)