溫馨提示×

Python自動化測試在Ubuntu上如何進行

小樊
60
2025-06-23 10:31:41
欄目: 編程語言

在Ubuntu上進行Python自動化測試,你可以遵循以下步驟:

安裝Python和pip

確保你的系統上已經安裝了Python和pip。你可以通過以下命令檢查是否已安裝:

python3 --version
pip3 --version

如果未安裝,可以使用以下命令安裝:

sudo apt update
sudo apt install python3 python3-pip

安裝測試框架

Python有許多測試框架,常用的有unittest、pytest和nose。這里我們以pytest為例。使用以下命令安裝pytest:

pip3 install pytest

編寫測試用例

創建一個Python文件,例如 test_my_module.py,并編寫針對你的代碼的測試用例。以下是一個簡單的示例:

# test_my_module.py
def add(a, b):
    return a + b

def test_add():
    assert add(2, 3) == 5
    assert add(0, 0) == 0

運行測試

在終端中,導航到包含測試文件的目錄,然后運行以下命令:

pytest test_my_module.py

pytest會自動發現并運行所有以 test_ 開頭的文件和函數。

使用pytest進行更高級的測試

pytest提供了豐富的功能,如參數化測試、fixtures、mocking等。以下是一個使用pytest進行接口自動化測試的示例:

安裝requests庫

pip3 install requests

編寫API測試框架

import pytest
import requests
from typing import Dict, Any

class APITestFramework:
    def __init__(self, base_url: str):
        self.base_url = base_url
        self.session = requests.Session()

    def api_request(self, method: str, endpoint: str, **kwargs) -> Dict[str, Any]:
        url = f"{self.base_url.rstrip('/')}/{endpoint.lstrip('/')}"
        try:
            response = self.session.request(method, url, **kwargs)
            response.raise_for_status()
            return {
                'status_code': response.status_code,
                'data': response.json() if response.content else {},
                'headers': dict(response.headers)
            }
        except requests.exceptions.RequestException as e:
            pytest.fail(f"API請求失?。?{e}")

@pytest.fixture(scope="session")
def api_client():
    return APITestFramework("http://localhost:8000")

@pytest.fixture
def test_user():
    return {
        "username": f"test_user_{int(time.time())}",
        "email": "test@example.com",
        "password": "SecurePass123!"
    }

def test_user_login(api_client, test_user):
    data = {"username": test_user["username"], "password": test_user["password"]}
    response = api_client.api_request("POST", "api/login", json=data)
    assert response['status_code'] == 200

運行測試

在終端中運行以下命令:

pytest test_example.py

集成到CI/CD流程(可選)

你可以使用GitHub Actions、GitLab CI或其他CI工具來自動化測試流程。以下是一個簡單的GitHub Actions配置示例:

# .github/workflows/python-app.yml
name: Python application
on: [push]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Set up Python 3.8
      uses: actions/setup-python@v2
      with:
        python-version: 3.8
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install pytest
    - name: Run tests
      run: pytest

通過以上步驟,你可以在Ubuntu上配置一個基本的Python測試環境,并開始編寫和運行測試。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女