怎样用脚本模拟购物车操作?

wen 实用脚本 1

本文目录导读:

怎样用脚本模拟购物车操作?

  1. 基础前端模拟(JavaScript)
  2. 自动化测试脚本(Playwright)
  3. API测试脚本(Python + Requests)
  4. 性能测试脚本(Locust)
  5. 完整测试场景脚本
  6. 关键功能点总结

我来详细介绍几种模拟购物车操作的脚本方法,涵盖不同的测试场景和技术方案。

基础前端模拟(JavaScript)

// 购物车类
class ShoppingCart {
    constructor() {
        this.items = [];
        this.total = 0;
    }
    // 添加商品
    addItem(product, quantity = 1) {
        const existingItem = this.items.find(item => item.id === product.id);
        if (existingItem) {
            existingItem.quantity += quantity;
        } else {
            this.items.push({
                ...product,
                quantity: quantity
            });
        }
        this.calculateTotal();
        this.updateUI();
    }
    // 删除商品
    removeItem(productId) {
        this.items = this.items.filter(item => item.id !== productId);
        this.calculateTotal();
        this.updateUI();
    }
    // 修改数量
    updateQuantity(productId, newQuantity) {
        const item = this.items.find(item => item.id === productId);
        if (item) {
            item.quantity = Math.max(0, newQuantity);
            if (item.quantity === 0) {
                this.removeItem(productId);
            }
        }
        this.calculateTotal();
        this.updateUI();
    }
    // 计算总价
    calculateTotal() {
        this.total = this.items.reduce((sum, item) => 
            sum + (item.price * item.quantity), 0
        );
    }
    // 清空购物车
    clearCart() {
        this.items = [];
        this.total = 0;
        this.updateUI();
    }
    // 更新UI(示例)
    updateUI() {
        console.log('购物车更新:', {
            items: this.items,
            total: this.total
        });
    }
}
// 使用示例
const cart = new ShoppingCart();
// 模拟添加商品
const product1 = { id: 1, name: '商品A', price: 99.9 };
const product2 = { id: 2, name: '商品B', price: 59.9 };
cart.addItem(product1, 2);  // 添加2个商品A
cart.addItem(product2, 1);  // 添加1个商品B
cart.updateQuantity(1, 3);  // 修改商品A数量为3
cart.removeItem(2);         // 删除商品B

自动化测试脚本(Playwright)

const { chromium } = require('playwright');
async function simulateCartOperations() {
    const browser = await chromium.launch({ headless: false });
    const page = await browser.newPage();
    // 访问电商网站
    await page.goto('https://example-shop.com');
    // 模拟购物车操作
    try {
        // 1. 添加商品到购物车
        await page.click('.add-to-cart-button');
        await page.waitForSelector('.cart-count');
        // 2. 查看购物车
        await page.click('.cart-icon');
        await page.waitForURL('**/cart');
        // 3. 修改数量
        await page.fill('.quantity-input', '3');
        await page.click('.update-button');
        // 4. 移除商品
        await page.click('.remove-item-button');
        // 5. 应用优惠券
        await page.fill('.coupon-input', 'DISCOUNT20');
        await page.click('.apply-coupon');
        // 验证结果
        const cartTotal = await page.textContent('.cart-total');
        console.log(`购物车总价: ${cartTotal}`);
    } catch (error) {
        console.error('操作失败:', error);
    } finally {
        await browser.close();
    }
}
simulateCartOperations();

API测试脚本(Python + Requests)

import requests
import json
import random
class CartAPI:
    def __init__(self, base_url):
        self.base_url = base_url
        self.session = requests.Session()
        # 模拟用户登录
        self.login()
    def login(self):
        """模拟用户登录"""
        login_data = {
            'username': 'test_user',
            'password': 'test_password'
        }
        response = self.session.post(f'{self.base_url}/api/login', json=login_data)
        if response.status_code == 200:
            print('登录成功')
            self.user_id = response.json()['user_id']
        else:
            raise Exception('登录失败')
    def add_to_cart(self, product_id, quantity=1):
        """添加商品到购物车"""
        data = {
            'user_id': self.user_id,
            'product_id': product_id,
            'quantity': quantity
        }
        response = self.session.post(f'{self.base_url}/api/cart/add', json=data)
        return response.json()
    def get_cart(self):
        """获取购物车内容"""
        response = self.session.get(f'{self.base_url}/api/cart/{self.user_id}')
        return response.json()
    def update_quantity(self, product_id, new_quantity):
        """更新商品数量"""
        data = {
            'user_id': self.user_id,
            'product_id': product_id,
            'quantity': new_quantity
        }
        response = self.session.put(f'{self.base_url}/api/cart/update', json=data)
        return response.json()
    def remove_item(self, product_id):
        """移除购物车商品"""
        data = {
            'user_id': self.user_id,
            'product_id': product_id
        }
        response = self.session.delete(f'{self.base_url}/api/cart/remove', json=data)
        return response.json()
    def checkout(self):
        """结账"""
        response = self.session.post(f'{self.base_url}/api/cart/checkout/{self.user_id}')
        return response.json()
# 模拟购物车操作
def simulate_cart_scenario():
    api = CartAPI('http://localhost:8000')
    # 模拟随机商品选择
    products = [101, 102, 103, 104, 105]
    # 添加多个商品
    print("=== 添加商品 ===")
    for _ in range(3):
        product_id = random.choice(products)
        quantity = random.randint(1, 3)
        result = api.add_to_cart(product_id, quantity)
        print(f"添加商品 {product_id} x {quantity}: {result}")
    # 查看购物车
    print("\n=== 当前购物车 ===")
    cart = api.get_cart()
    print(json.dumps(cart, indent=2))
    # 修改某个商品数量
    if cart.get('items'):
        first_item = cart['items'][0]
        print(f"\n=== 修改商品 {first_item['product_id']} 数量 ===")
        api.update_quantity(first_item['product_id'], 5)
    # 移除一个商品
    if len(cart.get('items', [])) > 1:
        remove_id = cart['items'][1]['product_id']
        print(f"\n=== 移除商品 {remove_id} ===")
        api.remove_item(remove_id)
    # 最终检查购物车
    print("\n=== 最终购物车状态 ===")
    final_cart = api.get_cart()
    print(json.dumps(final_cart, indent=2))
    # 结账
    print("\n=== 结账 ===")
    checkout_result = api.checkout()
    print(f"结账结果: {checkout_result}")
# 运行模拟
simulate_cart_scenario()

性能测试脚本(Locust)

from locust import HttpUser, task, between
import random
class CartUser(HttpUser):
    wait_time = between(1, 5)
    def on_start(self):
        """用户启动时的初始化"""
        # 登录
        self.client.post("/login", {
            "username": f"test_user_{random.randint(1, 1000)}",
            "password": "test123"
        })
    @task(3)
    def add_to_cart(self):
        """添加商品到购物车"""
        product_id = random.randint(1, 100)
        quantity = random.randint(1, 5)
        self.client.post("/cart/add", json={
            "product_id": product_id,
            "quantity": quantity
        })
    @task(2)
    def view_cart(self):
        """查看购物车"""
        self.client.get("/cart")
    @task(1)
    def update_cart(self):
        """更新购物车商品数量"""
        product_id = random.randint(1, 100)
        new_quantity = random.randint(1, 10)
        self.client.put("/cart/update", json={
            "product_id": product_id,
            "quantity": new_quantity
        })
    @task(1)
    def remove_from_cart(self):
        """从购物车移除商品"""
        product_id = random.randint(1, 100)
        self.client.delete(f"/cart/remove/{product_id}")
    @task(1)
    def checkout(self):
        """结账"""
        self.client.post("/cart/checkout")
# 运行:locust -f cart_simulation.py

完整测试场景脚本

import time
import random
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class CartTestScenario:
    def __init__(self):
        self.driver = webdriver.Chrome()
        self.wait = WebDriverWait(self.driver, 10)
    def setup(self):
        """测试准备"""
        self.driver.maximize_window()
        self.driver.get("https://example-ecommerce.com")
        self.login()
    def login(self):
        """登录操作"""
        self.driver.find_element(By.ID, "login-btn").click()
        self.driver.find_element(By.NAME, "username").send_keys("testuser")
        self.driver.find_element(By.NAME, "password").send_keys("password123")
        self.driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
        time.sleep(2)
    def test_add_multiple_items(self):
        """测试添加多个商品"""
        print("测试:添加多个商品到购物车")
        products = [
            {"name": "Product A", "quantity": 2},
            {"name": "Product B", "quantity": 1},
            {"name": "Product C", "quantity": 3}
        ]
        for product in products:
            # 搜索商品
            search_box = self.driver.find_element(By.NAME, "search")
            search_box.clear()
            search_box.send_keys(product["name"])
            search_box.submit()
            # 等待搜索结果
            self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, "product-card")))
            # 添加购物车
            add_button = self.driver.find_element(By.CLASS_NAME, "add-to-cart")
            for _ in range(product["quantity"]):
                add_button.click()
                time.sleep(0.5)
            print(f"  ✓ 已添加 {product['quantity']} 个 {product['name']}")
    def test_modify_quantities(self):
        """测试修改数量"""
        print("\n测试:修改购物车商品数量")
        # 进入购物车
        self.driver.find_element(By.CLASS_NAME, "cart-icon").click()
        time.sleep(2)
        # 修改第一个商品数量
        quantity_input = self.driver.find_element(By.CSS_SELECTOR, ".cart-item .quantity-input")
        quantity_input.clear()
        quantity_input.send_keys("5")
        update_btn = self.driver.find_element(By.CSS_SELECTOR, ".update-quantity")
        update_btn.click()
        time.sleep(1)
        print("  ✓ 已修改商品数量为 5")
    def test_remove_items(self):
        """测试删除商品"""
        print("\n测试:删除购物车商品")
        remove_buttons = self.driver.find_elements(By.CLASS_NAME, "remove-item")
        if remove_buttons:
            remove_buttons[0].click()
            time.sleep(1)
            print("  ✓ 已删除一个商品")
    def test_apply_coupon(self):
        """测试应用优惠券"""
        print("\n测试:应用优惠券")
        coupon_input = self.driver.find_element(By.CLASS_NAME, "coupon-input")
        coupon_input.send_keys("SAVE20")
        apply_btn = self.driver.find_element(By.CLASS_NAME, "apply-coupon")
        apply_btn.click()
        time.sleep(1)
        # 验证优惠券应用
        discount = self.driver.find_element(By.CLASS_NAME, "discount-amount")
        print(f"  ✓ 优惠券已应用,折扣金额: {discount.text}")
    def test_checkout(self):
        """测试结账"""
        print("\n测试:结账流程")
        checkout_btn = self.driver.find_element(By.CLASS_NAME, "checkout-button")
        checkout_btn.click()
        time.sleep(2)
        # 填写配送信息
        self.driver.find_element(By.NAME, "address").send_keys("测试地址 123号")
        self.driver.find_element(By.NAME, "phone").send_keys("13800138000")
        # 选择支付方式
        payment_options = self.driver.find_elements(By.NAME, "payment")
        if payment_options:
            random.choice(payment_options).click()
        # 提交订单
        submit_btn = self.driver.find_element(By.CLASS_NAME, "submit-order")
        submit_btn.click()
        time.sleep(2)
        # 验证订单
        order_confirmation = self.driver.find_element(By.CLASS_NAME, "order-confirmation")
        print(f"  ✓ 订单提交成功,订单号: {order_confirmation.text}")
    def run_all_tests(self):
        """运行所有测试"""
        try:
            self.setup()
            self.test_add_multiple_items()
            self.test_modify_quantities()
            self.test_remove_items()
            self.test_apply_coupon()
            self.test_checkout()
            print("\n✅ 所有购物车操作测试完成!")
        except Exception as e:
            print(f"❌ 测试失败: {str(e)}")
        finally:
            self.driver.quit()
# 运行测试
scenario = CartTestScenario()
scenario.run_all_tests()

关键功能点总结

操作类型 实现方式 测试重点
添加商品 DOM操作/API请求 数量统计、价格计算
修改数量 输入框修改/API更新 数量限制、库存验证
删除商品 删除按钮/API请求 剩余商品、总价更新
优惠券 表单提交/API调用 折扣计算、有效期
结账 表单提交/API请求 订单生成、支付跳转

选择哪种方案取决于你的具体需求:

  • 单元测试:使用Jest/Pytest测试纯逻辑
  • 自动化测试:使用Playwright/Selenium模拟用户操作
  • API测试:使用Requests直接调用接口
  • 性能测试:使用Locust模拟并发访问

抱歉,评论功能暂时关闭!