如何为Python __del__函数编写单元测试用例

时间:2017-05-17 18:30:51

标签: python python-3.x unit-testing mocking

我有以下代码设置,我有一个测试用例来测试Db.__init__,如何测试__del__?你能提供一个例子吗?

import psycopg2


class Db(object):
    def __init__(self):
        import app
        conn_string = "host='{}' port='{}' dbname='{}' user='{}' password='{}'".format(app.app.config['DB_HOST'], \
                      app.app.config['DB_PORT'], app.app.config['DB_NAME'], app.app.config['DB_USER'], \
                      app.app.config['DB_PASSWORD'])
        self.conn = psycopg2.connect(conn_string)

    def __del__(self):
        self.conn.close()

测试用例

@ddt
class TestDB(unittest.TestCase):
    @patch('psycopg2.connect')
    def test_db_constructor(self, mock_psycopg2_connect):
        mock_psycopg2_connect.returned_value = True
        db = Db()

        self.assertTrue(db.conn)

1 个答案:

答案 0 :(得分:1)

直接调用该方法,通过self.conn方法模拟__init__

@patch('psycopg2.connect')
def test_db_destructor(self, mock_psycopg2_connect):
    db = Db()
    mock_conn = mock_psycopg2_connect.return_value
    close = mock_conn.close

    db.__del__()
    close.assert_called_once()

您的原始测试存在缺陷;你拼错了return_value,所以你的模拟连接永远不会返回True;它返回一个新的模拟对象。那个模拟对象只是发生才有真正的值:

>>> from unittest.mock import MagicMock
>>> mock = MagicMock()
>>> mock.connect()
<MagicMock name='mock.connect()' id='4536051752'>
>>> bool(mock.connect())
True

要正确测试connect()方法返回值是否存储在db.conn中,请测试该属性是否与模拟返回的对象完全相同:

@patch('psycopg2.connect')
def test_db_constructor(self, mock_psycopg2_connect):
    mock_conn = mock_psycopg2_connect.return_value

    db = Db()
    self.assertTrue(db.conn is mock_conn)