'How to avoid database connection, while debugging
I am wondering what the most pythonic way is to avoid making connections to databases while being in debugging/development. Since I moved my project away from the server (where the db is settled) to my local machine, this option would become quite comfortable.
I guess I could use the mock module for that in a very uncommon approach since it is not a test case...
those are the lines which are of my interest to be
with apputils.create_cx_oracle_connection() as connection:
with connection.cursor() as cursor:
apputils.create_cx_oracle_connection() returns an cx_Oracle connection.
I can not work around those lines since they are being used in a important decorator which wraps the function which are doing the important business logic in a later process.
This line is easy for me to been altered if the cli flag --no-db is set, since I can change the return object of my module.
with apputils.create_cx_oracle_connection() as connection:
But it will throw an error at this point since this method will not be available...
with connection.cursor() as cursor:
At this point I could either use an faked object with a cursor method, which will be returned from create_cx_oracle_connection, when --no-db was used as cli option or do some error handling, but maybe there is something more pythonic for that I am not aware of
Solution 1:[1]
You can mock out the call to connect with your own object. Adding __enter__ and __exit__ methods to the object will allow it to work as a context manager. This would then need a cursor method which returns a cursor object where you can define the methods that you would like to test.
class MockCursor:
# Add the cursor methods you want to test
class MockConnect:
def __enter__(self, *args, **kwargs):
return self
def __exit__(self, type, value, traceback):
pass
@staticmethod
def cursor():
return MockCursor()
@mock.patch.object(apputils, "create_cx_oracle_connection")
def test_foo(mock_connect):
mock_connect.return_value = MockConnect()
I have added a more complete example on this question
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
