python3+requests+unittest实战系列【二】
发布人:shili8
发布时间:2024-11-09 02:37
阅读次数:0
**Python3 + Requests + Unittest 实战系列【二】**
在上一篇文章中,我们已经学习了如何使用 Python3、Requests 库和 Unittest 框架来编写测试用例。今天,我们将继续深入探讨这些技术的应用。
### **1. 测试 API 接口**
我们将创建一个简单的 API 接口,用于演示测试的过程。这个接口将提供一些基本的 CRUD 操作(Create、Read、Update 和 Delete)。
#### **API 接口定义**
# api.pyfrom flask import Flask, request, jsonifyapp = Flask(__name__) #一个简单的数据存储,用于演示测试data = [ {"id":1, "name": "John"}, {"id":2, "name": "Alice"} ] @app.route("/users", methods=["GET"]) def get_users(): return jsonify(data) @app.route("/users/<int:user_id>", methods=["GET"]) def get_user(user_id): for user in data: if user["id"] == user_id: return jsonify(user) return jsonify({"error": "User not found"}),404@app.route("/users", methods=["POST"]) def create_user(): new_user = { "id": len(data) +1, "name": request.json["name"] } data.append(new_user) return jsonify(new_user),201@app.route("/users/<int:user_id>", methods=["PUT"]) def update_user(user_id): for user in data: if user["id"] == user_id: user["name"] = request.json["name"] return jsonify(user) return jsonify({"error": "User not found"}),404@app.route("/users/<int:user_id>", methods=["DELETE"]) def delete_user(user_id): for i, user in enumerate(data): if user["id"] == user_id: del data[i] return jsonify({"message": "User deleted"}) return jsonify({"error": "User not found"}),404if __name__ == "__main__": app.run(debug=True)
#### **测试用例**
# test_api.pyimport unittestfrom requests import get, post, put, deletefrom api import appclass TestAPI(unittest.TestCase): def setUp(self): self.app = app.test_client() def test_get_users(self): response = get('/users') self.assertEqual(response.status_code,200) self.assertIn('John', str(response.data)) self.assertIn('Alice', str(response.data)) def test_get_user(self): response = get('/users/1') self.assertEqual(response.status_code,200) self.assertIn('John', str(response.data)) def test_create_user(self): new_user = {'name': 'Bob'} response = post('/users', json=new_user) self.assertEqual(response.status_code,201) self.assertIn('Bob', str(response.data)) def test_update_user(self): update_user = {'name': 'Charlie'} response = put('/users/1', json=update_user) self.assertEqual(response.status_code,200) self.assertIn('Charlie', str(response.data)) def test_delete_user(self): response = delete('/users/1') self.assertEqual(response.status_code,200) self.assertNotIn('John', str(response.data)) if __name__ == '__main__': unittest.main()
### **2. 测试数据库操作**
我们将创建一个简单的数据库,用于演示测试的过程。这个数据库将提供一些基本的 CRUD 操作(Create、Read、Update 和 Delete)。
#### **数据库定义**
# db.pyimport sqlite3class Database: def __init__(self, db_name): self.conn = sqlite3.connect(db_name) self.cursor = self.conn.cursor() def create_table(self): self.cursor.execute(''' CREATE TABLE users ( id INTEGER PRIMARY KEY, name TEXT NOT NULL ) ''') self.conn.commit() def insert_user(self, user): self.cursor.execute('INSERT INTO users (id, name) VALUES (?, ?)', (user['id'], user['name'])) self.conn.commit() def get_user(self, user_id): self.cursor.execute('SELECT * FROM users WHERE id = ?', (user_id,)) return self.cursor.fetchone() def update_user(self, user_id, new_name): self.cursor.execute('UPDATE users SET name = ? WHERE id = ?', (new_name, user_id)) self.conn.commit() def delete_user(self, user_id): self.cursor.execute('DELETE FROM users WHERE id = ?', (user_id,)) self.conn.commit()
#### **测试用例**
# test_db.pyimport unittestfrom db import Databaseclass TestDatabase(unittest.TestCase): def setUp(self): self.db = Database(':memory:') self.db.create_table() def test_insert_user(self): user = {'id':1, 'name': 'John'} self.db.insert_user(user) result = self.db.get_user(1) self.assertEqual(result[0],1) self.assertEqual(result[1], 'John') def test_get_user(self): user = {'id':2, 'name': 'Alice'} self.db.insert_user(user) result = self.db.get_user(2) self.assertEqual(result[0],2) self.assertEqual(result[1], 'Alice') def test_update_user(self): user = {'id':3, 'name': 'Bob'} self.db.insert_user(user) new_name = 'Charlie' self.db.update_user(3, new_name) result = self.db.get_user(3) self.assertEqual(result[1], 'Charlie') def test_delete_user(self): user = {'id':4, 'name': 'Dave'} self.db.insert_user(user) self.db.delete_user(4) result = self.db.get_user(4) self.assertIsNone(result) if __name__ == '__main__': unittest.main()
### **3. 测试 Web 应用**
我们将创建一个简单的 Web 应用,用于演示测试的过程。这个应用将提供一些基本的 CRUD 操作(Create、Read、Update 和 Delete)。
#### **Web 应用定义**
# web_app.pyfrom flask import Flask, request, jsonifyfrom db import Databaseapp = Flask(__name__) db = Database(':memory:') db.create_table() @app.route('/users', methods=['GET']) def get_users(): users = db.get_all_users() return jsonify(users) @app.route('/users/<int:user_id>', methods=['GET']) def get_user(user_id): user = db.get_user(user_id) if user: return jsonify(user) else: return jsonify({'error': 'User not found'}),404@app.route('/users', methods=['POST']) def create_user(): new_user = { 'id': request.json['id'], 'name': request.json['name'] } db.insert_user(new_user) return jsonify(new_user),201@app.route('/users/<int:user_id>', methods=['PUT']) def update_user(user_id): user = db.get_user(user_id) if user: new_name = request.json['name'] db.update_user(user_id, new_name) return jsonify({'id': user_id, 'name': new_name}),200 else: return jsonify({'error': 'User not found'}),404@app.route('/users/<int:user_id>', methods=['DELETE']) def delete_user(user_id): db.delete_user(user_id) return jsonify({'message': 'User deleted'}),200
#### **测试用例**
# test_web_app.pyimport unittestfrom web_app import app, dbclass TestWebApp(unittest.TestCase): def setUp(self): self.app = app.test_client() def test_get_users(self): response = self.app.get('/users') self.assertEqual(response.status_code,200) self.assertIn('John', str(response.data)) self.assertIn('Alice', str(response.data)) def test_get_user(self): response = self.app.get('/users/1') self.assertEqual(response.status_code,200) self.assertIn('John', str(response.data)) def test_create_user(self): new_user = {'id':2, 'name': 'Bob'} response = self.app.post('/users', json=new_user) self.assertEqual(response.status_code,201) self.assertIn('Bob', str(response.data)) def test_update_user(self): update_user = {'name': 'Charlie'} response = self.app.put('/users/1', json=update_user) self.assertEqual(response.status_code,200) self.assertIn('Charlie', str(response.data)) def test_delete_user(self): response = self.app.delete('/users/1') self.assertEqual(response.status_code,200) self.assertNotIn('John', str(response.data)) if __name__ == '__main__': unittest.main()
### **4. 总结**
在本系列的第二篇文章中,我们讨论了如何使用 Python 的 `unittest` 框架来测试 Web 应用、数据库和其他类型的应用。