首頁 後端開發 Python教學 測試自動化中的 Python 類型參數化裝飾器

測試自動化中的 Python 類型參數化裝飾器

Jan 22, 2025 pm 08:12 PM

Python Typed Parameterized Decorators in Test Automation

Python 的裝飾器機制與現代類型提示功能相結合,顯著提高了測試自動化。 這種強大的組合利用了 Python 的靈活性和 typing 模組的類型安全性,產生了更可維護、可讀和健壯的測試套件。本文探討了先進技術,並著重於它們在測試自動化框架中的應用。

利用 typing 模組的增強功能

typing模組進行了重大改進:

  • PEP 585: 對標準集合中泛型類型的本機支援最大限度地減少了對常見類型的 typing 模組的依賴。
  • PEP 604: | 運算子簡化了 Union 型態註解。
  • PEP 647: TypeAlias 澄清型別別名定義。
  • PEP 649:延遲註解評估可加快大型專案的啟動速度。

建造型別參數化裝飾器

以下是如何使用這些更新的輸入功能來建立裝飾器:

from typing import Protocol, TypeVar, Generic, Callable, Any
from functools import wraps

# TypeVar for generic typing
T = TypeVar('T')

# Protocol for defining function structure
class TestProtocol(Protocol):
    def __call__(self, *args: Any, **kwargs: Any) -> Any:
        ...

def generic_decorator(param: str) -> Callable[[Callable[..., T]], Callable[..., T]]:
    """
    Generic decorator for functions returning type T.

    Args:
        param:  A string parameter.

    Returns:
        A callable wrapping the original function.
    """
    def decorator(func: Callable[..., T]) -> Callable[..., T]:
        @wraps(func)  # Preserves original function metadata
        def wrapper(*args: Any, **kwargs: Any) -> T:
            print(f"Decorator with param: {param}")
            return func(*args, **kwargs)
        return wrapper
    return decorator

@generic_decorator("test_param")
def test_function(x: int) -> int:
    """Returns input multiplied by 2."""
    return x * 2
登入後複製

此裝飾器使用 Protocol 定義測試函數的結構,以提高測試框架中不同函數簽名的彈性。

將裝飾器應用於測試自動化

讓我們看看這些裝飾器如何增強測試自動化:

1。使用 Literal

進行特定於平台的測試
from typing import Literal, Callable, Any
import sys

def run_only_on(platform: Literal["linux", "darwin", "win32"]) -> Callable:
    """
    Runs a test only on the specified platform.

    Args:
        platform: Target platform.

    Returns:
        A callable wrapping the test function.
    """
    def decorator(func: Callable) -> Callable:
        @wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            if sys.platform == platform:
                return func(*args, **kwargs)
            print(f"Skipping test on platform: {sys.platform}")
            return None
        return wrapper
    return decorator

@run_only_on("linux")
def test_linux_feature() -> None:
    """Linux-specific test."""
    pass
登入後複製

Literal 確保類型檢查器識別有效的 platform 值,明確哪些測試在哪些平台上運行——這對於跨平台測試至關重要。

2。帶有線程的超時裝飾器

from typing import Callable, Any, Optional
import threading
import time
from concurrent.futures import ThreadPoolExecutor, TimeoutError

def timeout(seconds: int) -> Callable:
    """
    Enforces a timeout on test functions.

    Args:
        seconds: Maximum execution time.

    Returns:
        A callable wrapping the function with timeout logic.
    """
    def decorator(func: Callable) -> Callable:
        @wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Optional[Any]:
            with ThreadPoolExecutor(max_workers=1) as executor:
                future = executor.submit(func, *args, **kwargs)
                try:
                    return future.result(timeout=seconds)
                except TimeoutError:
                    print(f"Function {func.__name__} timed out after {seconds} seconds")
                    return None
        return wrapper
    return decorator

@timeout(5)
def test_long_running_operation() -> None:
    """Test that times out if it takes too long."""
    time.sleep(10)  # Triggers timeout
登入後複製

這使用執行緒來實現可靠的超時功能,這在控制測試執行時間時至關重要。

3。聯合型式的重試機制

from typing import Callable, Any, Union, Type, Tuple, Optional
import time

def retry_on_exception(
    exceptions: Union[Type[Exception], Tuple[Type[Exception], ...]], 
    attempts: int = 3,
    delay: float = 1.0
) -> Callable:
    """
    Retries a function on specified exceptions.

    Args:
        exceptions: Exception type(s) to catch.
        attempts: Maximum retry attempts.
        delay: Delay between attempts.

    Returns:
        A callable wrapping the function with retry logic.
    """
    def decorator(func: Callable) -> Callable:
        @wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            last_exception: Optional[Exception] = None
            for attempt in range(attempts):
                try:
                    return func(*args, **kwargs)
                except exceptions as e:
                    last_exception = e
                    print(f"Attempt {attempt + 1} failed with {type(e).__name__}: {str(e)}")
                    time.sleep(delay)
            if last_exception:
                raise last_exception
        return wrapper
    return decorator

@retry_on_exception(Exception, attempts=5)
def test_network_connection() -> None:
    """Test network connection with retry logic."""
    pass
登入後複製

這個改進的版本使用全面的類型提示、強大的異常處理和可配置的重試延遲。 Union 類型允許靈活地指定異常類型。

結論

將 Python 的高級類型功能整合到裝飾器中可以提高類型安全性和程式碼可讀性,從而顯著增強測試自動化框架。 顯式類型定義確保測試在正確的條件下運行,並具有適當的錯誤處理和效能限制。這會帶來更健壯、可維護和高效的測試,在大型、分散式或多平台測試環境中尤其有價值。

以上是測試自動化中的 Python 類型參數化裝飾器的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1664
14
CakePHP 教程
1421
52
Laravel 教程
1316
25
PHP教程
1266
29
C# 教程
1239
24
Python vs.C:申請和用例 Python vs.C:申請和用例 Apr 12, 2025 am 12:01 AM

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。Python以简洁和强大的生态系统著称,C 则以高性能和底层控制能力闻名。

2小時的Python計劃:一種現實的方法 2小時的Python計劃:一種現實的方法 Apr 11, 2025 am 12:04 AM

2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

Python:遊戲,Guis等 Python:遊戲,Guis等 Apr 13, 2025 am 12:14 AM

Python在遊戲和GUI開發中表現出色。 1)遊戲開發使用Pygame,提供繪圖、音頻等功能,適合創建2D遊戲。 2)GUI開發可選擇Tkinter或PyQt,Tkinter簡單易用,PyQt功能豐富,適合專業開發。

Python與C:學習曲線和易用性 Python與C:學習曲線和易用性 Apr 19, 2025 am 12:20 AM

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。

您可以在2小時內學到多少python? 您可以在2小時內學到多少python? Apr 09, 2025 pm 04:33 PM

兩小時內可以學到Python的基礎知識。 1.學習變量和數據類型,2.掌握控制結構如if語句和循環,3.了解函數的定義和使用。這些將幫助你開始編寫簡單的Python程序。

Python和時間:充分利用您的學習時間 Python和時間:充分利用您的學習時間 Apr 14, 2025 am 12:02 AM

要在有限的時間內最大化學習Python的效率,可以使用Python的datetime、time和schedule模塊。 1.datetime模塊用於記錄和規劃學習時間。 2.time模塊幫助設置學習和休息時間。 3.schedule模塊自動化安排每週學習任務。

Python:自動化,腳本和任務管理 Python:自動化,腳本和任務管理 Apr 16, 2025 am 12:14 AM

Python在自動化、腳本編寫和任務管理中表現出色。 1)自動化:通過標準庫如os、shutil實現文件備份。 2)腳本編寫:使用psutil庫監控系統資源。 3)任務管理:利用schedule庫調度任務。 Python的易用性和豐富庫支持使其在這些領域中成為首選工具。

Python:探索其主要應用程序 Python:探索其主要應用程序 Apr 10, 2025 am 09:41 AM

Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。

See all articles