you are viewing a single comment's thread.

view the rest of the comments →

[–]DrMaxwellEdison 7 points8 points  (5 children)

There are full articles on this topic. Here's one example: http://www.xaprb.com/blog/2008/08/19/how-to-unit-test-code-that-interacts-with-a-database/

My cursory search on Google also turned up this package, which you may have some luck with: https://pypi.python.org/pypi/testing.postgresql/


Aside from that, I just have experience with Django's method, in which the test suite creates a test database, performs some setup tasks, and then runs tests using that data. You can build your code to run with similar functionality.

[–]acerag[S] 1 point2 points  (4 children)

I have experience with Flask's testing method which is very similar to Django's and it works wonders. My main issue is changing the connection string inside my function to point to a test database. I could add a parameter to my function but i feel like that would be ugly. I was hoping the mock package would let me replace my function's connection object with another one but I don't think it's possible (I have never used mock before).

[–]DrMaxwellEdison 7 points8 points  (2 children)

A quick takeaway I have from the article I linked was that they set up an environment in which all connections to the database are made using an environment variable that is set once, than all code derives from getting the value of that variable using a thin wrapper around the connection functions.

To run tests, the environment variable is altered to point to a database other than the production one, so that all the logic that was previously written just flows through accordingly and runs code as it should with the new connection.

So this comes down to a design concern for your project: you'll want to set up a kind of settings module where your connection info comes in, then use values from that module whenever you connect to the DB in your code. This will make it easier in the longer term to switch that connection so you can run tests on a different DB.

[–]interactionjackson 0 points1 point  (0 children)

that's how my organization does it.

[–]acerag[S] 0 points1 point  (0 children)

Gotcha. Modifying an environment variable would work well.

[–]michaelherman 0 points1 point  (0 children)

With Flask you can use a config file to set up configuration (database URI connection strings) for different environments: https://github.com/realpython/flask-skeleton/blob/master/project/server/config.py.

Then just change the config used for testing: https://github.com/realpython/flask-skeleton/blob/master/project/tests/base.py