Transforming declarative tests into pytest asserts
<p>I have a long script that is full of lines like this</p>

<pre><code>[UBInt8.parse, b"\x01", 0x01, None],
[UBInt8.build, 0x01, b"\x01", None],
</code></pre>

<p>I need to turn them through regular expressions into</p>

<pre><code>assert UBInt8.parse(b"\x01") == 0x01
assert UBInt8.build(0x01) == b"\x01"
</code></pre>

<p>Lists are always of length 4. 1st is method, 2nd is its argument, 3rd is return value, 4th is always None. I already used regex to solve a similar problem (someone produced the parser) but I need help writing the formatting string:</p>

<p>See <a href="http://stackoverflow.com/questions/39131755/removing-six-b-from-multiple-files">Removing six.b from multiple files</a> . This is the code I used before, the formatting expression needs to be rewritten and I dont speak regex. :(</p>

<pre><code>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)
</code></pre>

<p>Here is the manual parsing that I came up with. No regex.</p>

<pre><code>#!/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])
</code></pre>

python regex py.test