Click here to Skip to main content
15,943,335 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am new to Python and Flask, and have inherited some Python Flask code, and my task is to write tests for it - bad process I know but we are where we are :/

I have read lots of similar problems to mine but still none of them work in my situation.

The method I am trying to test is:

@ICEAPP.route('/login', methods=['GET', 'POST'])
def login():
    session['ContactList'] = []
    form = LoginForm()
    if request.method == 'POST':
        if request.form['username'] is not None:

When I call this method from my test, an exception is thrown on the last line:
if request.form['username'] is not None
does not exist. I don't know how to fix this as none of the examples I have found about passing form data into a request are the same situation as this.

My test is:

class TestLogin(unittest.TestCase):
    def test_login(self):
       flask_app = create_app()
       flask_app.config['WTF_CSRF_ENABLED'] = False
       data = dict(username="admin")
       with flask_app.test_client() as c:
           with c.session_transaction() as session:
               session["username"] ='admin'
      response ='/login', data, follow_redirects=True, 

Thank you in advance for any help!

What I have tried:

I have tried settin form["username" in the test method
I have also tried seeting up the EnvironBuilder with a
parameter, but I don't know how to pass this in the request.
Updated 27-Jun-22 8:50am

1 solution

Share this answer
Jackie Lloyd 23-Jun-22 15:23pm    
Thank you, I had read that but have obviously missed something as I tried to use it to solve my problem but didn't succeed - I'll try again!
Jackie Lloyd 27-Jun-22 14:52pm    
I finally got this to work, the command I needed is:

response ='/login', data=dict(username="admin"), follow_redirects=True)

which is virtually the same as before except I set the 'data' parameter then passed it in as an arg rather than passing in 'data=...' but I guess the devil is in the detail!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900