案例: ERP 系統中,處理訂單時需要確保庫存充足,否則應當返回相應錯誤。
測試場景: 測試處理訂單的函式,當庫存不足時,應該觸發庫存不足的錯誤。
import unittest
class TestOrderProcessing(unittest.TestCase):
def setUp(self):
self.order_data = {
"product_id": 1,
"quantity": 10,
}
self.inventory = {
1: 5 # 產品庫存不足
}
def test_insufficient_inventory(self):
result = process_order(self.order_data, self.inventory)
self.assertEqual(result, "Insufficient inventory", "Should return 'Insufficient inventory' when stock is too low.")
# 模擬處理訂單函式
def process_order(order, inventory):
product_id = order["product_id"]
quantity = order["quantity"]
if inventory[product_id] < quantity:
return "Insufficient inventory"
return "Order processed"
if __name__ == "__main__":
unittest.main()
案例: ERP 系統會生成銷售報表,您需要測試報表生成的準確性。
測試場景: 測試銷售報表生成功能,確保銷售總額的計算正確。
import unittest
class TestSalesReport(unittest.TestCase):
def setUp(self):
self.sales_data = [
{"product": "A", "quantity": 10, "price": 50},
{"product": "B", "quantity": 5, "price": 100},
]
def test_sales_total(self):
total = generate_sales_report(self.sales_data)
self.assertEqual(total, 1000, "The sales total should be 1000.")
# 模擬銷售報表生成函式
def generate_sales_report(sales_data):
total = 0
for sale in sales_data:
total += sale["quantity"] * sale["price"]
return total
if __name__ == "__main__":
unittest.main()
案例: ERP 系統中,某些功能只能由特定權限的用戶執行,您需要測試權限驗證邏輯。
測試場景: 測試功能操作前的權限檢查,確保只有有權限的用戶才能執行操作。
import unittest
class TestPermissionCheck(unittest.TestCase):
def setUp(self):
self.user_data = {"username": "admin", "role": "user"} # 用戶角色無權限
self.operation = "delete_record"
def test_permission_denied(self):
result = check_permission(self.user_data, self.operation)
self.assertEqual(result, "Permission denied", "User should not have permission to delete records.")
# 模擬權限檢查函式
def check_permission(user, operation):
if user["role"] != "admin" and operation == "delete_record":
return "Permission denied"
return "Permission granted"
if __name__ == "__main__":
unittest.main()