Refactoring Automated Test Scripts with the Strategy Pattern: Design and Python Implementation

This article explains how to redesign an automated testing framework by applying the Strategy pattern to replace complex conditional branches, thereby improving script reusability, maintainability, and extensibility across diverse business scenarios in Python.

JD Tech
JD Tech
JD Tech
Refactoring Automated Test Scripts with the Strategy Pattern: Design and Python Implementation

In automated testing, the growing number of scripts and evolving business scenarios expose the limitations of hard‑coded conditional logic, leading to low reusability and high maintenance cost. The article proposes a layered refactor using the Strategy design pattern to encapsulate each algorithm as an independent class.

Pain points : frequent changes in upstream processes require script modifications; duplicated if/elif branches become error‑prone and hard to scale.

Design theory : applying high cohesion and low coupling principles, the framework separates concerns by defining an abstract algorithm base, concrete strategy classes, and a context that selects the appropriate strategy at runtime.

Strategy pattern definition : it encapsulates a family of algorithms, hides branching code, and allows interchangeable use without affecting clients, supporting the Open/Closed principle.

Advantages : decoupled code, easier maintenance, avoidance of deep conditional trees, runtime algorithm switching, and extensibility without modifying existing context code.

Disadvantages : added boilerplate when algorithms are stable and the need to understand all concrete strategies.

Solution approach :

1. Extract frequently changed logic into separate algorithm classes.

2. Define an abstract base class with read_params and execute methods.

3. Implement concrete strategies (e.g., CreateTFCEnquiryBill, CreateECLPClodEnquiryBill) that override these methods.

4. Build a context class ( AlgorithmStrategy) that holds a reference to the chosen strategy and delegates execution.

5. Register strategies in a dictionary for dynamic lookup and invoke them from test cases.

Code examples :

【python】

def receive_enquiry_bill(**kwargs):
    params = [{}]
    params[0].update(kwargs)
    if params[0].get("enquirySource") == 8:
        pass
    elif params[0].get("enquiryWay") == 2 and params[0].get("payMode") == 2:
        pass
    elif params[0].get("enquiryWay") == 2 and params[0].get("payMode") == 3:
        pass
    if params[0].get("enquirySource") == 46:
        pass
    if params[0].get("enquirySource") == 20:
        pass
【python】

class AlgorithmStrategy(object):
    def __init__(self, algorithm_name):
        self.algorithm_name = algorithm_name

    @property
    def algorithm(self):
        return self.algorithm_name

    @algorithm.setter
    def algorithm(self, name):
        self.algorithm_name = name

    def execute_algorithm(self, params):
        return self.algorithm_name.execute(params)
【python】

class CreateEnquiryBillBaseAlgorithm(ABC):
    @abstractmethod
    def read_params(self, **kwargs):
        scenario = kwargs.get('scenario', 'base')
        # implementation omitted for brevity

    @abstractmethod
    def execute(self, params):
        return jsf_receive_enquiry_bill(data=json.dumps(params))
【python】

class CreateTFCEnquiryBill(CreateEnquiryBillBaseAlgorithm):
    def read_params(self, **kwargs):
        params = super().read_params(**kwargs)
        params[0].update({
            "businessCode": kwargs.get('businessCode', f"TJ{laputa_util.date_time_str(fmt='%y%m%d')}{laputa_util.get_random_num(8)}"),
            "receiveBeginTime": tms_util.data_time_str(minutes=100),
            "deliveryBeginTime": tms_util.data_time_str(minutes=180)
        })
        return params

    def execute(self, params):
        return super().execute(params)

The refactored design enables test engineers to add new business algorithms simply by creating a new strategy class and registering it, without touching the existing framework code.

Summary : By adopting the Strategy pattern, the automation platform achieves higher script reusability, clearer architecture, and easier adaptation to future business changes, aligning with best practices of modular design and maintainable code bases.

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.

Design PatternsStrategy PatternPythonBackend Developmenttest automationFramework Refactoring
JD Tech
Written by

JD Tech

Official JD technology sharing platform. All the cutting‑edge JD tech, innovative insights, and open‑source solutions you’re looking for, all in one place.

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.