Click here to Skip to main content
15,886,518 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:

Python
@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:
Python
if request.form['username'] is not None
because
Python
form['username']
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:

Python
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 = c.post('/login', data, follow_redirects=True, 
             headers={"Content-Type":"application/x-www-form-urlencoded"})


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
Python
data={'form["username"]':'admin'}
parameter, but I don't know how to pass this in the request.
Posted
Updated 27-Jun-22 8:50am

1 solution

 
Share this answer
 
Comments
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 = c.post('/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