2013-08-06 82 views
3

我在Anaconda環境下使用Python 3.3。如何在Python中模擬sqlite3.connect

我想模擬sqlite3.connect。例如在MyTests(見下文)中,我想要test_sqlite3_connect返回字符串'connection'而不是實際的sqlite3.Connection對象。

我已經試過修補它,但那不起作用。

from unittest.mock import patch 
import unittest 

import sqlite3 

@patch('sqlite3.connect') 
def sqlite3_connect(self,connection_string): 
    print('connect with : {0}'.format(connection_string)) 
    return 'connection ' 

class MyTests(unittest.TestCase): 

    def test_sqlite3_connect(self): 

     print('testing connection') 

     dbc = DataBaseClass() 


class DataBaseClass(): 

    def __init__(self): 
     print('initialising database class') 
     self.connection = sqlite3.connect('test database') 

回答

4

我設法解決從

http://www.voidspace.org.uk/python/mock/

下面的代碼顯示嘲諷sqlite3.connect兩種方式快速指南部分的問題用的信息。

''' An example of how to mock the sqlite3.connection method ''' 

from unittest.mock import MagicMock,Mock 
import unittest 
import sqlite3 

class MyTests(unittest.TestCase): 

    def test_sqlite3_connect_success(self): 

     sqlite3.connect = MagicMock(return_value='connection succeeded') 

     dbc = DataBaseClass() 
     sqlite3.connect.assert_called_with('test_database') 
     self.assertEqual(dbc.connection,'connection succeeded') 


    def test_sqlite3_connect_fail(self): 

     sqlite3.connect = MagicMock(return_value='connection failed') 

     dbc = DataBaseClass() 
     sqlite3.connect.assert_called_with('test_database') 
     self.assertEqual(dbc.connection, 'connection failed') 

    def test_sqlite3_connect_with_sideaffect(self): 

     self._setup_mock_sqlite3_connect() 

     dbc = DataBaseClass('good_connection_string') 
     self.assertTrue(dbc.connection) 
     sqlite3.connect.assert_called_with('good_connection_string') 

     dbc = DataBaseClass('bad_connection_string') 
     self.assertFalse(dbc.connection) 
     sqlite3.connect.assert_called_with('bad_connection_string') 

    def _setup_mock_sqlite3_connect(self): 

     values = {'good_connection_string':True, 
        'bad_connection_string':False} 

     def side_effect(arg): 
      return values[arg] 

     sqlite3.connect = Mock(side_effect=side_effect) 


class DataBaseClass(): 

    def __init__(self,connection_string='test_database'):   
     self.connection = sqlite3.connect(connection_string)