Testresources: Unittest Extension for Resource Management

2.0.2 · active · verified Thu Apr 16

Testresources extends Python's `unittest` module with a clean and simple API to optimize tests by managing expensive, common resources. This includes scenarios like setting up sample working directories for version control systems, establishing reference databases, or spinning up web servers. The library is currently at version 2.0.2, with its latest release in April 2025, indicating active maintenance.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a shared resource (a simulated database connection) using `TestResource`, declare its usage within a `ResourcedTestCase`, and then execute tests efficiently with `OptimisingTestSuite` to minimize setup and teardown overhead.

import unittest
from testresources import TestResource, ResourcedTestCase, OptimisingTestSuite

# 1. Define your expensive resource and how to set it up/tear it down
class DatabaseResource(TestResource):
    def make(self):
        print("\n--- Creating database connection ---")
        # Simulate a database connection object
        self.connection = {'host': 'localhost', 'port': 5432, 'db': 'test'}
        return self.connection

    def clean(self, connection):
        print("--- Closing database connection ---")
        self.connection = None

    # Optional: Implement isDirty if the resource can become dirty and needs resetting
    # def isDirty(self, connection):
    #     return False # Assume it's always clean for this example

# Create a singleton instance of the resource manager
db_resource_manager = DatabaseResource()

# 2. Define your test case, inheriting from ResourcedTestCase
class MyDatabaseTest(ResourcedTestCase):
    # Declare the resources needed by tests in this class
    # The resource will be assigned to self.db_conn
    resources = [('db_conn', db_resource_manager)]

    def test_query_data(self):
        print(f"Test 1: Querying data with {self.db_conn}")
        self.assertIn('host', self.db_conn)

    def test_insert_data(self):
        print(f"Test 2: Inserting data with {self.db_conn}")
        # Simulate modifying the resource, then mark it dirty if necessary
        # db_resource_manager.dirtied(self.db_conn) # Uncomment if isDirty is implemented
        self.assertEqual(self.db_conn['db'], 'test')

    def test_another_query(self):
        print(f"Test 3: Another query with {self.db_conn}")
        self.assertTrue(self.db_conn['port'] == 5432)

# 3. Use OptimisingTestSuite to run your tests efficiently
if __name__ == '__main__':
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(MyDatabaseTest))

    # Wrap the suite in OptimisingTestSuite
    optimised_suite = OptimisingTestSuite(suite)

    # Run the tests
    runner = unittest.TextTestRunner(verbosity=2)
    runner.run(optimised_suite)

view raw JSON →