pytest-bdd icon indicating copy to clipboard operation
pytest-bdd copied to clipboard

How to add the ``django_db`` mark to automatically generated tests?

Open brianmay opened this issue 8 years ago • 5 comments

I keep getting this error from pytest-django:

Failed: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.

However, I don't know how to add the django_db mark to tests automatically created with the scenarios() function. Some sort of documentation on how to do this would be great.

I also suspect this is the underlying reason for #187.

brianmay avatar May 13 '17 08:05 brianmay

The documentation refers to a pytest_bdd_apply_tag hook which would seem appropriate, if I could work out how to override pytest hooks...

brianmay avatar May 13 '17 09:05 brianmay

On second thoughts, no, I don't think that hook looks appropriate. Is called once for every tag added, not for adding a new tag when none exist.

brianmay avatar May 13 '17 09:05 brianmay

Oh, wait, I think I got it. Need to add the following to conftest.py:

def pytest_bdd_apply_tag(tag, function):
    if tag == "django_db":
        marker = pytest.mark.django_db(transaction=True)
        marker(function)
        return True
    else:
        # Fall back to pytest-bdd's default behavior
        return None

Then need to prefix the scenario in the *.feature file with @django_db.

Now that I have worked it out, it seems so obvious, however I had real problems trying to work this out from the documentation.

brianmay avatar May 13 '17 09:05 brianmay

PR is more than welcome to elaborate on this :)

bubenkoff avatar May 13 '17 20:05 bubenkoff

Like #187 I'm trying to use along side live_server of pytest-django. I tried @brianmay method, the thing is that the database access was working, but the data created in the given steps was not visible from the live_server. I think the steps where being isolated in a PostgreSQL transaction.

I manage to use both using in the scenario function the transactional_db fixture explicitly.

@scenario('my.feature', 'My feature')
def test_my_feature(transactional_db):
    pass

Do you guys have any idea as to why?

alejandrodnm avatar Aug 17 '17 13:08 alejandrodnm