Fundamentals 9 min read

Master Python’s unittest: From Basics to Real‑World Email Login Tests

This article introduces Python’s built‑in unittest framework, explains its core concepts such as test cases, fixtures, suites and runners, demonstrates common assertion methods, and provides a step‑by‑step Selenium example for testing a webmail login flow.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python’s unittest: From Basics to Real‑World Email Login Tests

What is unittest

unittest is Python’s built‑in unit testing framework, similar to JUnit for Java.

It revolves around four key concepts: test fixture, test case, test suite, and test runner.

Testcase

A TestCase instance represents a single test case, which includes environment setup ( setUp), execution ( run), and teardown ( tearDown). The essence of a unit test is a complete test unit that validates a specific piece of code.

Test suite

A TestSuite groups multiple test cases together and can also contain nested TestSuites.

Test runner

The test runner executes test cases; its run(test) method calls the run(result) method of each TestSuite or TestCase.

TestLoader

TestLoader loads TestCase instances into a TestSuite using methods like loadTestsFrom..., which discover and instantiate test cases before adding them to a suite.

Test fixture

A fixture sets up and tears down the environment for a test case, typically by overriding setUp() and tearDown(). For example, a database connection can be opened in setUp and closed in tearDown. A dedicated library function fixtures offers more advanced capabilities.

How to write unittest code

Create a Python class that inherits from unittest.TestCase.

Define test methods whose names start with test and contain no extra parameters. Use assertion methods such as assertEqual inside these methods.

Call unittest.main() to discover and run all test cases.

Simple usage example

Import the unittest module: import unittest.

Define a test case class inheriting from unittest.TestCase.

Optionally implement setUp and tearDown for per‑test initialization and cleanup.

Write test methods prefixed with test.

Each test should focus on a single aspect and use assertions like assertEqual, assertRaises, etc.

Run the tests with unittest.main().

Test results are displayed as . for pass, F for failure, and E for error.

Common assertion methods

assertEqual(a, b)          # a == b
assertNotEqual(a, b)       # a != b
assertTrue(x)              # bool(x) is True
assertFalse(x)             # bool(x) is False
assertIs(a, b)             # a is b
assertIsNot(a, b)          # a is not b
assertIsNone(x)            # x is None
assertIsNotNone(x)         # x is not None
assertIn(a, b)             # a in b
assertNotIn(a, b)          # a not in b
assertIsInstance(a, b)     # isinstance(a, b)
assertNotIsInstance(a, b)  # not isinstance(a, b)

Example: unittest for a webmail login (Selenium)

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import unittest
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC

class mailLogin(unittest.TestCase):
    def setUp(self):
        url = 'https://mail.yeah.net/'
        self.browser = webdriver.Firefox()
        self.browser.get(url)
        time.sleep(5)

    def test_login_01(self):
        """Username and password are empty"""
        self.browser.switch_to.frame("x-URS-iframe")
        self.browser.find_element_by_name('email').send_keys('')
        self.browser.find_element_by_name('password').send_keys('')
        self.browser.find_element_by_id('dologin').click()
        self.browser.switch_to.default_content()
        time.sleep(3)
        name = self.browser.find_element_by_id('spnUid')
        if name == '[email protected]':
            print('登录成功')
        else:
            print('登陆失败')

    def test_login_02(self):
        """Username correct, password wrong"""
        self.browser.switch_to.frame("x-URS-iframe")
        self.browser.find_element_by_name('email').send_keys('sanzang520')
        self.browser.find_element_by_name('password').send_keys('xxx')
        self.browser.find_element_by_id('dologin').click()
        self.browser.switch_to.default_content()
        time.sleep(3)
        name = self.browser.find_element_by_id('spnUid')
        if name == '[email protected]':
            print('登录成功')
        else:
            print('登陆失败')

    def test_login_03(self):
        """Username and password correct"""
        self.browser.switch_to.frame("x-URS-iframe")
        self.browser.find_element_by_name('email').send_keys('sanzang520')
        self.browser.find_element_by_name('password').send_keys('xxx')
        self.browser.find_element_by_id('dologin').click()
        self.browser.switch_to.default_content()
        time.sleep(3)
        name = self.browser.find_element_by_id('spnUid')
        if name == '[email protected]':
            print('登录成功')
        else:
            print('登陆失败')

    def tearDown(self):
        self.browser.quit()

if __name__ == "__main__":
    unittest.main()

The example demonstrates how to structure test cases, use setUp and tearDown, and apply assertions to verify login outcomes.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythontest automationunit testingTesting frameworkSeleniumunittest
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.