You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用pytest测试生成随机整数和的rand_sum函数?

用pytest测试含随机逻辑的rand_sum函数

由于rand_sum依赖random.randint生成随机数,直接测试会因结果不固定无法断言,核心思路是mock随机生成器,让它返回固定值,从而验证函数的累加逻辑是否正确。

测试边界场景

当n=1时,range(1,1)是空序列,循环不会执行,总和应为0:

def test_rand_sum_n1():
    assert rand_sum(1) == 0

用monkeypatch mock随机函数

借助pytest自带的monkeypatch fixture替换random.randint为固定返回的函数:

import random
from your_module import rand_sum  # 替换为实际导入rand_sum的模块名

def test_rand_sum_with_monkeypatch(monkeypatch):
    # 定义mock函数,固定返回10
    def mock_randint(min_val, max_val):
        return 10
    
    # 替换系统的random.randint
    monkeypatch.setattr(random, 'randint', mock_randint)
    
    # n=4时,循环执行3次(range(1,4) → 1、2、3),总和为10*3=30
    assert rand_sum(4) == 30

用unittest.mock patch随机函数

也可以用Python标准库的unittest.mock.patch来临时替换随机函数:

from unittest.mock import patch
import random
from your_module import rand_sum

def test_rand_sum_with_patch():
    with patch('random.randint') as mock_rand:
        # 设置mock的返回值为15
        mock_rand.return_value = 15
        
        # n=5时,循环执行4次,总和为15*4=60
        assert rand_sum(5) == 60

两种方式都能让随机逻辑固定,确保测试用例的可重复性,专注验证函数的累加逻辑是否符合预期。

内容的提问来源于stack exchange,提问作者Nanda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 04:30:11