使用 Python 中 re 模塊對測試用例 參數化,進行搜索 search、替換 sub


  參數化的目的:運行自動化測試用例的時候參數都不需要改變,直接使用封裝好的類進行參數化,發起請求時直接使用替換后參數;

  自動化測試用例,如果一百個接口要在Excel寫100個sheet表單,每個接口有10個字段,里面有5個都可能是變化的,需要使用參數化,先試用特定的字符在用例中進行站位,在發起請求構造參數時在進行替換占位符;----------我們可以每個接口分別創建一個參數化;

一、用例中手機號的替換,以字符串中的方法,使用 replace (譯:瑞破類似) 進行替換

# 原始字符串:{"mobilephone": "${not_existed_tel}", "pwd":"123456"}
# json 字符串
src_str = '{"mobilephone": "${not_existed_tel}", "pwd":"123456"}'
# 替換 json 字符串中 ${not_existed_tel} 為 18845820369
print(src_str.replace("${not_existed_tel}", "18845820369"))

# 結果:{"mobilephone": "18845820369", "pwd":"123456"}

二、使用 re 模塊進行替換

  re 正則表達式,是一個查找、搜索、替換文本的一種格式語言

搜索方法一,re 模塊中的 match(譯:馬馳)方法,match方法是從頭開始匹配

import re


# 1. 創建原始字符串(待替換的字符串)
src_str4 = '{"mobilephone": "${not_existed_tel}", "pwd":"123456"}'

# 2. 定義模式字符串去進行匹配
# 模式字符串 == 模子,以這個模板去原始字符串中進行比對

# 方法一,re 正則中的 match(譯:馬馳)方法,match方法是從頭開始匹配
# 從 { 開始,匹配不上, 那么就回復None
res = re.match("{not_existed_tel}", src_str4)
print(res)  # 結果:None

# 從 { 開始,能匹配上, 會返回Match對象,加r不需要轉義
res = re.match(r'{"mobilephone"', src_str4)
print(res)      # 返回Match對象結果:<re.Match object; span=(0, 14), match='{"mobilephone"'>

# 獲取匹配的結果內容 group (譯:歌如破)
a = res.group()
print(a)        # 結果:{"mobilephone"

搜索方法二:search   (譯:澀吃)方法,只匹配一次

import re


# 1. 創建原始字符串(待替換的字符串)
src_str1 = '{"mobilephone": "${not_existed_tel}", "pwd":"123456"}'

# 2. 定義模式字符串去進行匹配
# 模式字符串 == 模子,以這個模板去原始字符串中進行比對:"${not_existed_tel}"

# 方法二:search (譯:澀吃)方法,只匹配一次
# 如果能匹配上會返回Match對象,匹配不上會返回None
# 美元符號需要轉義加 r,特殊字符都需要轉義
res1 = re.search(r"\${not_existed_tel}", src_str1)
print(res1)     # Match對象結果:<re.Match object; span=(17, 35), match='${not_existed_tel}'>

# 獲取匹配到的結果,group(譯:格如破)方法
b = res1.group()
print(b)    # 結果:${not_existed_tel}

搜索方法三:findall  (譯:范德奧)方法,會匹配很多次

src_str1 = '{"mobilephone": "${not_existed_tel}", "pwd":"123456"}'
res2 = re.findall(r'o', src_str1)
print(res2)     # 直接返回列表結果:['o', 'o', 'o']

替換方法: sub  (譯:薩博)方法

import re


# 1. 創建原始字符串(待替換的字符串)
src_str2 = '{"mobilephone": "${not_existed_tel}", "pwd":"123456"}'

# 第一個參數為模式字符串:${not_existed_tel}
# 第二個參數為新的字符串:18845820369
# 第三個參數為原始的字符串
# sub 方法如果能匹配上, 那么會返回替換之后的字符串
# sub 方法如果匹配不上, 那么直接返回原始的字符串

# 使用 search 方法先搜索,搜索到再用 sub 方法進行替換;count=0 默認匹配一次
if re.search(r"\${not_existed_tel}", src_str2):     # 先搜索
    res2 = re.sub(r"\${not_existed_tel}", "18845820369", src_str2)  # 在替換
    print(res2)
else:
    print("無法匹配原始字符串")
# 替換后結果:{"mobilephone": "18845820369", "pwd":"123456"}

# 使用正則匹配:\w+ 單詞字符[A-Za-z0-9_],+ 多次匹配;通過正則在原始字符串中匹配
if re.search(r"\${\w+}", src_str2):     # 先搜索
    res2 = re.sub(r"\${not_existed_tel}", "18845820369", src_str2)  # 在替換
    print(res2)
else:
    print("無法匹配原始字符串")
# 替換后結果:{"mobilephone": "18845820369", "pwd":"123456"}

 

  re 模塊基本參數化封裝

 

import re

from scripts.handle_mysql import HandleMysql        # 數據庫封裝
from scripts.handle_config import HandleConfig      # 配置文件封裝
from scripts.constants import CONFIGS_USER_ACCOUTS_DIR      # 要讀取的配置文件路徑


class Context:
    """
    處理上下文參數化
    """
    not_existed_tel_pattern = r'\${not_existed_tel}'
    invest_user_tel_pattern = r'\${invest_user_tel}'  # 配置${invest_user_tel} 的正則表達式
    invest_user_pwd_pattern = r'\${invest_user_pwd}'  # 配置${invest_user_pwd} 的正則表達式

    handle_config = HandleConfig(filename=CONFIGS_USER_ACCOUTS_DIR)     # 配置文件:需要指定用戶賬號所在的配置文件路徑,為了讀取數據

    @classmethod
    def not_existed_tel_replace(cls, data):
        """
        參數化未注冊手機號(調用隨機生成手機號方法)----常用替換方法以下面的方式
        :param data: 發起請求時傳入的data
        :return: 參數化后data 或 匹配不上不需要參數化的原始data
        """
        if re.search(cls.not_existed_tel_pattern, data):          # 使用search方法在用例中匹配,匹配不上不需要替換,返回原始字符串
            do_mysql = HandleMysql()    # 創建會話
            data = re.sub(cls.not_existed_tel_pattern,            # 使用sub方法替換
                          do_mysql.create_not_existed_mobile(),   # 隨機生成一個在數據庫不存在的手機號
                          data)
            do_mysql.close()            # 關閉會話
        return data

    @classmethod
    def invest_user_tel_replace(cls, data):
        """
        參數化已注冊的手機號(配置文件中獲取已注冊手機號碼)
        :param data: 發起請求時傳入的data
        :return: 參數化后data 或 匹配不上不需要參數化的原始data
        """
        if re.search(cls.invest_user_tel_pattern, data):            # 使用search方法在用例中匹配,匹配不上不需要替換,返回原始字符串
            invest_user_tel = cls.handle_config.get_value("invest_user", "mobilephone")     # 配置文件中獲取手機號碼
            data = re.sub(cls.invest_user_tel_pattern, invest_user_tel, data)               # 使用sub方法替換
        return data

    @classmethod
    def invest_user_pwd_replace(cls, data):
        """
        參數化已注冊的密碼(配置文件中賬號的密碼)
        :param data: 發起請求時傳入的data
        :return: 參數化后data 或 匹配不上不需要參數化的原始data
        """
        if re.search(cls.invest_user_pwd_pattern, data):            # 使用search方法在用例中匹配,匹配不上不需要替換,返回原始字符串
            invest_user_pwd = cls.handle_config.get_value("invest_user", "pwd")     # 配置文件中獲取密碼
            data = re.sub(cls.invest_user_pwd_pattern, invest_user_pwd, data)       # 使用sub方法替換
        return data

    @classmethod
    def register_parameterization(cls, data):
        """
        對某個接口批量參數化
        :param data: 發起請求時傳入的data
        :return:  參數化后data 或 匹配不上不需要參數化的原始data
        """
        data = cls.not_existed_tel_replace(data)  # 參數化未注冊的手機號
        data = cls.invest_user_tel_replace(data)  # 參數化已注冊的手機號
        data = cls.invest_user_pwd_replace(data)  # 再參數化已注冊的用戶密碼
        return data


if __name__ == '__main__':
    one_str = '{"mobilephone": "${not_existed_tel}", "pwd":"${invest_user_pwd}", "regname": "KeYou"}'
    two_str = '{"mobilephone": "${not_existed_tel}", "pwd": ""}'
    three_str = '{"mobilephone": "", "pwd": "123456"}'          # 不需要參數化,返回原始data
    six_str = '{"mobilephone": "${invest_user_tel}", "pwd": "123456", "regname": "KeYou"}'

    # 參數化
    print(Context.register_parameterization(one_str))
    print(Context.register_parameterization(two_str))
    print(Context.register_parameterization(three_str))
    print(Context.register_parameterization(six_str))

    # 結果
    # {"mobilephone": "13218495762", "pwd":"123456", "regname": "KeYou"}
    # {"mobilephone": "13278293460", "pwd": ""}
    # {"mobilephone": "", "pwd": "123456"}
    # {"mobilephone": "13226834715", "pwd": "123456", "regname": "KeYou"}

 

 

*******請大家尊重原創,如要轉載,請注明出處:轉載自:https://www.cnblogs.com/shouhu/   謝謝!!******* 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM