Nelo
Nelo

Reputation: 155

Flask API unit test returns an empty 200 response

I'm trying to write unit tests for my flask project with no luck. For example, I have the following API endpoint on flask:

@app.route('/1.0/account/login', methods=['POST'])
def login():
    return jsonify({'success':0, 
                  'response_detail': "Could not log in", 
                  'method':'login', 
                  'error_code':1,
                  'error_tag':"invalid_json_request", 
                  'response_message':"Failing test request", 
                  'response_code': 0,
                  'data': "",
                  'data_count': 0}), 400

As you see it should always return a json object with a 400 response error.

I wrote this test:

import unittest
from MY_PROJECT import app, db
 
 
class BasicTests(unittest.TestCase):
 
    ############################
    #### setup and teardown ####
    ############################
 
    # executed prior to each test
    def setUp(self):
        app.config['TESTING'] = True
        #app.config['WTF_CSRF_ENABLED'] = False
        app.config['DEBUG'] = False
        self.app = app.test_client()
        #db.drop_all()
        #db.create_all()
 
        # Disable sending emails during unit testing
        #mail.init_app(app)
        self.assertEqual(app.debug, False)
 
    # executed after each test
    def tearDown(self):
        pass
 
 
###############
#### tests ####
###############
# run with: ENV=test python3 -m unittest fotomarket/tests/test_basic.py

    def test_login(self):
      r = self.app.post('/1.0/account/login', json={"name":"lala"})

      print(r.get_json())
      self.assertEqual(r.status_code, 200)
 
 
if __name__ == "__main__":
    unittest.main()

It runs but it always asserts that the status code of the response is 200 (even though it should be 400, no json data anywhere. I tried passing the content_type='application/json' in the test with no luck. What exacly I'm I doing wrong?

Thanks.

Upvotes: 0

Views: 1334

Answers (1)

Nelo
Nelo

Reputation: 155

Make sure you don't have any @app.before_request or @app.after_request decorators in use as they will affect the result you get. They are comonly used for handling CORS headers.

Upvotes: 1

Related Questions