I am writing a unit test for a function in my python flask and the function contains a @login_required. I am only trying to check whether the function is being called properly and gives out the same status code of 200 or not. Here is my function which resides in app.py
@app.route('/settings', methods=['GET', 'POST'])
@login_required
def settings():
global application_inst
if request.method == 'POST':
print("Setting changed")
return render_template('settings.html', user=session['user'], application=application_inst)
and this is how I have written my test case in a testcase file test_app.py which is present in my tests folder.
def setUp(self):
self.app = create_app(db)
self.app.config['TESTING'] = True
self.app.config['LOGIN_DISABLED'] = True
self.client = self.app.test_client(self)
with self.app.app_context():
# create all tables
db.create_all()
def tearDown(self):
pass
def test_settings_passed(self):
with self.app.app_context():
response = self.client.get('/settings', follow_redirects=True)
self.assertEqual(response.status_code, 200)
The error that is being displayed is an AssertionError which says that 200!=404. please see the stacktrace
st_app_new.py::MyTestCase::test_settings FAILED [100%]ENV :default
############ INIT ############
############ INIT ############
############ INIT ############
200 != 404
Expected :404
Actual :200
<Click to see difference>
self = <test_app_new.MyTestCase testMethod=test_settings>, first = 404
second = 200, msg = None
def _patched_equals(self, first, second, msg=None):
try:
> old(self, first, second, msg)
/snap/pycharm-community/214/plugins/python-ce/helpers/pycharm/teamcity/diff_tools.py:32:
Assertion failed
I have tried to test the function by testing the testing the request from the logged in user. This is how I did it.
def test_settings(self):
with self.app.test_client() as c:
with c.session_transaction() as sess:
sess['user_id'] = 'leadgenuser'
sess['fresh'] = True
response = c.get('/settings')
self.assertEqual(response.status_code, 200)
and even this failed and returned the same error. What I wanted from this test case was that upon asserting the response equal to 200 the testcase should pass,but at present it is failing. I have even tried to comment out the @login_required from the function but that gave the same error. Please help me understand where I am making a mistake.