【问题标题】:Randomly choose a file inside a folder using Hypothesis使用假设随机选择文件夹内的文件
【发布时间】:2020-02-22 12:19:24
【问题描述】:

我想使用 Hypothesis 库添加测试(已在软件中用于测试)。 对于这些测试,我必须使用文件夹中包含的一组 txt 文件。 每次运行测试时,我都需要随机选择其中一个文件。 如何使用假设来做到这一点?

编辑 这里基本上看起来像,以符合现有测试的模板。

@given(doc=)
def mytest(doc):

    # assert some stuff according to doc
    assert some_stuff

【问题讨论】:

标签: python testing python-hypothesis


【解决方案1】:

静态案例

如果文件列表被假定为“冻结”(不会删除/添加任何文件),那么我们可以使用os.listdir + hypohtesis.strategies.sampled_from like

import os

from hypothesis import strategies

directory_path = 'path/to/directory/with/txt/files'
txt_files_names = strategies.sampled_from(sorted(os.listdir(directory_path)))

或者如果我们需要完整路径

from functools import partial
...
txt_files_paths = (strategies.sampled_from(sorted(os.listdir(directory_path)))
                   .map(partial(os.path.join, directory_path)))

或者如果目录可能有不同扩展名的文件,我们只需要 .txt 我们可以使用glob.glob

import glob
...
txt_files_paths = strategies.sampled_from(sorted(glob.glob(os.path.join(directory_path, '*.txt'))))

动态案例

如果目录内容可能发生变化,并且我们希望在每次数据生成尝试时进行目录扫描,可以这样做

dynamic_txt_files_names = (strategies.builds(os.listdir,
                                             strategies.just(directory_path))
                           .map(sorted)
                           .flatmap(strategies.sampled_from))

或使用完整路径

dynamic_txt_files_paths = (strategies.builds(os.listdir,
                                             strategies.just(directory_path))
                           .map(sorted)
                           .flatmap(strategies.sampled_from)
                           .map(partial(os.path.join, directory_path)))

glob.glob

dynamic_txt_files_paths = (strategies.builds(glob.glob,
                                             strategies.just(os.path.join(
                                                     directory_path,
                                                     '*.txt')))
                           .map(sorted)
                           .flatmap(strategies.sampled_from))

编辑

【讨论】:

  • 您应该在平面图之前放置一个.map(sorted) 以确保示例可重现 - 并非所有操作系统或文件系统都保证稳定的迭代顺序,这会破坏重放。
  • sorted 特别需要 before sampled_from - 如所写,您并没有稳定迭代顺序,而是将字符串转换为已排序的字符列表!
  • @ZacHatfield-Dodds:你是对的,我的错误,只测试了“静态”案例,现在应该修复
猜你喜欢
  • 2014-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多