Karate复用文件多次调用执行耗时递增,求性能优化方案
问题:提升Karate自动化脚本中多次调用复用文件的性能
Booking Confirmation是自动化脚本中的复用文件,负责调用API接口并返回大JSON payload。首次执行速度较快,主feature文件中会进行大量校验。在执行其他操作后再次调用该复用文件校验修改详情时,执行耗时变长,第三次调用耗时比第二次更长。怀疑是上下文变量被覆盖,现寻求帮助优化性能。
相关代码
main.feature
* def bookingConfirmationDetails = call read('classpath:Opera/ReusableFiles/Features/ReusableBookingConfirmation.feature') {basketReference: '#(reference)', country: '#(countryLowerCase)', language: <languageBooking>, bookingChannel: 'PI'}
ReusableBookingConfirmation.feature(复用文件)
@ignore Feature: Booking Confirmation Background: * url Endpoint # 输入参数 xApiKey, basketReference, language, country, queryFileName, statusCode * def basketReference = karate.get('reference', null) * def language = karate.get('language', null) * def country = karate.get('country', null) * def bookingChannel = karate.get('bookingChannel', '') * def queryFileName = karate.get('queryFile', 'BookingConfirmation.graphql') * def statusCode = karate.get('statusCode', 200) Scenario: Booking Confirmation - Experience API * def query = read('classpath:ReusableFiles/QueryPayload/BookingConfirmation/' + queryFileName) * def variables = {basketReference: '#(basketReference)', country: '#(country)', language: '#(language)', bookingChannel: '#(bookingChannel)'} Given request { query: '#(query)', variables: '#(variables)' } And header X-WHIT-API-KEY = EncryptionUtils.decode(ENCODED_X_WHIT_API_KEY) When method post Then assert responseStatus == statusCode
注意:Endpoint 和 ENCODED_X_WHIT_API_KEY 定义在 karate-config.js 文件中。
优化建议
隔离调用上下文:每次调用复用文件时,避免依赖父上下文的变量传递,直接使用调用时传入的参数,防止变量污染。修改复用文件的参数赋值逻辑,去掉
karate.get,直接使用传入的变量:# 复用文件Background部分修改为直接使用传入参数 * def basketReference = basketReference * def language = language * def country = country * def bookingChannel = bookingChannel * def queryFileName = queryFile || 'BookingConfirmation.graphql' * def statusCode = statusCode || 200缓存静态资源:
BookingConfirmation.graphql是静态文件,无需每次调用都重新读取。可以在karate-config.js中提前加载,或在复用文件中用callonce读取一次:* def query = callonce read('classpath:ReusableFiles/QueryPayload/BookingConfirmation/BookingConfirmation.graphql')避免重复解密API密钥:每次调用都执行
EncryptionUtils.decode是冗余操作,在karate-config.js中提前解密并存储为全局变量,后续直接引用:// karate-config.js var decodedApiKey = EncryptionUtils.decode(ENCODED_X_WHIT_API_KEY); return { decodedApiKey: decodedApiKey, // 其他配置项 };复用文件中直接使用:
And header X-WHIT-API-KEY = decodedApiKey清理冗余变量:主feature中对大JSON payload做大量校验后,及时清理不需要的变量释放内存,比如在下次调用前执行:
* karate.remove('bookingConfirmationDetails')排查API服务端性能:耗时变长可能是API接口本身的问题,单独测试该接口的多次调用响应时间,确认是否是服务端的性能瓶颈。
内容的提问来源于stack exchange,提问作者priya darisini
相关产品推荐
相关产品推荐

