Skip to content
Tong Lam edited this page Mar 25, 2024 · 4 revisions

Overall

Basically, there are two popular test frameworks in python eco systems, and we will use python unittest as the unit required.

Get Started

  1. Install flask-unittest from the requirements.txt.
pip install -r requirements.txt
  1. run the test.py in a terminal.
python test.py

Write a new Test

All unit tests are located in the test.py file. Additional testing data can be added to test_data.py if necessary.

Test Base Case

The unit test framework is based on flask_unittest, which can be used for both Python unit tests and Flask client tests.

Let's examine the TestBase class, which extends flask_unittest.ClientTestCase.

class TestBase(flask_unittest.ClientTestCase):
    """This class contains the test cases for the base module."""

    app = create_app()

    def setUp(self, client: FlaskClient) -> None:
        """Set up the test case."""
        self.appctx = self.app.app_context()
        self.appctx.push()
        self.test_user = self.create_mock_user(mock_user_data)
        client.post(
            "/login",
            data={
                "email": self.test_user.email,
                "password": mock_user_data["password"],
            },
        )

    def tearDown(self, client: FlaskClient) -> None:
        """Tear down the test case."""
        db.session.remove()
        self.appctx.pop()
        client.get("/logout")

The setUp(self, client) method acts like a before_test hook in other test frameworks. You can include code here that you want to execute before all of your test cases.

Similarly, the tearDown(self, client) method acts like an after_test hook in other test frameworks. You can include code here that you want to execute after all of your test cases have run.

Testing Modules

Let's use the auth module as an example to understand how to write unit tests.

  1. Create a new class for the module that inherits from the TestBase class.
  2. Write unit test methods that start with test_ and always include assert statements to verify if the actual returns of the testing code match the expected returns.
class TestAuth(TestBase):
    """This class contains the test cases for the authentication module."""

    def test_register(self, client):
        """Test the registration of a new client."""

        # test the registration page, smoke test
        print("test register page")
        self.assertEqual(
            client.get("/register").status_code, 200, msg="Register page did not load"
        )

    def test_login(self, client):
        """Test the login of a user."""

        # test the login page, smoke test
        print("test login page")
        self.assertEqual(
            client.get("/login").status_code, 200, msg="Login page did not load"
        )

    def test_logout(self, client):
        """Test the logout of a user."""
        # some code here...

    def test_forgot_password(self, client):
        """Test the forgot password of a user."""
        # some code here...

Run the Test

There are two ways to run the unit tests.

Run with Command Line

open a terminal and use:

python test.py
image

Run with VsCode Testing

Open the Testing view from the sidebar of your VSCode. Follow its instructions to configure the testing file. Then, you can run the test cases by clicking on the method name in the Testing Tab.

image image image image

Final Word

Remember: Every time you change your code, ensure to update the test code accordingly and run the tests to verify the changes.

Clone this wiki locally