python - 我如何在 Python 中对随机洗牌操作进行单元测试?

标签 python unit-testing

我已经编写了代码来从 .csv 文件创建一个 secret 圣诞老人列表,其中包含一组名称和相应的电子邮件。

import random
import pandas as pd

def compare(list_of_names, list_of_emails):
    zipped_lists = list(zip(list_of_emails, list_of_names))
    random.shuffle(zipped_lists)  # shuffle list of emails and names
    result = []
    shuffled_emails = [i[0] for i in zipped_lists]
    for i, _ in enumerate(shuffled_emails):
        result.append(zipped_lists[i-1][1])  # shift email relatively one position to the right
    return list(zip(result, shuffled_emails))

def main():
    names  = ["John", "Bob", "Alice"]
    emails = ["John@gmail.com", "Bob@gmail.com", "Alice@outlook.com"]

    print(compare(names,emails))

if __name__ == '__main__':
    main()
我如何对这段代码进行单元测试,因为我使用的是随机洗牌操作?我不确定如何为相同的测试用例编写测试用例。

最佳答案

一种常见的方法是在测试中植入随机数生成器,生成数据集并手动验证。然后,该测试将用作回归测试,以确保实现没有改变。如果实现确实发生了变化,您将被迫重新生成数据集并手动重新验证。
例如:

def test_compare():
    seed = 0xBEEF
    names = ['Alice', 'Bob', 'Cuthbert', 'Daisy', 'Ethelred']
    emails = [f'{n}@company.com' for n in names]

    expected = [('Alice', 'Cuthbert@company.com'), ('Cuthbert', 'Bob@company.com'), ('Bob', 'Daisy@company.com'), ('Daisy', 'Ethelred@company.com'), ('Ethelred', 'Alice@company.com')]

    random.seed(seed)

    #k = list(zip(emails, names))
    #random.shuffle(k)
    #print(k)

    assert compare(names, emails) == expected

test_compare()
我第一次运行测试时,我运行了注释掉的行而不是断言,并手动构建了列表 expected .之后,断言应该通过,直到您更改种子或 compare 的实现。 .
从更广泛的意义上讲,您试图断言关于您正在测试的函数的某些确定性。随机种子的存在正是为了使这成为可能。由于您没有测试 random.shuffle 的属性,使用一堆硬编码的数量是完全没问题的。

关于python - 我如何在 Python 中对随机洗牌操作进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67155178/

相关文章:

python - 显示子进程的控制台输出

python - 生成器和返回生成器的函数之间的区别

python - Ubuntu 上的 Tensorflow GPU/CUDA 安装

c# - 远程 Mysql 连接的模拟 IP 地址 .NET C Sharp

c++ - 模拟来自外部类的静态方法(我无法更改!)

python - 如何更改 Pygame 窗口的名称?

python - Pandas 散点图 : Indices Out-of-Bounds

java - 对使用 httpclient 的类进行单元测试

java - 如何模拟 shirosession?

c# - 使用 Mocks 验证依赖调用时的 TDD Arrange Act Assert 模式