- tmpdir
Pytest and tempdir
- This is a simple application that reads and writes config files (ini file).
- We can test the parse_file by preparing some input files and check if we get the expected data structure.
- In order to test the save_file we need to be able to save a file somewhere.
- Saving it in the current folder will create garbage files. (and the folder might be read-only in some environments).
- For each test we'll have to come up with a separate filename so they won't collide.
- Using a tmpdir solves this problem.
examples/pytest/mycfg.py
import re def parse_file(filename): data = {} with open(filename) as fh: for row in fh: row = row.rstrip("\n") if re.search(r'=', row): k, v = re.split(r'\s*=\s*', row) data[k] = v else: pass # error reporting? return data def save_file(filename, data): with open(filename, 'w') as fh: for k in data: fh.write("{}={}\n".format(k, data[k])) if __name__ == '__main__': print(parse_file('a.cfg'))
examples/pytest/a.cfg
name=Foo Bar email = foo@bar.com
examples/pytest/test_mycfg.py
import mycfg import os def test_parse(): data = mycfg.parse_file('a.cfg') assert data, { 'name' : 'Foo Bar', 'email' : 'foo@bar.com', } def test_example(tmpdir): original = { 'name' : 'My Name', 'email' : 'me@home.com', 'home' : '127.0.0.1', } filename = str(tmpdir.join('abc.cfg')) assert not os.path.exists(filename) mycfg.save_file(filename, original) assert os.path.exists(filename) new = mycfg.parse_file(filename) assert new == original