Home > Software engineering >  Testin a flask enfpoint which renders an HTML using unittest
Testin a flask enfpoint which renders an HTML using unittest

Time:11-09

I have a simple code which returns render_template("home.html") of Flask in the main route. I wonder how can I test it using unittest?

@app.route("/", methods=["GET", "POST"])
def home():
  
    return render_template("home.html")

CodePudding user response:

I personally do the following

import unittest
from whereyourappisdefined import application

class TestFoo(unittest.TestCase):

    # executed prior to each test
    def setUp(self):
        # you can change your application configuration
        application.config['TESTING'] = True

        # you can recover a "test cient" of your defined application
        self.app = application.test_client()

    # then in your test method you can use self.app.[get, post, etc.] to make the request
    def test_home(self):
        url_path = '/'
        response = self.app.get(url_path)
        self.assertEqual(response.status_code, 200)

For more information about testing Flask applications: https://flask.palletsprojects.com/en/2.0.x/testing/

  • Related