pytest-dev / pytest-bdd

BDD library for the pytest runner
https://pytest-bdd.readthedocs.io/en/latest/
MIT License
1.31k stars 221 forks source link

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

Open brianmay opened 7 years ago

brianmay commented 7 years ago

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 commented 7 years ago

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 commented 7 years ago

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 commented 7 years ago

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.

bubenkoff commented 7 years ago

PR is more than welcome to elaborate on this :)

alejandrodnm commented 7 years ago

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?