6

I want to test my views using data from postgres localhost database (with already loaded data). I'm using tox with pytest and pytest-django.

My question: How to set up / connect to local database to get all the data model schema and data itself? Or maybe it is better to use factory_boy? Or to load whole data from .sql script (if yes, how)?

Example of my test:

def test_foo_view(custom_client_login):
    response = custom_client_login.get('/foo/bar/123/')

    assert response.status_code == 200
    assert 'Transaction no. 123' in response.content

But instead of getting status code 200 I get 404, which points that no data is in test database. But when I lunch runserver and go to that view ('localhost:8000/foo/bar/123/') I will get status 200 and html webpage with some data.

Please help!


I'm using:

  • Django==1.7.11
  • pytest==3.0.6
  • pytest-django==3.1.2
  • tox==2.6.0
  • Use the test runner setup (def setUp) and create a site to use within your view test – Jingo Mar 02 '17 at 15:17
  • @Jingo could you please elaborate a little bit more about your answer? isn't `def setUp` using with unittest? – MichalTHEDUDE Mar 02 '17 at 15:21
  • https://docs.djangoproject.com/en/1.10/topics/testing/overview/ have a look at that – Jingo Mar 02 '17 at 15:22
  • @Jingo I see. But I wanted to avoid creating objects (and creating whole database structure) and just use my local db. Any thoughts? – MichalTHEDUDE Mar 02 '17 at 15:23
  • 1
    maybe you are looking for fixtures then... http://django-testing-docs.readthedocs.io/en/latest/fixtures.html – Jingo Mar 02 '17 at 17:31
  • Possible duplicate of [Django test to use existing database](http://stackoverflow.com/questions/6250353/django-test-to-use-existing-database) – trinchet Mar 02 '17 at 17:40
  • @trinchet Thanks for pointing that out. Your link gave another two answers [How to run django unit-tests on production database?](http://stackoverflow.com/questions/1646468/how-to-run-django-unit-tests-on-production-database) and [How can I specify a database for Django Tests to use instead of having it build it everytime?](http://stackoverflow.com/questions/4606756/how-can-i-specify-a-database-for-django-tests-to-use-instead-of-having-it-build). I thinkt that i would need to mix those answers and find a way to implement it using pytest with tox. – MichalTHEDUDE Mar 02 '17 at 22:44

1 Answers1

4

Just found a way! It was simpler then I thought! Without writing any custom TestRunners etc.

The answer is in pytest-django docs in Chapter 5 -> Examples -> Use a read only database.

Check out other examples, which are really handy in such situations.

Thanks!