How can I mock sqlite3.Cursor

后端 未结 3 1229
你的背包
你的背包 2021-02-14 12:06

I\'ve been pulling my hair out trying to figure out how to mock the sqlite3.Cursor class specifically the fetchall method.

Consider the followi

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-14 12:44

    I would take the approach of patching out sqlite3 imported in your module and then work from there.

    Let's assume your module is named what.py.

    I would patch out what.sqlite3 and then mock the return value of .connect().cursor().fetchall.

    Here is a more complete example:

    from mock import patch
    from nose.tools import assert_true, assert_false
    
    from what import Foo
    
    def test_existing_name():
        with patch('what.sqlite3') as mocksql:
            mocksql.connect().cursor().fetchall.return_value = ['John', 'Bob']
            foo = Foo()
            assert_true(foo.check_name('John'))
    

提交回复
热议问题