Thursday, September 7, 2023

Re: pytest, asgiref, Selenium and database access? How to make them work?

install pytest-django
use fixture @pytest.mark.db

On 5 September 2023 at 08:15:10, Alfons Eberle ( wrote:

Hey, has anyone gotten pytest to work with django-channels (or asgiref + Daphne) and Selenium in general when database access is required?

My fixtures for users and other models import just fine, but my browser and Daphne process seem to be unaware of the test database and seem unable to create them. Frontend errors out with the classic pytest django.db.utils.OperationalError: connection to server at "", port 5432 failed: FATAL: database "test2" does not exist

I am using a Daphne test server implementation I found on SO + GitHub here:

Here's some sample code I have for reference. channels_live_server is from the implementation above. Doing this simply shows the yellow Django error page with the error above.
I have tried explicitly creating the database, which gets rid of the error, trying to e.g. log in via the admin but it still does not cause the database to fill with any data. It's like they are in two different worlds (threads).

All my other pytests run fine.

Any ideas? Thanks

def authenticated_browser_staff(channels_live_server, client):
    """Return a browser instance with logged-in user session."""
    options = webdriver.ChromeOptions()
    browser_ = webdriver.Chrome(options=options)
    user_staff = User.objects.create(
    ) # usually a fixture, but easier to share like this
    print('staff id',  # works as expected

    client.force_login(user_staff)  # works and returns the session ID
    print('cookie', client.cookies[settings.SESSION_COOKIE_NAME].value)

    browser.get(channels_live_server.url + "/admin/")
        'name': settings.SESSION_COOKIE_NAME,
        'value': client.cookies[settings.SESSION_COOKIE_NAME].value,
        #'expires': None,
        #'secure': False,
        #'path': '/'
    # server responds with setting sessionid to empty

    # trying to log in, since passing the cookie does not 
    # work, but errors out with user does not exist
    browser.find_element('name', 'username').send_keys(
    browser.find_element('name', 'password').send_keys('hunter42')
    browser.find_element(By.CSS_SELECTOR, "input[type='submit']").click()

    assert any(c for c in browser.get_cookies() if c['name'] == settings.SESSION_COOKIE_NAME)
    return browser

You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To view this discussion on the web visit

No comments:

Post a Comment