backend api api testing QA Automate

快速生成API測試案例 - Keploy

張庭瑋 Gary Chang 2024/03/07 10:00:00
1253

環境說明:

 

Keploy官方文件的範例是使用Docker做測試環境

本文為方便示範,使用Windows + wsl + 本機MongoDB*

如何設定可以參考這篇

 

 

前言:

說到測試api,一定會很快地想到swagger 和 Postman

這兩項工具確實是開發中測試api的好幫手,但隨著要測的api越來越多,人工調整難免會出錯

Keploy可以(半)**自動產生測試案例,快速且穩定地替你把關

How it works

運作機制為:"紀錄每次呼叫API時的request / respond"產生測試案例,使用這個【真實情境】進行測試

 

使用範例:

比起文字說明,展示實際使用的效果應該可以比較好理解

使用keploy 提供的python範例

操作流程為 建立學生資料 > 修改 > 刪除

@app.route('/students', methods=['GET'])
def get_students():
    students = list(students_collection.find({}, {'_id': 0}))
    return jsonify(students)

@app.route('/students/<student_id>', methods=['GET'])
def get_student(student_id):
    student = students_collection.find_one({'student_id': student_id}, {'_id': 0})
    return jsonify(student)

@app.route('/students', methods=['POST'])
def create_student():
    new_student = request.json
    students_collection.insert_one(new_student)
    return jsonify({'message': 'Student created successfully'})

@app.route('/students/<student_id>', methods=['PUT'])
def update_student(student_id):
    updated_student = request.json
    students_collection.update_one({'student_id': student_id}, {'$set': updated_student})
    return jsonify({'message': 'Student updated successfully'})

@app.route('/students/<student_id>', methods=['DELETE'])
def delete_student(student_id):
    students_collection.delete_one({'student_id': student_id})
    return jsonify({'message': 'Student deleted successfully'})

 

呼叫的指令為如下 (也可以用Postman或是其他習慣使用的工具,沒有侷限)

curl -X POST -H "Content-Type: application/json" -d '{"student_id": "12345", "name": "John Doe", "age": 20}' http://localhost:6000/students

curl http://localhost:6000/students

curl -X PUT -H "Content-Type: application/json" -d '{"name": "Jane Smith", "age": 21}' http://localhost:6000/students/12345

curl http://localhost:6000/students/12345

curl -X DELETE http://localhost:6000/students/12345

 

Keploy 實際運作畫面

 

通過的情境:

錄製完成之後,執行測試

每次開啟Keploy就會新建一個資料夾

該次錄製的案例名稱就是test - 1, 2, 3....

 

失敗的情境:

這時候我們將DELETE修改為

@app.route('/students/<student_id>', methods=['DELETE'])
def delete_student(student_id):
    
    return jsonify({'message': 'Deletion simulated, but not executed.'})

使用原本的test-set-0進行測試

 

 

讓我們到mocks.ymal看看Keploy怎麼產生測試案例的

用test-2.ymal裡面的時間戳當關鍵字

version: api.keploy.io/v1beta1
kind: Mongo
name: mock-6
spec:
    metadata:
        operation: '{ OpMsg flags: 0, sections: [{ SectionSingle msg: {"update":"students","ordered":true,"lsid":{"id":{"$binary":{"base64":"Ux3NoLNFTjOsXVJRhjfCyQ==","subType":"04"}}},"$db":"studentsdb"} }, { SectionSingle identifier: updates , msgs: [ {"q":{"student_id":"12345"},"u":{"$set":{"name":"Jane Smith","age":{"$numberInt":"21"}}},"multi":false,"upsert":false} ] }], checksum: 0 }'
    requests:
        - header:
            length: 227
            requestId: 783368690
            responseTo: 0
            Opcode: 2013
          message:
            flagBits: 0
            sections:
                - '{ SectionSingle msg: {"update":"students","ordered":true,"lsid":{"id":{"$binary":{"base64":"Ux3NoLNFTjOsXVJRhjfCyQ==","subType":"04"}}},"$db":"studentsdb"} }'
                - '{ SectionSingle identifier: updates , msgs: [ {"q":{"student_id":"12345"},"u":{"$set":{"name":"Jane Smith","age":{"$numberInt":"21"}}},"multi":false,"upsert":false} ] }'
            checksum: 0
          read_delay: 19107808362
    responses:
        - header:
            length: 60
            requestId: 1365
            responseTo: 783368690
            Opcode: 2013
          message:
            flagBits: 0
            sections:
                - '{ SectionSingle msg: {"n":{"$numberInt":"1"},"nModified":{"$numberInt":"1"},"ok":{"$numberDouble":"1.0"}} }'
            checksum: 0
          read_delay: 15387499
    created: 1709352834
    reqTimestampMock: 2024-03-02T12:13:54.773334937+08:00
    resTimestampMock: 2024-03-02T12:13:54.789065636+08:00

 

使用上的考量:

1. 相對新的測試工具

使用上"可能"會遇到一些版本兼容性的問題,例如前一陣子Docker更新有讓部分Mac的使用者無法正常操作

不過在GitHub上面回報的話,他們社群都蠻積極處理的

其實按照官方文件的步驟走就不會碰到太多問題

2. 設定較複雜

上面展示的情境比較單純,如果有其他需求要改變測試情境的話,就要花比較多時間去看文件怎麼使用設定檔

 

補充:

如果要像本文一樣使用python,要記得安裝相關套件

另外Keploy有支援Java ,Golang, Javascript ,Rust

*用wsl環境連到windows本機的db,需要設定mongoDB的連接

mongoDB使用者設定 連接到自己的專案

**原本我想要打全自動,但是最初的"呼叫api"終究還是要手動

 

 

參考資料:

Keploy  What is Keploy?

MondoDB  https://www.mongodb.com/community/forums/

官方demo ( in java)  https://youtu.be/23yQaY81Zho?si=yln5xFBfUyIxXtMR

 

張庭瑋 Gary Chang