Back to Repositories

Testing Proxy Pattern Access Control in python-patterns

This test suite validates the Proxy design pattern implementation, focusing on access control and request handling mechanisms. The tests verify proper authentication behavior and logging functionality for both admin and anonymous users.

Test Coverage Overview

The test suite provides comprehensive coverage of the Proxy pattern’s core functionality.

Key areas tested include:
  • Admin user access verification
  • Anonymous user request rejection
  • Request logging behavior
  • Output stream capture and validation

Implementation Analysis

The testing approach uses Python’s unittest framework with systematic setup and teardown procedures. The implementation employs StringIO for output capture and verification, with clear separation between admin and non-admin access paths.

Testing patterns include:
  • Class-level fixture setup
  • Per-test stdout redirection
  • Assertion-based result validation

Technical Details

Testing tools and configuration:
  • Python unittest framework
  • StringIO for output stream manipulation
  • Systematic test case isolation
  • setUp/tearDown mechanisms for resource management
  • sys.stdout redirection for output validation

Best Practices Demonstrated

The test suite exemplifies several testing best practices including proper test isolation, resource cleanup, and clear test case organization. Notable practices include:
  • Separate setup for class and function scopes
  • Proper teardown and resource cleanup
  • Clear test naming conventions
  • Explicit assertion messages

faif/python-patterns

tests/structural/test_proxy.py

            
import sys
import unittest
from io import StringIO

from patterns.structural.proxy import Proxy, client


class ProxyTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        """Class scope setup."""
        cls.proxy = Proxy()

    def setUp(cls):
        """Function/test case scope setup."""
        cls.output = StringIO()
        cls.saved_stdout = sys.stdout
        sys.stdout = cls.output

    def tearDown(cls):
        """Function/test case scope teardown."""
        cls.output.close()
        sys.stdout = cls.saved_stdout

    def test_do_the_job_for_admin_shall_pass(self):
        client(self.proxy, "admin")
        assert self.output.getvalue() == (
            "[log] Doing the job for admin is requested.
"
            "I am doing the job for admin
"
        )

    def test_do_the_job_for_anonymous_shall_reject(self):
        client(self.proxy, "anonymous")
        assert self.output.getvalue() == (
            "[log] Doing the job for anonymous is requested.
"
            "[log] I can do the job just for `admins`.
"
        )