Mocking of execute definition in sqlite3 with python.
(1) By krishna chaitanya (kc.maroju) on 2021-01-20 09:03:42 [link] [source]
Hi, To mock the sqlite3.connect(), sqlite3.Connection.execute() and perform CRUD operations. The original functionality of the sqlite3.connect() and the sqlite3.Connection.execute() has to be mocked. I'm able to mock the connect definition but blocked at mocking the execute function. I'm able to mock connect definition by the below line “@mock.patch('sqlite3.connect', side_effect = stub_sqlite3_connect)” The execute function is present inside the Connection class in the _sqlite3.py file which is the sqlite3 package. The following are the different ways which we tried to mock the execute function: 1. “from sqlite3 import Connection @mock.patch.object(Connection,'execute',stub_sqlite3_execute_create)” 2. “import sqlite3 @mock.patch('sqlite3.Connection.execute',side_effect=stub_sqlite3_execute_select)” 3. “import sqlite3 conn = sqlite3.connect('database.db') @mock.patch('conn.execute', side_effect = stub_sqlite3_execute_select)” 4. “import sqlite3 connection_object = sqlite3.Connection() @mock.patch('connection_object.execute', side_effect = stub_sqlite3_execute_select)” For all the above different ways of mocking im facing the below error statement. The error statement is: TypeError: can't set attributes of built-in/extension type 'sqlite3.Connection'; Any ideas/suggestions to achieve mocking of execute definition in sqlite3 with python.
(2) By Keith Medcalf (kmedcalf) on 2021-01-20 10:12:16 in reply to 1 [source]
Not that this is a Python forum but I would suggest that the error message is very explicit.
TypeError: can't set attributes of built-in/extension type 'sqlite3.Connection'
Which would seem to indicate that this mock thing does not work with built-in/extension types -- the Connection class is a built-in type implemented in C -- that in order to function it requires a dynamic type/class object in which it can monkeypatch the attributes.
Depending on the version of Python you can probably create a Python class which inherits from the builtin type and then write delegates back to all the Connection type methods/attributes so that mock has something which it can monkeypatch as every attribute of Connection is also defined statically and to modify it you need to code a specific Python delegate even if the delegate only executes the super procedure (you need to do this so that the attribute of the new class you are creating can be monkeypatched or you will get the same error).