Pytest create fixture with file(s) - app and test
examples/pytest/configfile/myapp.py
import json import os def _get_config_file(): return os.environ.get('APP_CONFIG_FILE', 'config.json') def _read_config(): config_file = _get_config_file() with open(config_file) as fh: return json.load(fh) def app(protocol): config = _read_config() # ... do stuff based on the config address = protocol + '://' + config['host'] + ':' + config['port'] path = os.path.dirname(_get_config_file()) outfile = os.path.join(path, 'out.txt') with open(outfile, 'w') as fh: fh.write(address) return address
examples/pytest/configfile/config.json
{"host" : "szabgab.com", "port" : "80"}
examples/pytest/configfile/use_myapp.py
from myapp import app result = app('https') print(result)
examples/pytest/configfile/out.txt
https://szabgab.com:80
- Test application
examples/pytest/configfile/test_app.py
import json import os from myapp import app def test_app_one(tmpdir): config_file = os.path.join(str(tmpdir), 'conf.json') with open(config_file, 'w') as fh: json.dump({'host' : 'code-maven.com', 'port' : '443'}, fh) os.environ['APP_CONFIG_FILE'] = config_file result = app('https') assert result == 'https://code-maven.com:443' outfile = os.path.join(str(tmpdir), 'out.txt') with open(outfile) as fh: output_in_file = fh.read() assert output_in_file == 'https://code-maven.com:443' def test_app_two(tmpdir): config_file = os.path.join(str(tmpdir), 'conf.json') with open(config_file, 'w') as fh: json.dump({'host' : 'code-maven.com', 'port' : '443'}, fh) os.environ['APP_CONFIG_FILE'] = config_file result = app('http') assert result == 'http://code-maven.com:443' outfile = os.path.join(str(tmpdir), 'out.txt') with open(outfile) as fh: output_in_file = fh.read() assert output_in_file == 'http://code-maven.com:443'