'AttributeError: 'function' object has no attribute 'get' when testing Flask requests

Good afternoon, I am developing some unit tests for my Flask application. It is my first time trying to develop unit tests for a Flask app, but I am currently getting this error when trying to test GET requests.

    def testTagCategories():
>       response = client.get("/forum")
E       AttributeError: 'function' object has no attribute 'get'

I have been struggling to find what the problem is, as I have followed all the steps required in the Flask documentation. Here is the code.

    @pytest.fixture(scope='session')
def test_client():
    flask_app = app()
    testing_client = flask_app.test_client()
    ctx = flask_app.app_context()
    ctx.push()
    yield testing_client
    ctx.pop()

@pytest.fixture()
def client(app):
    return app.test_client()

@pytest.fixture()
def runner(app):
    return app.test_cli_runner()

Finally, this is one of the functions where I get the error. Thanks in advance.

def test_access():
    response = client.get("/")
    assert (response.status_code == 200)


Solution 1:[1]

I'm also learning to unit test a flask controller so take my answer with a pinch of salt.

But in the failing code (like below) there appears to be no client instance and thus you cannot call the get method.

def test_access():
    response = client.get("/")
    assert (response.status_code == 200)

I'm sure there is a nicer way of doing it by having the client created before every test fixture (that's how I would do it in another language I'm more familiar with like C# with setup / teardown before each test).

But something like this works for me:

from app import application

def test_access():
    client = application.test_client()
    response = client.get('/')
    assert response.status_code == 200
    html = response.data.decode()
    assert 'xxx' in html

in my app directory there is an __init__.py with application = Flask(__name__) in it. That's what from app import application is importing.

Would love to hear a better solution from someone though.

Edit: On the function that is causing an error, trying changing the signature to the following:

def test_access(client):

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1