2013-05-07 11 views
5

Sto utilizzando Flask e ho endpoint che richiedono l'autorizzazione (e occasionalmente altre intestazioni specifiche dell'app). Nei miei test utilizzare la funzione test_client per creare un client e quindi eseguire i vari get, put, delete calls. Tutte queste chiamate richiedono l'autorizzazione e altre intestazioni da aggiungere. Come posso impostare il client di prova per inserire tali intestazioni su tutte le richieste?Imposta intestazioni HTTP per tutte le richieste in un test pallone.

risposta

11

Puoi avvolgere l'applicazione WSGI e iniettare intestazioni lì:

from flask import Flask, request 
import unittest 

def create_app(): 
    app = Flask(__name__) 

    @app.route('/') 
    def index(): 
     return request.headers.get('Custom', '') 

    return app 

class TestAppWrapper(object): 

    def __init__(self, app): 
     self.app = app 

    def __call__(self, environ, start_response): 
     environ['HTTP_CUSTOM'] = 'Foo' 
     return self.app(environ, start_response) 


class Test(unittest.TestCase): 

    def setUp(self): 
     self.app = create_app() 
     self.app.wsgi_app = TestAppWrapper(self.app.wsgi_app) 
     self.client = self.app.test_client() 

    def test_header(self): 
     resp = self.client.get('/') 
     self.assertEqual('Foo', resp.data) 


if __name__ == '__main__': 
    unittest.main() 
9

La classe Client prende gli stessi argomenti come la classe EnvironBuilder, tra i quali è l'argomento headers parola chiave.

Quindi è sufficiente utilizzare client.get('/', headers={ ... }) per inviare l'autenticazione.

Ora, se si desidera fornire un insieme predefinito di intestazioni da parte del cliente, avresti bisogno di fornire la propria implementazione di open che fornisce un costruttore ambiente modificato (simile a make_test_environ_builder) e impostare app.test_client_class per puntare al tuo nuova classe.

2

Sulla @DazWorrall risposta, e guardando nel codice sorgente Werkzeug, ho finito con la seguente involucro per il passaggio di intestazioni predefinite che mi servivano per l'autenticazione:

class TestAppWrapper: 
    """ This lets the user define custom defaults for the test client. 
    """ 

    def build_header_dict(self): 
     """ Inspired from : https://github.com/pallets/werkzeug/blob/master/werkzeug/test.py#L591 """ 
     header_dict = {} 
     for key, value in self._default_headers.items(): 
      new_key = 'HTTP_%s' % key.upper().replace('-', '_') 
      header_dict[new_key] = value 
     return header_dict 

    def __init__(self, app, default_headers={}): 
     self.app = app 
     self._default_headers = default_headers 

    def __call__(self, environ, start_response): 
     new_environ = self.build_header_dict() 
     new_environ.update(environ) 
     return self.app(new_environ, start_response) 

è quindi possibile utilizzare le cose come:

class BaseControllerTest(unittest.TestCase): 

    def setUp(self): 
     _, headers = self.get_user_and_auth_headers() # Something like: {'Authorization': 'Bearer eyJhbGciOiJ...'} 
     app.wsgi_app = TestAppWrapper(app.wsgi_app, headers) 
     self.app = app.test_client() 

    def test_some_request(self): 
     response = self.app.get("/some_endpoint_that_needs_authentication_header") 
0

È possibile impostare l'intestazione all'interno del client di prova.

client = app.test_client() 
client.environ_base['HTTP_AUTHORIZATION'] = 'Bearer your_token' 

Quindi è possibile utilizzare colpo di testa da richiesta:

request.headers['Authorization'] 
Problemi correlati