eukaryote / pytest-tornasync

A pytest plugin for testing Tornado (version 5.0 or newer) apps using plain (undecoratored) native coroutine tests.
MIT License
25 stars 4 forks source link

Testing a tornado app which does a redirect #11

Open pelson opened 3 years ago

pelson commented 3 years ago

I wanted to test that a redirect was setup correctly, so I went for something like:

import pytest
import tornado.web

class RedirecterHandler(tornado.web.RequestHandler):
    async def get(self):
        self.redirect('/')

class MainHandler(tornado.web.RequestHandler):
    async def get(self):
        self.finish('Welcome!')

@pytest.fixture
def app():
    return tornado.web.Application([
        (r"/", MainHandler),
        (r"/redirect_me", RedirecterHandler),
    ])

async def test_http_server_client(http_server_client):
    resp = await http_server_client.fetch('/redirect_me')
    assert resp.code == 302

But unfortunately the fetch call never returns. I suspect there is a deadlock somewhere.

For what it is worth, my workaround is to do something like:

    resp = await http_server_client.fetch('/redirect_me', max_redirects=0, raise_error=False)
    assert resp.code == 302
    assert resp.headers['Location'] == "/"
Joshix-1 commented 2 years ago

Can confirm, the following doesn't work:

async def test_http_server_client_fetch(http_server_client):
    resp = await http_server_client.fetch("/")
    assert resp.code == 200
    assert resp.body.decode("utf8") == MESSAGE

    resp = await http_server_client.fetch("/redirect")
    assert resp.effective_url == http_server_client.get_url("/")
    assert resp.code == 200
    assert resp.body.decode("utf8") == MESSAGE

But, the following works:

async def test_http_client_fetch(http_client, http_server, http_server_port):
    url = "http://localhost:%s/" % http_server_port[1]
    resp = await http_client.fetch(url)
    assert resp.code == 200
    assert resp.body.decode("utf8") == MESSAGE

    url = "http://localhost:%s/redirect" % http_server_port[1]
    resp = await http_client.fetch(url)
    assert resp.effective_url == "http://localhost:%s/" % http_server_port[1]
    assert resp.code == 200
    assert resp.body.decode("utf8") == MESSAGE