2026年测试工程师(接口自动化)岗位实操考核试题及答案_第1页
2026年测试工程师(接口自动化)岗位实操考核试题及答案_第2页
2026年测试工程师(接口自动化)岗位实操考核试题及答案_第3页
2026年测试工程师(接口自动化)岗位实操考核试题及答案_第4页
2026年测试工程师(接口自动化)岗位实操考核试题及答案_第5页
已阅读5页,还剩26页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

2026年测试工程师(接口自动化)岗位实操考核试题及答案一、接口逆向分析(10分)背景:被测系统「闪电购」采用微服务架构,商品服务端口8080,订单服务端口8081,网关端口8088。网关统一返回格式{"code":0,"msg":"success","data":any}code非0表示失败。1.使用任何工具抓取「登录→加入购物车→提交订单」完整链路,要求:①输出抓包文件至/home/qa/automation/capture/flow.har(2分)②在同目录下给出analysis.md,列出实际调用的7个接口,包含方法、路径、作用、是否携带加密字段(4分)③找出商品服务与订单服务之间通过网关转发的「内部令牌」Header名称及值的前8位(4分)答案解析:①启动虚拟机内预装Chrome,F12开启Network,勾选Preservelog,完成一次下单后右键SaveallasHARwithcontent。②analysis.md示例(节选):```markdown1.POST/gateway/api/v1/login方法:POST作用:账号密码登录加密:password字段采用RSA公钥加密2.GET/gateway/api/v1/product/SPU123方法:GET作用:查询商品详情加密:无...7.POST/gateway/api/v1/order方法:POST作用:提交订单加密:X-Inner-Token携带JWT,需解密```③通过搜索HAR内header名称含inner的字段,发现`X-Inner-Token:eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3...`,前8位为`eyJhbGci`。评分以文件内容为准。二、自动化框架搭建(15分)要求:1.在/home/qa/automation/framework/目录初始化Python工程,采用pytest+requests+allure,目录结构必须符合:```framework/├──config/#环境配置├──data/#测试数据├──utils/#封装├──api/#业务层├──testcase/#用例层├──report/#报告└──requirements.txt```2.实现基础封装BaseApi,支持统一发送请求、打印日志、自动附加网关认证Header,代码需包含异常重试(最多3次,退避系数0.3)。3.提供一条可运行的pytest命令,可在项目根目录一键执行所有用例并生成allure报告,命令写入run.sh,报告静态文件输出至framework/report/html/。答案解析:①目录结构3分,缺失一层扣1分。②BaseApi核心代码(utils/base_api.py)```pythonimportrequests,time,logging,allurefromrequests.adaptersimportHTTPAdapterfromurllib3.util.retryimportRetryclassBaseApi:def__init__(self):self.session=requests.Session()retry=Retry(total=3,backoff_factor=0.3,status_forcelist=[500,502,503,504])self.session.mount('http://',HTTPAdapter(max_retries=retry))self.session.headers.update({'X-Inner-Token':self.get_inner_token()})defget_inner_token(self):从登录接口获取并缓存return'eyJhbGciOiJIUzI1NiJ9.xxx'@allure.step('API{method}{url}')defsend(self,method,url,**kwargs):(f'{method}{url}')r=self.session.request(method,url,timeout=10,**kwargs)r.raise_for_status()returnr```③run.sh```bash!/usr/bin/envbashcd"(dpytesttestcase/-s-q--alluredir=report/allure_rawalluregeneratereport/allure_raw-oreport/html--clean```赋可执行权限chmod+xrun.sh。评分以文件存在且可直接运行通过为准。三、数据驱动与参数化(10分)场景:商品搜索接口GET/gateway/api/v1/product/search?keyword=xxx&page=1&size=20要求:1.在data/search.yaml维护5条关键字(含中文、英文、特殊符号、空串、SQL注入)及期望的最小命中条数。2.编写pytest用例,使用`@pytest.mark.parametrize`读取YAML,断言返回的`data.total`≥期望条数,若keyword为空串则断言code=400。3.用例失败时自动截图请求与响应,并附加到allure报告。答案解析:search.yaml```yamlkeyword:"手机"expect:10keyword:"phone"expect:5keyword:"%'OR1=1--"expect:0keyword:""expect:-1keyword:"©®™"expect:0```test_search.py```pythonimportpytest,yaml,allure,osfromutils.base_apiimportBaseApiYAML_PATH=os.path.join(os.path.dirname(__file__),'../data/search.yaml')withopen(YAML_PATH,encoding='utf-8')asf:data=yaml.safe_load(f)@allure.feature('商品搜索')@pytest.mark.parametrize('kw,exp',[(d['keyword'],d['expect'])fordindata])deftest_search(kw,exp):api=BaseApi()withallure.step(f'搜索关键字:{kw}'):r=api.send('GET',f'{api.gateway}/product/search',params={'keyword':kw,'page':1,'size':20})j=r.json()ifkw=="":assertj['code']==400else:assertj['data']['total']>=exp```评分以YAML存在、参数化运行通过、allure报告内可看到5条用例及失败截图为准。四、加密与签名(10分)背景:下单接口要求对body进行MD5签名,规则:sign=MD256(body的JSON字符串+固定密钥"Lightning2026")请求头需携带X-Sign和X-Timestamp(秒级)。要求:1.在utils/sign.py实现函数get_sign(body:dict)->(str,int),返回签名与时间戳。2.在api/order.py封装提交订单方法submit_order(sku_id,qty),自动附加签名头。3.编写用例验证签名错误时服务返回code=403,签名正确返回code=0。答案解析:utils/sign.py```pythonimporttime,hashlib,jsondefget_sign(body:dict)->(str,int):ts=int(time.time())payload=json.dumps(body,separators=(',',':'),ensure_ascii=False)+"Lightning2026"sign=hashlib.md5(payload.encode()).hexdigest()returnsign,ts```api/order.py```pythonfromutils.base_apiimportBaseApifromutils.signimportget_signclassOrderApi(BaseApi):defsubmit_order(self,sku_id,qty):body={"skuId":sku_id,"qty":qty}sign,ts=get_sign(body)headers={'X-Sign':sign,'X-Timestamp':str(ts)}returnself.send('POST',f'{self.gateway}/order',json=body,headers=headers)```test_sign.py```pythonimportpytest,allurefromapi.orderimportOrderApi@allure.feature('签名验证')deftest_wrong_sign():api=OrderApi()api.session.headers.update({'X-Sign':'wrong'})r=api.send('POST',f'{api.gateway}/order',json={"skuId":"123","qty":1})assertr.json()['code']==403deftest_correct_sign():api=OrderApi()r=api.submit_order("123",1)assertr.json()['code']==0```评分以签名算法正确、用例通过、allure显示两条测试为准。五、数据库断言与回滚(10分)场景:提交订单成功后,需要在订单库lightning_order的t_order表插入一条记录,状态status=1(待支付)。要求:1.在utils/mysql_tool.py封装PyMySQL连接池,支持with语法自动回收连接。2.用例执行前开启事务,执行后查询订单号是否存在并断言,最后回滚事务,保证重复运行无脏数据。3.使用pytestfixture实现,标记scope=function。答案解析:utils/mysql_tool.py```pythonimportpymysqlfromdbutils.pooled_dbimportPooledDBPOOL=PooledDB(pymysql,host='',port=3306,user='root',password='123456',database='lightning_order',maxconnections=10)defget_conn():returnPOOL.connection()```conftest.py```pythonimportpytest,pymysqlfromutils.mysql_toolimportget_conn@pytest.fixture(scope='function')defdb():conn=get_conn()conn.begin()yieldconnconn.rollback()conn.close()```test_order_db.py```pythonimportpytest,allurefromapi.orderimportOrderApifromutils.mysql_toolimportget_conn@allure.feature('订单数据库断言')deftest_order_insert(db):api=OrderApi()r=api.submit_order("SKU2026",2)j=r.json()assertj['code']==0order_no=j['data']['orderNo']withdb.cursor()ascur:cur.execute("selectstatusfromt_orderwhereorder_no=%s",(order_no,))row=cur.fetchone()assertrowisnotNoneassertrow[0]==1```评分以事务回滚、重复运行仍通过、allure报告展示为准。六、Redis缓存验证(8分)场景:商品详情接口在Redis缓存30秒,key格式`product:cache:{spu_id}`,value为JSON字符串。要求:1.用例先请求详情,验证Redis存在对应key且TTL≤30。2.删除缓存后再次请求,验证MySQL与Redis数据一致(比较price字段)。3.使用pytest-redis或自行封装redis连接。答案解析:utils/redis_tool.py```pythonimportredis,jsonrds=redis.Redis(host='',port=6379,db=0,decode_responses=True)```test_cache.py```pythonimportpytest,allure,jsonfromutils.base_apiimportBaseApifromutils.redis_toolimportrdsfromutils.mysql_toolimportget_conn@allure.feature('缓存一致性')deftest_product_cache():spu='SPU2026'api=BaseApi()r=api.send('GET',f'{api.gateway}/product/{spu}')j=r.json()price=j['data']['price']key=f'product:cache:{spu}'assertrds.exists(key)ttl=rds.ttl(key)assert0<ttl<=30rds.delete(key)r=api.send('GET',f'{api.gateway}/product/{spu}')cached=json.loads(rds.get(key))assertcached['price']==pricewithget_conn().cursor()ascur:cur.execute("selectpricefromt_productwherespu_id=%s",(spu,))db_price=cur.fetchone()[0]assertfloat(db_price)==float(price)```评分以缓存TTL、删除再查、数据一致为准。七、错误注入与容错(7分)场景:订单服务依赖库存服务,库存服务端口8082。要求:1.用例使用toxiproxy将8082注入5秒延迟,验证下单接口超时重试2次后返回友好提示,且总耗时<15秒。2.用例结束后自动移除代理,恢复网络。3.输出toxiproxy日志到/home/qa/automation/toxi.log。答案解析:步骤:①启动toxiproxy:dockerrun-d--nametoxiproxy-p8474:8474-p8082:8082shopify/toxiproxy②创建代理:curl-d'{"name":"inventory","listen":":8082","upstream":"inventory:8082"}'http://localhost:8474/proxies③添加延迟toxicity:curl-d'{"type":"latency","attributes":{"latency":5000}}'http://localhost:8474/proxies/inventory/toxicstest_fault.py```pythonimportrequests,time,allure,subprocessfromapi.orderimportOrderApi@allure.feature('容错延迟')deftest_delay():start=time.time()api=OrderApi()api.timeout=6#单次超时6sr=api.submit_order("SKU_DELAY",1)elapsed=time.time()startassertr.json()['code']==0assert10<elapsed<15subprocess.run(['curl','-X','DELETE','http://localhost:8474/proxies/inventory'],check=False)```评分以延迟注入、重试通过、总耗时、日志存在为准。八、持续集成与报告(10分)要求:1.在虚拟机Jenkins新建任务「api-auto-2026」,参数化构建选择环境dev/test/prod,默认test。2.Pipeline脚本从Git本地仓库file:///home/qa/automation/.git拉取,执行run.sh,将allure报告发布到Jenkins插件。3.构建触发邮件,收件人qa@,主题「接口自动化报告:${BUILD_NUMBER}」,正文附带allure链接。4.构建历史保留最近5次,artifacts保留html报告压缩包。答案解析:Jenkinsfile```groovypipeline{agentanyparameters{choice(name:'ENV',choices:['dev','test','prod'],description:'部署环境')}stages{stage('Checkout'){steps{git'file:///home/qa/automation/.git'}}stage('Test'){steps{sh"cdframework&&exportENV=${params.ENV}&&./run.sh"}}}post{always{allureincludeProperties:false,jdk:'',results:[[path:'framework/report/allure_raw']]archiveArtifactsartifacts:'framework/report/html/**',fingerprint:trueemailextto:'qa@',subject:"接口自动化报告:${env.BUILD_NUMBER}",body:'${BUILD_URL}allure'}}options{buildDiscarder(logRotator(numToKeepStr:'5'))}}```评分以Jenkins蓝图可点击构建、allure报告正常显示、邮件收到为准。九、性能基准(10分)场景:商品搜索接口在高并发下RT95线<500ms,错误率<1%。要求:1.使用locust编写性能脚本,文件/home/qa/automation/perf/locustfile.py,支持命令行locust-flocustfile.py--host=http://localhost:8088-u100-r10-t60s。2.输出HTML报告至perf/report.html,内含平均RT、95线、错误率。3.在Jenkins增加构建步骤,若95线>500ms则标记构建为UNSTABLE。答案解析:locustfile.py```pythonfromlocustimportHttpUser,task,betweenclassSearchUser(HttpUser):wait_time=between(0.5,1.5)@task(10)defsearch(self):withself.client.get('/gateway/api/v1/product/search',params={'keyword':'手机','page':1,'size':20},catch_response=True)asr:ifr.json()['code']!=0:r.failure('codenot0')```Jenkins步骤增加```groovysh'cdperf&&locust-flocustfile.py--host=http://localhost:8088-u100-r10-t60s--html=report.html--headless'script{defcontent=readFile'perf/report.html'defp95=(content=~/"95%":(\d+)/)[0][1].toInteger()if(p95>500){currentBuild.result='UNSTABLE'}}```评分以报告存在、指标正确、Jenkins状态变化为准。十、安全测试(10分)场景:登录接口POST/gateway/api/v1/login参数username、password。要求:1.使用bruteforce字典/opt/sec/user.txt、/opt/sec/pass.txt各20条,编写Python脚本security/brute.py,实现多线程5并发,成功返回200且code=0即停止,输出第一条成功组合到security/crack.txt。2.用例脚本test_security.py调用brute.py,并断言破解耗时<60秒,否则失败。3.将破解结果以附件形式上传allure。答案解析:brute.py```pythonimportrequests,threading,itertools,sys,time,osfromconcurrent.futuresimportThreadPoolExecutor,as_completedgateway='http://localhost:8088'users=open('/opt/sec/user.txt').read().split()passw=open('/opt/sec/pass.txt').read().split()found={}lock=threading.Lock()deftry_one(combo):u,p=combor=requests.post(f'{gateway}/gateway/api/v1/login',json={'username':u,'password':p},timeout=5)ifr.status_code==200andr.json()['code']==0:withlock:found['combo']=combofound['resp']=r.textreturnTruereturnFalsedefmain():withThreadPoolExecutor(max_workers=5)asexe:futures=[exe.submit(try_one,c)forcinduct(users,passw)]forfinas_completed(futures):iff.result():exe.shutdown(wait=False,cancel_futures=True)breakif'combo'infound:withopen('security/crack.txt','w')asf:f.write(f"{found['combo'][0]}/{found['combo'][1]}\n{found['resp']}")if__name__=='__main__':main()```test_security.py```pythonimportsubprocess,time,allure,osfromutils.base_apiimportBaseApi@allure.feature('安全破解')deftest_brute():start=time.time()subprocess.run(['python','security/brute.py'],check=True)elapsed=time.time()startassertelapsed<60withopen('security/crack.txt')asf:allure.attach(f.read(),'crackresult',allure.attachment_type.TEXT)```评分以破解成功、耗时、allure附件为准。十一、兼容性矩阵(10分)场景:网关支持HTTP/1.1、HTTP/2,需验证两种协议下相同接口返回一致。要求:1.使用hyper库编写脚本compat/test_http2.py,分别用HTTP/1.1(requests)与HTTP/2请求商品详情,断言返回JSON相等。2.输出对比报告compat/diff.txt,若不一致列出差异字段。3.用例失败自动在allure附加diff.txt。答案解析:test_http2.py```pythonimportrequests,json,allurefromhyperimportHTTP20ConnectionHOST='localhost'PORT=8088P

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论