Testing a Python Flask Post method which accesses form data

Viewed 64

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 because 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:

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!

0 Answers
Related