顶部右侧自定义内容
顶部左侧自定义内容
当前位置:首页 > 一般文章 > 正文

Python 接口自动化测试:10个实战案例

作者:jm8X08LA发布时间:2024-11-29 14:24分类: 一般文章 浏览:224评论:0


导读: 1、数据验证接口 class DataValidator: @staticmethod def validate_email(email):# 使用正则表达式验证邮箱格式 im...
  1. 1、数据验证接口
    class DataValidator:
    @staticmethod
    def validate_email(email):# 使用正则表达式验证邮箱格式

    import re
    pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]{2,}\b'
    return bool(re.match(pattern, email))

  2. 2、HTTP 请求封装
    import requests
    class HTTPClient:
    @staticmethod
    def get(url, params=None):
    response = requests.get(url, params=params)
    return response.json()

  3. 3、文件读写接口
    class FileHandler:
    @staticmethod
    def write_to_file(filename, content):
    with open(filename, 'w') as file:
    file.write(content)
    @staticmethod
    def read_from_file(filename):
    with open(filename, 'r') as file:
    return file.read()

  4. 4、数据解析器

  5. import json
    class JSONParser:
    @staticmethod
    def parse(json_string):
    return json.loads(json_string)
    @staticmethod
    def stringify(data):
    return json.dumps(data)

  6. 5、时间日期处理接口
    from datetime import datetime
    class DateTimeUtils:
    @staticmethod
    def format_datetime(dt=datetime.now()):
    return dt.strftime('%Y-%m-%d %H:%M:%S')

  7. 6、数据加密解密

  8. from cryptography.fernet import Fernet
    class Crypto:
    def init(self, key):
    self.key = key
    self.cipher_suite = Fernet(key)
    def encrypt(self, data):
    return self.cipher_suite.encrypt(data.encode())
    def decrypt(self, token):
    return self.cipher_suite.decrypt(token).decode()

  9. 7、数据持久化接口(使用SQLite)
    import sqlite3
    class Database:
    def init(self, db_name='data.db'):
    self.conn = sqlite3.connect(db_name)
    self.cursor = self.conn.cursor()
    def execute(self, query, data=None):
    if data:
    self.cursor.execute(query, data)
    else:
    self.cursor.execute(query)
    self.conn.commit()
    def fetch_all(self, query):
    self.cursor.execute(query)
    return self.cursor.fetchall()

  10. 8、图像处理接口
    from PIL import Image
    class ImageProcessor:
    @staticmethod
    def resize_image(image_path, size=(100, 100)):
    img = Image.open(image_path)
    img_resized = img.resize(size)
    imgresized.save('resized' + image_path)

  11. 9、异常处理接口
    class ErrorHandler:
    @staticmethod
    def handle_exception(func):
    def wrapper(*args, *kwargs):
    try:
    return func(
    args, **kwargs)
    except Exception as e:
    print(f"Error occurred: {e}")
    return wrapper

  12. 10、配置加载接口
    import yaml
    class ConfigLoader:
    @staticmethod
    def load_config(config_file='config.yaml'):
    with open(config_file, 'r') as file:
    return yaml.safe_load(file)

标签:


发表评论: