简体   繁体   中英

Test failing in Flask unit test with 404 error

I am running unit test to test an API that works fine when tested with Postman. The API takes in two parameters in the form {"body":"hey","title":"title"} adds these values to the database based on the models I have made. A response is returned in similar format with an extra key of id which is obtained from the database. The thing is that it works fine with Postman. However, when tested using the Pytest, just does not work.

Here is the code in the test file.

import os
import unittest
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
# from flask_backend import app
# from flask_backend.core import db


class BasicTests(unittest.TestCase):
    app = Flask(__name__)
    db = SQLAlchemy(app)

    def setUp(self):
        file_path = os.path.abspath(os.getcwd()) + "\database_test.db"
        self.app.config['TESTING'] = True
        self.app.config['DEBUG'] = False
        self.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + file_path
        self.app = self.app.test_client()
        self.db.drop_all()
        self.db.create_all()

    def tearDown(self):
        self.db.session.remove()


class TestApi(BasicTests):

    def test_add_post(self):
        url = 'http://127.0.0.1:5000'
        parameters = {'body': 'Body', 'title': 'title'}
        response = self.app.post(url+'/api/dbapi/post/', data=parameters)
        print(self.app)
        self.assertEqual(response.status_code, 200)


if __name__ == '__main__':
    unittest.main()

I am thinking that while executing the test a server is not started and hence the 404 error is raised.

The reason I am not importing the app variable from the project itself is because the module is not getting imported. I have asked the question in a different thread. Here is the link to it: Can not import the files from parent directory even though it has __init__.py file in it

From what I understand, if I can import the app instance that is used in the project itself, I should be good but that isn't working either.

Here is how I solved the problem. So, apparently it was required to get the server running for the API to be accessible and the test to run successfully.

So, I added app.run() at the end of the code and it worked fine. Here is what it looks like


    if __name__ == '__main__':
        unittest.main()
        app.run()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM