SarahJessica
SarahJessica

Reputation: 524

Pytest Flask Application AttributeError: module 'src.api' has no attribute 'test_client'

I am trying a basic Pytest test for a "hello world" flask application Please see below what I have in the src file

api.py:

from flask import Flask, jsonify


api = Flask(__name__)


@api.route('/')
def hello_world():
    return jsonify(message="hello world")


if __name__ == '__main__':
    api.run(debug=True)

and this is what I have written for the test

test_api.py

import pytest
from src import api


api.testing = True
client = api.test_client()


def test_route(client):
    response = api.get('/')
    assert response.status_code == 200

Structure

my_project
    __init__.py
    src
        __init__.py
        api.py
    test
        __init__.py
        test_api.py

I run the tests from the root with python -m pytest The error message I get is

test/test_api.py:13: in <module>
    with api.test_client() as client:
E   AttributeError: module 'src.api' has no attribute 'test_client'

I am really unsure of how to make this work.

Upvotes: 5

Views: 995

Answers (1)

dedoussis
dedoussis

Reputation: 440

from src import api imports the module of src/api.py

However, you are interested in the global api object that is within the scope of that src.api module

from src.api import api will import the flask application object which should have the test_client method that you are calling.

Upvotes: 7

Related Questions