Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Dynamic Parameter Handling for Multi-API Test Automation in Python

Tech Sep 24 6
import re
import json
import requests
from loguru import logger
from jsonpath import jsonpath

class EnvironmentConfig:
    pass


def substitute_placeholders(template_string):
    if template_string is None:
        return None
        
    processed_string = template_string
    
    while True:
        match = re.search(r"#(.*?)#", processed_string)
        if match is None:
            break
            
        placeholder = match.group()
        variable_name = match.group(1)
        
        try:
            variable_value = getattr(EnvironmentConfig, variable_name)
        except AttributeError as error:
            logger.error(f"Missing environment attribute: {variable_name}")
            raise error
            
        processed_string = processed_string.replace(placeholder, str(variable_value))
        
    return processed_string


def capture_response_data(response_object, extraction_rules):
    if extraction_rules is None:
        logger.info("No data extraction required for this case")
        return
        
    logger.info("Starting response data extraction process")
    rules_dict = json.loads(extraction_rules)
    
    for variable_key, json_path_expr in rules_dict.items():
        extracted_value = jsonpath(response_object.json(), json_path_expr)[0]
        setattr(EnvironmentConfig, variable_key, extracted_value)
        
    logger.info(f"Updated environment attributes: {EnvironmentConfig.__dict__}")


def execute_api_request(case_info, auth_token=None):
    http_method = case_info["method"]
    endpoint_url = case_info["url"]
    request_headers = case_info["headers"]
    request_params = case_info["parameters"]
    
    # Process placeholders before sending request
    request_headers = substitute_placeholders(request_headers)
    request_params = substitute_placeholders(request_params)
    
    # Deserialize JSON strings
    if request_headers is not None:
        request_headers = json.loads(request_headers)
        
    if auth_token is not None:
        request_headers["Authorization"] = auth_token
        
    if request_params is not None:
        request_params = json.loads(request_params)
        
    # Execute HTTP request based on method
    if http_method.lower() == "get":
        api_response = requests.request(
            method=http_method, 
            url=endpoint_url, 
            params=request_params,
            headers=request_headers
        )
        
    elif http_method.lower() == "post":
        if request_headers is None:
            logger.warning("Missing headers for POST request")
            return
            
        content_type = request_headers.get("Content-Type")
        
        if content_type == "application/json":
            api_response = requests.request(
                method=http_method, 
                url=endpoint_url, 
                json=request_params, 
                headers=request_headers
            )
            
        elif content_type == "application/x-www-form-urlencoded":
            api_response = requests.request(
                method=http_method, 
                url=endpoint_url, 
                data=request_params, 
                headers=request_headers
            )
            
        elif content_type == "multipart/form-data":
            del request_headers["Content-Type"]
            file_reference = request_params["filename"]
            file_data = {"file": (file_reference, open(f"./assets/{file_reference}", "rb"))}
            api_response = requests.request(
                method=http_method, 
                url=endpoint_url,
                headers=request_headers,
                files=file_data
            )
            
    # Extract response data if specified
    capture_response_data(api_response, case_info.get("extract_fields"))
    
    return api_response

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.