测试人员常用python脚本

📝 面试求职: 「面试试题小程序」 ,内容涵盖 测试基础、Linux操作系统、MySQL数据库、Web功能测试、接口测试、APPium移动端测试、Python知识、Selenium自动化测试相关、性能测试、性能测试、计算机网络知识、Jmeter、HR面试,命中率杠杠的。(大家刷起来…)

📝 职场经验干货:

软件测试工程师简历上如何编写个人信息(一周8个面试)

软件测试工程师简历上如何编写专业技能(一周8个面试)

软件测试工程师简历上如何编写项目经验(一周8个面试)

软件测试工程师简历上如何编写个人荣誉(一周8个面试)

软件测试行情分享(这些都不了解就别贸然冲了.)

软件测试面试重点,搞清楚这些轻松拿到年薪30W+

软件测试面试刷题小程序免费使用(永久使用)


测试人员常用脚本

目录

1、日志分析工具

2、性能监控工具

3、数据处理工具

4、文件处理工具

5、网络检测工具

6、定时任务工具

日志分析工具

1.1 提取日志中错误信息

def extract_errors(log_file, output_file):
    with open(log_file, 'r') as f:
        lines = f.readlines()
    
    errors = [line for line in lines if "ERROR" in line]
    
    with open(output_file, 'w') as f:
        f.writelines(errors)

# 使用示例
extract_errors("app.log", "errors.log")

1.2 统计日志中关键词出现次数

from collections import defaultdict

def count_keywords(log_file, keywords):
    keyword_count = defaultdict(int)
    
    with open(log_file, 'r') as f:
        for line in f:
            for keyword in keywords:
                if keyword in line:
                    keyword_count[keyword] += 1
    
    return keyword_count

# 使用示例
keywords = ["ERROR", "WARNING", "INFO"]
result = count_keywords("app.log", keywords)
print(result)

1.3 按时间范围过滤日志

from datetime import datetime

def filter_logs_by_time(log_file, start_time, end_time, output_file):
    start = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
    end = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
    
    withopen(log_file, 'r') as f:
        logs = f.readlines()
    
    filtered_logs = []
    forloginlogs:
        log_time_str = log.split()[0] + " " + log.split()[1] # 假设时间戳在日志的前两部分
        log_time = datetime.strptime(log_time_str, "%Y-%m-%d %H:%M:%S")
        ifstart <= log_time <= end:
            filtered_logs.append(log)
    
    withopen(output_file, 'w') as f:
        f.writelines(filtered_logs)

# 使用示例
filter_logs_by_time("app.log", "2025-02-26 12:00:00", "2025-02-06 14:00:00", "filtered_logs.log")

1.4 统计日志中高频错误

from collections import Counter
import re

def top_n_errors(log_file, n=5):
    error_pattern = re.compile(r"ERROR: (.+)")
    errors = []
    
    with open(log_file, 'r') as f:
        for line in f:
            match = error_pattern.search(line)
            if match:
                errors.append(match.group(1))
    
    return Counter(errors).most_common(n)

# 使用示例
top_errors = top_n_errors("app.log", n=3)
print(top_errors)

1.5 日志文件合并

def merge_log_files(log_files, output_file):
    with open(output_file, 'w') as outfile:
        for log_file in log_files:
            with open(log_file, 'r') as infile:
                outfile.write(infile.read())

# 使用示例
merge_log_files(["log1.log", "log2.log", "log3.log"], "merged_logs.log")

1.6 日志文件实时监控

import time

def tail_log_file(log_file):
    with open(log_file, 'r') as f:
        f.seek(0, 2) # 移动到文件末尾
        while True:
            line = f.readline()
            if line:
                print(line.strip())
            else:
                time.sleep(0.1)

# 使用示例
tail_log_file("app.log")

性能监控工具

2.1 监控cpu和内存使用情况

import psutil
import time

def monitor_system(interval=1):
    while True:
        cpu_usage = psutil.cpu_percent(interval=interval)
        memory_usage = psutil.virtual_memory().percent
        print(f"CPU Usage: {cpu_usage}% | Memory Usage: {memory_usage}%")
        time.sleep(interval)

# 使用示例
monitor_system(interval=2)

2.2 监控GPU使用情况

import pynvml

def monitor_gpu_usage():
    pynvml.nvmlInit()
    device_count = pynvml.nvmlDeviceGetCount()
    
    for i in range(device_count):
        handle = pynvml.nvmlDeviceGetHandleByIndex(i)
        util = pynvml.nvmlDeviceGetUtilizationRates(handle)
        memory_info = pynvml.nvmlDeviceGetMemoryInfo(handle)
        print(f"GPU {i}: Usage={util.gpu}%, Memory Used={memory_info.used / 1024 ** 2} MB")

# 使用示例
monitor_gpu_usage()

2.3 监控网络带宽

import psutil
import time

def monitor_network_usage(interval=1):
    old_value = psutil.net_io_counters().bytes_sent + psutil.net_io_counters().bytes_recv
    
    whileTrue:
        new_value = psutil.net_io_counters().bytes_sent + psutil.net_io_counters().bytes_recv
        bandwidth = (new_value - old_value) / interval # 计算带宽(字节/秒)
        print(f"Network Bandwidth: {bandwidth} B/s")
        
        old_value = new_value
        time.sleep(interval)

# 使用示例
monitor_network_usage(interval=2)

2.4 监控磁盘IO

import psutil
import time

def monitor_disk_io(interval=1):
    old_read = psutil.disk_io_counters().read_bytes
    old_write = psutil.disk_io_counters().write_bytes
    
    whileTrue:
        new_read = psutil.disk_io_counters().read_bytes
        new_write = psutil.disk_io_counters().write_bytes
        
        read_speed = (new_read - old_read) / interval
        write_speed = (new_write - old_write) / interval
        
        print(f"Read Speed: {read_speed / 1024} KB/s | Write Speed: {write_speed / 1024} KB/s")
        
        old_read = new_read
        old_write = new_write
        time.sleep(interval)

# 使用示例
monitor_disk_io(interval=2)

2.5 监控进程资源占用

import psutil

def monitor_process(pid):
    process = psutil.Process(pid)
    
    while True:
        cpu_usage = process.cpu_percent(interval=1)
        memory_usage = process.memory_info().rss / 1024 ** 2  # 转换为MB
        print(f"PID {pid}: CPU={cpu_usage}%, Memory={memory_usage} MB")

# 使用示例
monitor_process(1234) # 替换为目标进程的PID

2.6 监控系统温度

import psutil

def monitor_temperature():
    temps = psutil.sensors_temperatures()
    for name, entries in temps.items():
        for entry in entries:
            print(f"{name}: {entry.label} = {entry.current}°C")

# 使用示例
monitor_temperature()

数据处理工具

3.1 数据清洗

import pandas as pd

def clean_data(input_file, output_file):
    df = pd.read_csv(input_file)
    df.dropna(inplace=True) # 删除空值
    df.drop_duplicates(inplace=True) # 删除重复值
    df.to_csv(output_file, index=False)

# 使用示例
clean_data("data.csv", "cleaned_data.csv")

3.2 数据对比

import pandas as pd

def compare_data(file1, file2):
    df1 = pd.read_csv(file1)
    df2 = pd.read_csv(file2)
    diff = df1.compare(df2)
    return diff

# 使用示例
result = compare_data("file1.csv", "file2.csv")
print(result)

文件处理工具

4.1 批量重命名文件

import os

def batch_rename(directory, prefix):
    for count, filename in enumerate(os.listdir(directory)):
        new_name = f"{prefix}_{count}.txt"
        os.rename(os.path.join(directory, filename), os.path.join(directory, new_name))

# 使用示例
batch_rename("/path/to/files", "file")

4.2 查找大文件

import os

def find_large_files(directory, size_limit_mb):
    size_limit = size_limit_mb * 1024 * 1024# 转换为字节
    large_files = []
    
    for root, dirs, files in os.walk(directory):
        for file in files:
            file_path = os.path.join(root, file)
            if os.path.getsize(file_path) > size_limit:
                large_files.append(file_path)
    
    return large_files

# 使用示例
large_files = find_large_files("/path/to/directory", 100) # 查找大于100MB的文件
print(large_files)

网络检测工具

5.1 检测端口是否开放

import socket

def check_port(host, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = sock.connect_ex((host, port))
    sock.close()
    return result == 0

# 使用示例
if check_port("example.com", 80):
    print("Port 80 is open")
else:
    print("Port 80 is closed")

5.2 批量ping测试

import os

def ping_hosts(hosts):
    for host in hosts:
        response = os.system(f"ping -c 1 {host}")
        if response == 0:
            print(f"{host} is up")
        else:
            print(f"{host} is down")

# 使用示例
hosts = ["google.com", "example.com", "localhost"]
ping_hosts(hosts)

定时任务工具

6.1 定时执行任务

import time
from datetime import datetime

def scheduled_task(interval):
    while True:
        print(f"Task executed at {datetime.now()}")
        time.sleep(interval)

# 使用示例
scheduled_task(60) # 每60秒执行一次

最后: 下方这份完整的软件测试视频教程已经整理上传完成,需要的朋友们可以自行领取【保证100%免费】
在这里插入图片描述​​
在这里插入图片描述​​

<think>嗯,用户想找关于测试工程师使用Python编写自动化测试脚本的教程和示例。首先,我需要回忆一下之前的引用内容,看看有没有相关的资料。引用1提到了接口自动化测试的示例,引用2和3都是关于Python自动化测试框架和工具的内容,比如Selenium和PyUnit。这些应该是用户需要的信息。 用户可能对具体的代码示例和步骤感兴趣,所以需要分步骤讲解。比如环境搭建、基础示例、框架使用等。另外,用户可能需要知道如何组织测试用例和处理测试报告,所以得包括这些方面。 还要注意用户提到的测试工程师,所以应该覆盖不同的测试类型,比如Web自动化、接口测试、单元测试等。引用3提到了持续集成,可能也需要提一下如何集成到CI/CD流程中。 需要确保回答结构清晰,分点说明,每个部分都有示例代码和解释。同时,生成的相关问题要围绕用户的需求展开,比如如何选择框架、处理复杂场景或者生成测试报告。最后,检查是否符合系统级指令,比如数学公式的正确格式和引用标注。</think>### 测试工程师使用Python编写自动化测试脚本教程 #### 一、环境搭建与工具选择 1. **Python环境**:安装Python 3.x并配置虚拟环境 ```bash python -m venv test_env source test_env/bin/activate # Linux/Mac test_env\Scripts\activate.bat # Windows ``` 2. **常用库安装**: - Selenium(Web自动化):`pip install selenium` - PyTest(测试框架):`pip install pytest` - Requests(接口测试):`pip install requests` - UnitTest(标准库):Python自带 #### 二、基础自动化测试示例 1. **Web自动化测试(Selenium)** 示例:Chrome浏览器登录功能测试[^2] ```python from selenium import webdriver driver = webdriver.Chrome() driver.get("https://example.com/login") driver.find_element("id", "username").send_keys("test_user") driver.find_element("id", "password").send_keys("secure_pwd") driver.find_element("xpath", "//button[@type='submit']").click() assert "Dashboard" in driver.title driver.quit() ``` 2. **接口测试(Requests + PyTest)** 示例:GET/POST请求验证[^1] ```python import requests def test_api_status(): response = requests.get("https://api.example.com/health") assert response.status_code == 200 assert response.json()["status"] == "OK" def test_login_api(): payload = {"username": "test", "password": "123456"} response = requests.post("https://api.example.com/login", json=payload) assert response.status_code == 200 assert "token" in response.json() ``` 3. **单元测试(UnitTest框架)** 示例:数学函数测试[^2] ```python import unittest def add(a, b): return a + b class TestMathFunc(unittest.TestCase): def test_add(self): self.assertEqual(add(3,5), 8) self.assertNotEqual(add(0,-1), 1) if __name__ == "__main__": unittest.main() ``` #### 三、进阶实践 1. **测试用例组织** - 使用`PyTest`标记分组:`@pytest.mark.smoke` - 参数化测试:`@pytest.mark.parametrize("input,expected", [(1,2), (3,4)])` 2. **测试报告生成** 使用`pytest-html`插件: ```bash pytest --html=report.html ``` 3. **持续集成(CI/CD)集成** 在Jenkins/GitLab中配置自动化触发脚本: ```yaml # .gitlab-ci.yml示例 test_job: image: python:3.9 script: - pip install -r requirements.txt - pytest tests/ ``` #### 四、学习资源推荐 1. **接口自动化**:Requests库官方文档 + Postman联动测试[^1] 2. **Web自动化**:Selenium官方指南 + XPath/CSS定位技巧[^2] 3. **框架进阶**:PyTest插件体系 + 自定义fixture设计[^3] ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值