問題背景
項目上有個模型文件一直在變動,但是自動化腳本里面導入該模型是把模型名稱寫死了的,因此更新了模型文件之後,自動化測試代碼裏面為了導入該文件也一直要修改,所以想通過模糊匹配文件名稱來獲取該文件名稱並導入。
解決方案
使用List Files In Directory關鍵字列出目錄下面符合模糊匹配的文件名稱,該關鍵字返回一個列表,獲取列表中的第一個文件名稱(項目中該文件名稱前綴固定,後面攜帶的日期在變化)
${list}= List Files In Directory ${filepath}/mdaf/common/中文/應急中心/EMC_Package/ pattern=DC資源池級應急*
Log ${list}
${dc_model}= Set Variable ${list[0]}
Log ${dc_model}
${file_name} Remove String ${dc_model} .zip
Set Suite Variable ${dc_file_name} ${file_name}
踩的坑
最開始直接AI提供的方案是使用
{dc_model}= Evaluate str('{dc_model}')
{filename_without_ext}= Evaluate '{dc_model}'.replace('.zip', '')
結果卻報錯了UnicodeDecodeError: 'utf8' codec can't decode byte 0xe8 in position 0: unexpected end of data 類似的這種報錯都是字符編碼格式的。
出現這個問題的原因是使用了python的模塊去處理字符串,默認轉成了unicode字符串。
建議
建議優先使用robotframework自帶的處理字符串的關鍵字
與字符串處理相關的關鍵字
- 基本字符串操作
Remove String
${result}= Remove String Hello World World
# 結果: "Hello "
${result}= Remove String filename.zip .zip
# 結果: "filename"
Replace String
${result}= Replace String Hello World World Robot
# 結果: "Hello Robot"
Get Substring
${result}= Get Substring Hello World 0 5
# 結果: "Hello"
Split String
@{parts}= Split String one,two,three ,
# 結果: @{parts} = ['one', 'two', 'three']
Catenate
${result}= Catenate Hello World
# 結果: "Hello World"
${result}= Catenate SEPARATOR=- Hello World
# 結果: "Hello-World"
- 字符串檢查
Should Contain
Should Contain Hello World World
# 驗證字符串包含指定內容
Should Not Contain
Should Not Contain Hello World Robot
# 驗證字符串不包含指定內容
Should Start With
Should Start With Hello World Hello
# 驗證字符串以指定內容開頭
Should End With
Should End With Hello World World
# 驗證字符串以指定內容結尾
- 字符串轉換
Convert To Lowercase
${result}= Convert To Lowercase Hello World
# 結果: "hello world"
Convert To Uppercase
${result}= Convert To Uppercase Hello World
# 結果: "HELLO WORLD"
Convert To String
${result}= Convert To String 123
# 結果: "123"
- 字符串清理
Strip String
${result}= Strip String ${SPACE}Hello World${SPACE}
# 結果: "Hello World" (去除前後空格)
Fetch From Left
${result}= Fetch From Left Hello World o
# 結果: "Hell"
Fetch From Right
${result}= Fetch From Right Hello World o
# 結果: "rld"
- 字符串比較
Should Be Equal
Should Be Equal Hello Hello
# 驗證兩個字符串相等
Should Be Equal As Strings
Should Be Equal As Strings 123 123
# 將參數轉為字符串後比較
Should Match
Should Match Hello World Hello*
# 使用通配符模式匹配
Should Match Regexp
Should Match Regexp example@email.com ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
# 使用正則表達式匹配
- 高級字符串處理
Get Length
${length}= Get Length Hello World
# 結果: 11
Count Values In String
${count}= Count Values In String Hello World l
# 結果: 3 (統計'l'出現的次數)
Encode String To Bytes & Decode Bytes To String
${bytes}= Encode String To Bytes Hello World UTF-8
${string}= Decode Bytes To String ${bytes} UTF-8
# 處理編碼轉換