[TIP] structure of a testing talk
andrea crotti
andrea.crotti.0 at gmail.com
Thu Oct 4 08:22:07 PDT 2012
So now I thought that as a teaser example in the beginning of the talk
I will show a bad function, that does too many things:
import subprocess
import MySQLdb
def long_crappy_function():
"""Do a bit of everything
"""
ls_cmd = 'ls'
temp = '/tmp'
p = subprocess.Popen(ls_cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, cwd=temp)
out, err = p.communicate()
res = []
for line in out:
if 'to-match' in line:
res.append(line)
dbc = MySQLdb.connect(host='host', user='user', passwd='passwd',
port='port')
cursor = dbc.cursor(MySQLdb.cursors.DictCursor)
for r in res:
cursor.execute('INSERT INTO table VALUES (%s)' % r)
and in 4 iterative steps reach the following state:
import subprocess
import MySQLdb
def run_ls():
## launching a shell command
ls_cmd = 'ls'
temp = '/tmp'
p = subprocess.Popen(ls_cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, cwd=temp)
## filtering the output of a shell command
out, err = p.communicate()
return out
def filter_output(out):
res = []
for line in out:
if 'to-match' in line:
res.append(line)
return res
def update_to_database(res):
## updating the results to database
dbc = MySQLdb.connect(host='host', user='user', passwd='passwd',
port='port')
cursor = dbc.cursor(MySQLdb.cursors.DictCursor)
for r in res:
cursor.execute('INSERT INTO table VALUES (%s)' % r)
def main():
"""Update filtered result from a shell command to the database
"""
out = run_ls()
res = filter_output(out)
update_to_database(res)
def test_filter_output():
lines = ['x1: to-match', 'x2', 'x3: to-match..']
desired = ['x1: to-match', 'x3: to-match..']
assert filter_output(lines) == desired
if __name__ == '__main__':
test_filter_output()
Where I have now a pure function and a st for it.
What do you think? Another thing which would be nice is to do an
interactive group-solving example of TDD.
I propose a problem to solve, and together we start to write down the
specifications as tests, and make them pass one by one..
Any advice of a nice example to use? I thought about managing
Rational numbers for example, but maybe it's a bit too abstract..
More information about the testing-in-python
mailing list