本文介绍了概念:模拟DB python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用postgresql,并且已经使用MagicMock进行了测试,但是我不确定我是否了解该模拟的概念.这是我的示例代码(我有dbname = test,table = py_test和user = simone):

I'm working with postgresql and I have used MagicMock to test, but I'm not sure that I have understanded the mock's concepts. This is my example code (I have a dbname=test, table=py_test and 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

推荐答案

也许我会给你一些使用Mockito软件包进行模拟的例子:

Maybe I'll give You some other example of mocking using Mockito package:

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模块)并记录一些行为.

Main concept is to replace some module (mock) that is tested some where else (it has it's own unittest module) and record some behavior.

替换您与模拟一起使用的模块:

Replace module You use with mock:

self.sphinx_client = mock()

然后在此模拟程序上记录,如果您调用特定方法,则该方法将返回一些数据-如果需要检查行为,则将返回简单值,例如字符串或模拟数据:

and then record on this mock that if You call specific method, this method will return some data - simple values like strings or mocked data if You need to check behavior:

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

在这种情况下,您告诉我们如果导入 sphinxsearch 模块并在其上调用 SphinxClient(),则会得到模拟对象.

In this case You tell that if You import sphinxsearch module and call SphinxClient() on it, You get mocked object.

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

Then the main test comes in. You call method or object to test (SearchManager here). It's body is tested with some given values:

self.search_manager = SearchManager()

何时部分验证是否执行了某些操作:

When section verifies if some actions where made:

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 .如上所述,另外两行是不言自明的.

Here - if SetServer was called on self.sphinx_client with parameters '127.0.0.1' and 9312. Two other lines are self explanatory like above.

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

And here we do normal checks:

self.assertEqual(result, expected_result)

这篇关于概念:模拟DB python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 22:31