【问题标题】:Transforming declarative tests into pytest asserts将声明式测试转换为 pytest 断言
【发布时间】:2016-09-19 02:35:30
【问题描述】:

我有一个很长的脚本,里面写满了这样的行

[UBInt8.parse, b"\x01", 0x01, None],
[UBInt8.build, 0x01, b"\x01", None],

我需要通过正则表达式把它们变成

assert UBInt8.parse(b"\x01") == 0x01
assert UBInt8.build(0x01) == b"\x01"

列表的长度总是 4。第一个是方法,第二个是它的参数,第三个是返回值,第四个总是无。我已经使用正则表达式解决了类似的问题(有人制作了解析器),但我需要帮助编写格式化字符串:

Removing six.b from multiple files。这是我之前使用的代码,格式化表达式需要重写,我不会说正则表达式。 :(

import re
import os

indir = 'files'

for root, dirs, files in os.walk(indir):
    for f in files:
        fname = os.path.join(root, f)
        with open(fname) as f:
            txt = f.read()
        txt = re.sub(r'six\.(b\("[^"]*"\))', r'\1', txt)
        with open(fname, 'w') as f:
            f.write(txt)
        print(fname)

【问题讨论】:

  • 您似乎希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的程序员编写代码,但他们通常只会在发布者已经尝试自己解决问题时提供帮助。展示这项工作的一个好方法是包含您迄今为止编写的代码、示例输入(如果有的话)、预期输出以及您实际获得的输出(控制台输出、回溯等)。您提供的详细信息越多,您可能收到的答案就越多。检查FAQHow to Ask
  • 已编辑。我在这里附上了代码。表达是我所缺少的。

标签: python regex pytest


【解决方案1】:

这是我想出的手动解析。没有正则表达式。

#!/usr/bin/python3

import re, os, sys

def processfile(fname):
    print(fname+'... ')
    with open(fname, 'rt') as f:
        txt = f.readlines()
    with open(fname+"-trans", 'wt') as f:
        for line in txt:
            items = list(map(str.strip, line.strip().strip(",[]").split(",")))
            if len(items) == 4:
                if items[1] == "None":
                    items[1] = ""
                if items[3] == "None":
                    o = "assert {0}({1}) == {2}".format(*items)
                else:
                    if items[1] == "":
                        o = "assert raises({0}) == {3}".format(*items)
                    else:
                        o = "assert raises({0}, {1}) == {3}".format(*items)

                f.write("        "+o+"\n")
            else:
                f.write(line)

processfile(sys.argv[1])

【讨论】:

    猜你喜欢
    • 2021-08-25
    • 1970-01-01
    • 2014-04-09
    • 2011-05-28
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多