Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Python Automated Testing: Unit, API, Web UI, Performance, and Database Test Cases
Fundamentals 7 min read

Python Automated Testing: Unit, API, Web UI, Performance, and Database Test Cases

This article introduces five common Python automated testing scenarios—unit testing, API testing, web UI testing, performance testing, and database testing—providing clear explanations and complete code examples to help developers improve software quality and stability.

In software development, automated testing is a key technique for improving quality and stability, and Python offers a rich ecosystem of tools and libraries for this purpose.

Unit Testing

Unit testing verifies the smallest testable parts of a program, such as functions or classes. Python's unittest framework makes it easy to write and run these tests.

import unittest

def add(a, b):
    return a + b

class TestMath(unittest.TestCase):
    def test_add(self):
        result = add(2, 3)
        self.assertEqual(result, 5, "Expected 5, but got {}".format(result))
        result = add(-1, 1)
        self.assertEqual(result, 0, "Expected 0, but got {}".format(result))
        result = add(0, 0)
        self.assertEqual(result, 0, "Expected 0, but got {}".format(result))

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

The example defines an add function and a TestMath class that checks several input cases using assertEqual to ensure correct output.

API Testing

API testing validates the functionality and performance of software interfaces. The requests library provides simple HTTP request capabilities for writing API tests.

import requests

def test_api():
    url = 'https://api.example.com/users'
    response = requests.get(url)
    assert response.status_code == 200, "Expected status code 200, but got {}".format(response.status_code)
    assert len(response.json()) > 0, "Expected non‑empty response"

test_api()

This snippet sends a GET request, asserts that the response status is 200, and checks that the returned JSON array is not empty.

Web UI Testing

Web UI testing checks that a web application's user interface works as expected. Python's Selenium library can automate browser interactions.

from selenium import webdriver

def test_web():
    driver = webdriver.Chrome()
    driver.get('https://www.example.com')
    assert 'Example' in driver.title, "Expected 'Example' in title, but got '{}'".format(driver.title)
    driver.close()

test_web()

The code launches Chrome, opens a page, and asserts that the page title contains the word "Example" before closing the browser.

Performance Testing

Performance testing evaluates system response time and throughput under load. The locust library can simulate many concurrent users.

from locust import HttpUser, task, between

class MyUser(HttpUser):
    wait_time = between(1, 3)

    @task
    def test_performance(self):
        self.client.get('/')

if __name__ == '__main__':
    MyUser().run()

This example defines a Locust user that repeatedly sends GET requests to the root path, with a random wait time between requests.

Database Testing

Database testing ensures data consistency and integrity. Using unittest together with a database driver allows writing tests that create, query, and clean up test data.

import unittest
import sqlite3

class TestDatabase(unittest.TestCase):
    def setUp(self):
        self.conn = sqlite3.connect('test.db')
        self.cursor = self.conn.cursor()
        self.cursor.execute('CREATE TABLE users (id INT, name TEXT)')

    def tearDown(self):
        self.cursor.execute('DROP TABLE users')
        self.conn.close()

    def test_insert(self):
        self.cursor.execute('INSERT INTO users VALUES (1, "Alice")')
        self.cursor.execute('SELECT * FROM users')
        result = self.cursor.fetchall()
        self.assertEqual(len(result), 1, "Expected 1 row, but got {}".format(len(result)))

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

The script creates a temporary SQLite table, inserts a row, verifies that exactly one row exists, and then cleans up the table.

Through these examples, we see how Python can be used for a wide range of automated testing tasks, helping developers ensure software quality and reliability.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Report an issue with this article
Pythonautomated testingunit testingAPI testingDatabase TestingWeb UI testing

Reader feedback

Was this useful?

Useful0

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion