104 lines
4.2 KiB
Python
104 lines
4.2 KiB
Python
"""Standalone tests: no tests/conftest.py or account/database fixture required."""
|
|
import json
|
|
from uuid import uuid4
|
|
from unittest.mock import patch
|
|
|
|
import pytest
|
|
from contact_app import create_app, deliver
|
|
|
|
VALID = dict(name='Example Person', email='person@example.com', service='',
|
|
description='A useful software project enquiry.', website='')
|
|
KEY = str(uuid4())
|
|
|
|
@pytest.fixture
|
|
def app():
|
|
return create_app(dict(TESTING=True, EMAIL_DELIVERY_ENABLED=True,
|
|
EMAIL_FROM='BortStack <verified@example.com>',
|
|
CONTACT_EMAIL='business@example.com', RESEND_API_KEY='test-only'))
|
|
|
|
|
|
def post(app, data=VALID, key=KEY):
|
|
return app.test_client().post('/api/contact', json=data, headers={'Idempotency-Key': key})
|
|
|
|
|
|
def test_independent_no_database_or_account_routes(app):
|
|
assert 'sqlalchemy' not in app.extensions
|
|
assert app.test_client().get('/api/health/ready').status_code == 200
|
|
assert app.test_client().get('/api/users').status_code == 404
|
|
assert app.test_client().get('/api/contact/config').json == {'email': 'business@example.com', 'available': True}
|
|
|
|
|
|
def test_success_safe_sender_replyto_and_escaping(app):
|
|
with patch('contact_app.deliver') as send:
|
|
r = post(app, {**VALID, 'name': '<script>Example</script>'})
|
|
assert r.status_code == 200 and r.json['success'] is True
|
|
payload, key, _ = send.call_args.args
|
|
assert payload['from'] == 'BortStack <verified@example.com>'
|
|
assert payload['reply_to'] == VALID['email']
|
|
assert payload['to'] == ['business@example.com']
|
|
assert '<script>' not in payload['html']
|
|
assert key == KEY
|
|
|
|
|
|
@pytest.mark.parametrize('change', [dict(name=''), dict(name='x'*101), dict(name='x\r\nBcc:x@y.com'),
|
|
dict(email='a@example.com\r\nBcc:x@y.com'), dict(email='not-an-email'), dict(email='a@localhost'),
|
|
dict(description='short'), dict(description='x'*5001), dict(service='Unknown'),
|
|
dict(name=['bad']), dict(email=None), dict(company='not allowed'), dict(website='bot')])
|
|
def test_invalid_does_not_send(app, change):
|
|
with patch('contact_app.deliver') as send:
|
|
assert post(app, {**VALID, **change}).status_code == 400
|
|
send.assert_not_called()
|
|
|
|
|
|
@pytest.mark.parametrize('data', [[], 'text', 42, None])
|
|
def test_json_shape(app, data):
|
|
assert post(app, data).status_code == 400
|
|
|
|
|
|
def test_payload_limit(app):
|
|
assert post(app, {**VALID, 'description': 'x'*40000}).status_code == 413
|
|
|
|
|
|
@pytest.mark.parametrize('config', [dict(EMAIL_DELIVERY_ENABLED=False), dict(RESEND_API_KEY=''),
|
|
dict(EMAIL_FROM=''), dict(EMAIL_FROM='x@y.com\r\nBcc:z@y.com'), dict(CONTACT_EMAIL='invalid')])
|
|
def test_disabled_or_unconfigured_never_claims_success(app, config):
|
|
app.config.update(config)
|
|
with patch('contact_app.deliver') as send:
|
|
assert post(app).status_code == 503
|
|
assert app.test_client().get('/api/contact/config').json['available'] is False
|
|
send.assert_not_called()
|
|
|
|
|
|
def test_missing_key(app):
|
|
assert post(app, key='').status_code == 400
|
|
|
|
|
|
def test_provider_failure_generic_no_payload_log(app, caplog):
|
|
with patch('contact_app.deliver', side_effect=RuntimeError('private provider detail')):
|
|
r = post(app)
|
|
assert r.status_code == 503
|
|
assert 'private provider detail' not in r.text + caplog.text
|
|
assert VALID['email'] not in caplog.text
|
|
assert VALID['description'] not in caplog.text
|
|
|
|
|
|
def test_rate_limit(app):
|
|
with patch('contact_app.deliver'):
|
|
responses = [post(app) for _ in range(6)]
|
|
assert [r.status_code for r in responses] == [200]*5 + [429]
|
|
assert responses[-1].headers['Retry-After'] == '3600'
|
|
|
|
|
|
def test_provider_contract_timeout_and_idempotency(app):
|
|
with patch('contact_app.urlopen') as url:
|
|
url.return_value.__enter__.return_value.read.return_value = b'{"id":"accepted"}'
|
|
deliver({'from':'verified@example.com'}, KEY, app.config)
|
|
req = url.call_args.args[0]
|
|
assert url.call_args.kwargs['timeout'] == 10
|
|
assert req.get_header('Idempotency-key') == 'contact/' + KEY
|
|
assert json.loads(req.data) == {'from':'verified@example.com'}
|
|
with patch('contact_app.urlopen') as url:
|
|
url.return_value.__enter__.return_value.read.return_value = b'{}'
|
|
with pytest.raises(ValueError):
|
|
deliver({}, KEY, app.config)
|