0

我正在使用 postgresql 并使用 MagicMock 进行测试,但我不确定我是否理解了 mock 的概念。这是我的示例代码(我有一个 dbname=test、table=py_test 和 user = simone):

    import psycopg2
    import sys
    from mock import Mock, patch
    import unittest
    from mock import MagicMock 
    from collections import Counter
    import doctest


    class db(object):
        def __init__(self,database, user):
            self.con = None
            self.database = database
            self.user = user

        def test_connection(self):
            """Connection DB"""
            try:
                self.con = psycopg2.connect(database=self.database, user=self.user)
                return True
            except psycopg2.DatabaseError, e:
                print 'Error %s' % e    
                return False

        def test_empty_table(self,table):
            """empty table?"""
            try:
                cur = self.con.cursor()
                cur.execute('SELECT * from ' + table )
                ver = cur.fetchone()
                return ver
            except psycopg2.DatabaseError, e:
                print 'Error %s' % e    

        def test_data_type(self, table, column):
            """data type"""
            try:
                cur = self.con.cursor()
                cur.execute("SELECT data_type from information_schema.columns where table_name = '"+ table + "' and column_name= '"+column+"'")
                ver = cur.fetchone()
                return ver
            except psycopg2.DatabaseError, e:
                print 'Error %s' % e    

        def __del__(self):
            if self.con:
                self.con.close()

    class test_db(unittest.TestCase):

        def testing(self):
            tdb = db('test','simone')
            self.assertTrue(tdb.test_connection(), 1)
            self.assertTrue(tdb.test_empty_table('py_test'), 1)
            self.assertTrue(tdb.test_data_type('py_test','id'), int)

    class test_mock(object):
        def __init__(self, db):
            self.db = db
        def execute(self, nomedb, user, table, field):
            self.db(nomedb, user)
            self.db.test_connection()
            self.db.test_empty_table(table)
            self.db.test_data_type(table, field)


    if __name__ == "__main__":
        c = MagicMock()
        d = test_mock(c)
        d.execute('test','simone','py_test','id')
        method_count = Counter([str(method) for method in c.method_calls])
        print c.method_calls
        print method_count
        print c.mock_calls
4

1 回答 1

2

也许我会给你一些使用 Mockito 包进行模拟的其他示例:

import sphinxsearch
import unittest
from mockito import mock, when, unstub, verify

class SearchManagerTest(unittest.TestCase):

    def setUp(self):
        self.sphinx_client = mock()
        when(sphinxsearch).SphinxClient().thenReturn(self.sphinx_client)

    def tearDown(self):
        unstub()

    def test_search_manager(self):
        # given
        value = {'id': 142564}
        expected_result = 'some value returned from SphinxSearch'

        # when
        search_manager = SearchManager()
        result = search_manager.get(value)

        # then
        verify(self.sphinx_client).SetServer('127.0.0.1', 9312)
        verify(self.sphinx_client).SetMatchMode(sphinxsearch.SPH_MATCH_ALL)
        verify(self.sphinx_client).SetRankingMode(sphinxsearch.SPH_RANK_WORDCOUNT)
        self.assertEqual(result, expected_result)

主要概念是替换一些在其他地方测试过的模块(模拟)(它有自己的 unittest 模块)并记录一些行为。

替换您使用模拟的模块:

self.sphinx_client = mock()

然后在这个模拟上记录,如果你调用特定的方法,这个方法将返回一些数据——如果你需要检查行为,简单的值,比如字符串或模拟数据:

when(sphinxsearch).SphinxClient().thenReturn(self.sphinx_client)

在这种情况下,您告诉如果您导入sphinxsearch模块并在其上调用SphinxClient() ,您将获得模拟对象。

然后是主要测试。您调用方法或对象进行测试(此处为 SearchManager)。它的身体用一些给定的值进行了测试:

self.search_manager = SearchManager()

部分验证是否进行了某些操作:

verify(self.sphinx_client).SetServer('127.0.0.1', 9312)
verify(self.sphinx_client).SetMatchMode(sphinxsearch.SPH_MATCH_ALL)
verify(self.sphinx_client).SetRankingMode(sphinxsearch.SPH_RANK_WORDCOUNT)

这里 - 如果在self.sphinx_client上使用参数'127.0.0.1'9312调用SetServer。另外两行像上面一样是不言自明的。

在这里我们进行常规检查:

self.assertEqual(result, expected_result)
于 2012-11-20T12:05:17.613 回答