Search code examples
pythonflaskflask-testing

Test Login Required Flask Application


i am writing tests for a flask web application and every Test Requires User To Be Logged in is there any Way to Define Test function and use it in other Tests? this is my current TestCase and i want to implement login function just using post to API URL

class TestLogin(unittest.TestCase):
   def setUp(self):
       self.headers = {'Content-type':'application/json','Accept':'tex/plain')
   def test_login(self):
      s=request.Session()
      url = 'http://localhost/api/v1/user/login/'
      data = {'username' = 'admin','password' :'123123'}
      r=s.post(url,data=json.dumps(data),headers=self.headers)
      self.assertEqual(r.status_code,200)

Solution

  • You could create a separate login function. E.g

      def login():
          s = request.Session()
          url = 'http://localhost/api/v1/user/login/'
          data = {'username' = 'admin','password' :'123123'}
          r=s.post(url,data=json.dumps(data),headers=self.headers)
          return (r.status_code == 200)
    

    And then call it from your tests:

     def test_something(self):
          if(login()):
             #Test stuff