SarahJessica
SarahJessica

Reputation: 524

Flask_testing Returns 404 unexpectedly for seemingly working endpoint

Writing some unit tests for my flask application. The endpoint '/' works and returns 200 when I try in postman, however flask_testing gives AssertionError: 404 != 200

I have set up a base config.

class BaseTestCase(TestCase):

    def create_app(self):
        app = Flask(__name__)
        app.config['TESTING'] = True
        app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///:memory:"
        app.config['JWT_SECRET_KEY'] = environ['JWT_SECRET_KEY']
        db = SQLAlchemy(app)
        db.init_app(app)
        return app

This is the test.

class FlaskTestCase(BaseTestCase):

    def test_root(self):
        response = self.client.get('/')
        self.assertEquals(response.status_code, 200)

Output from tests

======================================================================
FAIL: test_root (test.server-test.FlaskTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/my_name/path/to/my_project/test/server-test.py", line 13, in test_root
    self.assertEquals(response.status_code, 200)
AssertionError: 404 != 200

----------------------------------------------------------------------
Ran 1 test in 0.032s

FAILED (failures=1)

Upvotes: 1

Views: 715

Answers (1)

Mahmoud Magdy
Mahmoud Magdy

Reputation: 941

try this flask url_for:

with self.app.app_context():
    from flask import url_for
    url = url_for('app.index')
    print(url)
    response = self.client.get(url)
    self.assertEquals(response.status_code, 200)

in my case I had this if statement in the route I was testing

if len(books_per_request) == 0:
   response = make_response(jsonify(message="value exceeded books count"), 404)

While it successful request I sent 404 error for that reason when test run and count len == 0 it keep return the error if this your first test like me check with normal route that return normal string if every thing ok , check your home route '/'

  1. make sure it exist in your init.py file
  2. and make sure it not return any 404 errors

I hope this help anyone

Upvotes: 1

Related Questions