I am trying to unit test my Flask application. But when unit testing with unittest it won't let me login.
This is my test script. test_register_page and test_login_page both work, The test_user_registration function works as well. but I know this is not the way to test the register function. I am now just saving it to the database. But when trying to login it will not give me a status_code 201. So that means my unit test for login is not working correct.
import unittest
from damage_detection import create_app, db
from damage_detection.config import config_dict
from damage_detection.models import User
class UserTestCase(unittest.TestCase):
def setUp(self):
self.app=create_app(config=config_dict['testing'])
self.appctx=self.app.app_context()
self.appctx.push()
self.client=self.app.test_client()
db.create_all()
def tearDown(self):
db.drop_all()
self.appctx.pop()
self.app=None
self.client =None
def test_register_page(self):
r = self.client.get("/register")
self.assertEqual(r.status_code, 200)
def test_login_page(self):
r = self.client.get("/login")
self.assertEqual(r.status_code, 200)
def test_user_registration(self):
user = User(username="testuser", email="testuser@company.com", password="password", image_file="default.jpg")
db.session.add(user)
users = User.query.all()
assert user in users
def test_login(self):
data={
"email":"testuser@company.com",
"password":"password"
}
response=self.client.post('/login',data=data)
print(response.status_code)
assert response.status_code == 201
This is my login function:
@users.route("/login", methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('main.home'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and bcrypt.check_password_hash(user.password, form.password.data):
login_user(user, remember=form.remember.data)
next_page = request.args.get('next')
return redirect(next_page) if next_page else redirect(url_for('main.home'))
else:
flash('Login Unsuccessful. Please check email and password', 'danger')
return render_template('login.html', title='Login', form=form)
Do i need to give other data to the login function?
If you need more information about my files please let me know. Everything else is working correct so it is not a fault in my application code:)
it would be easier to debug this knowing which status code are you getting back from the test. As it fails I guess it is different from 201 .
By looking over your code I see some redirects. By Flask documentation flask.redirect()
method defaults the code to 302 . This might be the issue.
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.