I am looking to test, with my Flask server, when a post request is sent to my /signup route, and the username is a duplicate, that an integrity error is caught and a redirect occurs, with a flashed message of "Username already exists"
Here is the relevant part of the route, which all works fine, it seems the integrity error is caught because ""our integrity error was caught!" was printed.
My issue is that
if form.validate_on_submit():
try:
user = User.signup(
username=form.username.data,
password=form.password.data,
email=form.email.data,
image_url=form.image_url.data or User.image_url.default.arg,
)
print("passed user is", user)
db.session.commit()
except IntegrityError:
print("our integrity error was caught!")
flash("Username already taken", 'danger')
return render_template('users/signup.html', form=form)
So everything should work fine but I am also receiving the error code
sqlalchemy.exc.PendingRollbackError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "users_username_key"
DETAIL: Key (username)=(followtestuser) already exists
Which would imply that the try is being ran and that db.session.commit() is attempting to execute.
What I am looking to test is that we catch the Integrity error and therefore prevent duplicate usernames from being entered into the DB, So why is it running both the try and except blocks of code at the same time?
The post request is being initialized from our Unittest Python file and it reads as such
class TestUserMethods(TestCase):
"""testing the methods and factory methods of our user instances"""
#Does User.create fail to create a new user if any of the validations (e.g. uniqueness, non-nullable fields) fail?
def test_user_create_method(self):
"""does user.create fail to create a new user if any of the validations fail?"""
with app.test_client() as client:
app.config['WTF_CSRF_ENABLED'] = False
res = client.post("/signup", data={"username":"followtestuser","password":"abcdefg","email":"[email protected]"},
follow_redirects=True)
html = res.get_data(as_text=True)
self.assertIn("Sign me up!", html)
It is important to note that the username "followtestuser" exists already in the db as its a test for duplication.