Complete worked example
python
import io
import contextlib
import tempfile
from pathlib import Path
import pytest
TEST_SOURCE = """
from flask import Flask
import pytest
@pytest.fixture
def client():
app = Flask(__name__)
app.config['TESTING'] = True
@app.get('/count')
def count():
return BODY
return app.test_client()
def test_count(client):
response = client.get('/count')
assert response.status_code == 200
assert response.json['count'] == 2
"""
def test_contract(count, extra=False):
body = {'count': count}
if extra:
body['debug'] = 'private'
with tempfile.TemporaryDirectory(prefix='owned-flask-tests-') as folder:
path = Path(folder) / ('test_' + Path(folder).name.replace('-', '_') + '.py')
path.write_text('BODY = ' + repr(body) + '\n' + TEST_SOURCE)
with contextlib.redirect_stdout(io.StringIO()):
result = pytest.main([str(path), '-q', '--import-mode=importlib', '-p', 'no:cacheprovider'])
return {'passed': result == 0}- Reasoning
- The helper writes a tiny owned pytest module into a temporary directory, supplying a controlled response body. The fixture builds an application and yields its test client.