Ich möchte Anfrageparameter für das Testen von Einheiten fälschen. Wie kann ich das in Flask erreichen?
Haben Sie Flask-Dokumente zum Testen von gelesen?
Sie können folgendes verwenden:
self.app.post('/path-to-request', data=dict(var1='data1', var2='data2', ...))
self.app.get('/path-to-request', query_string=dict(arg1='data1', arg2='data2', ...))
Die aktuelle Entwicklungsversion von Flask unterstützt auch Testing-JSON-APIs :
from flask import request, jsonify
@app.route('/jsonapi')
def auth():
json_data = request.get_json()
attribute = json_data['attr']
return jsonify(resp=generate_response(attribute))
with app.test_client() as c:
rv = c.post('/jsonapi', json={
'attr': 'value', 'other': 'data'
})
json_data = rv.get_json()
assert generate_response(email, json_data['resp'])
POST:
self.app.post('/endpoint', data=params)
ERHALTEN:
self.app.get('/endpoint', query_string=params)
Wenn Sie lieber test_request_context
verwenden möchten:
import unittest aus myapp import extract_query_params testapp = flask.Flask (__ name__) Klasse TestFoo (unittest.TestCase): def test_happy (selbst): mit testapp.test_request_context ('? limit = 1 & offset = 2'): limit, offset = extract_query_params (['limit', 'offset']) self.assertEquals (limit, 1) self.assertEquals (offset, 2)
Ich hatte immer noch Probleme damit, als ich Postform-Daten für das Anmelden testete. Dies funktionierte für mich.
def login(self, username, password):
return self.app.post('/', data='Client_id=' + username +'&Password=' + password,
follow_redirects=True,content_type='application/x-www-form-urlencoded')
Ich habe herausgefunden, dass dies so ist.
Chrom: Entwicklermodus -> Dokument -> Angefordertes HTML-Dokument -> Registerkarte Kopfzeilen -> Formulardaten -> Quelltext anzeigen
hier ist ein vollständiges Codebeispiel eines Komponententests
testapp = app.test_client()
class Test_test(unittest.TestCase):
def test_user_registration_bad_password_short(self):
response = self.register(name='pat',
email='[email protected]',
password='Flask',
password2='Flask')
self.assertEqual(response.status_code, 200)
self.assertIn(b'password should be 8 or more characters long',
response.data)
def register(self, name, email, password, password2):
return testapp.post(
'/register',
data=dict(username=name,
email=email,
password=password,
password2=password2),
follow_redirects=True
)