【问题标题】:pyhamcrest modify "got" descriptionpyhamcrest 修改“得到”描述
【发布时间】:2014-02-17 16:27:21
【问题描述】:

我编写了一个自定义 hamcrest 匹配器,用于检查列表中的文件是否已被复制。该列表可能很长(1000 个文件+),因此如果缺少一个文件,我不希望匹配器打印出整个列表。

我可以对丢失的文件进行自定义描述,但有没有办法修改Got: <list of files> 部分?

完整代码:

class FilesHaveBeenCopied(BaseMatcher):
    def __init__(self):
        self.missing = None

    def _matches(self, source_files):
        try:            
            self.missing = next(f for f in source_files if not os.path.exists(target_of(f)))
        except StopIteration:
            return True
        return False

    def describe_to(self, description):            
        description.append_text("file to be copied '{0}'".format(self.missing)) 

def have_been_copied():
    return FilesHaveBeenCopied()

用法:

assert_that(self.source_files, have_been_copied())

【问题讨论】:

    标签: python hamcrest


    【解决方案1】:

    覆盖 describe_mismatch 以覆盖完整的实际值:

    def describe_mismatch(self, actual, description):
        description.append(self.missing)
    

    您的describe_to 应该描述预期值——而不是缺失值。或者它应该只报告文件的数量,例如“21 个现有文件的列表”。

    【讨论】:

    • 完美。我将它实现为类成员:describe_mismatch(self, actual, description)。完全按照我的意愿工作,谢谢!
    • @Stefan 很好,谢谢。自从我使用 Python 以来已经太久了。 :)
    猜你喜欢
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 2021-01-30
    • 2012-05-09
    相关资源
    最近更新 更多