Flea: WSGI testing ################## * :ref:`genindex` * :ref:`modindex` * :ref:`search` .. toctree:: :maxdepth: 3 Overview of testing with flea ============================= The ``Agent`` class provides a user agent that drives a WSGI application:: >>> from flea import Agent >>> agent = Agent(my_wsgi_app) You can now use this agent to navigate your WSGI application by... .. testsetup:: * from fresco import FrescoApp, Request, Response from flea import Agent def redirect_app(environ, start_response): return Response.redirect('/')(environ, start_response) form_html = """ foo link text
""" testapp = FrescoApp() testapp.route_wsgi('/register', redirect_app) testapp.route_wsgi('/', Response(content=[form_html]).buffered()) r = Agent(testapp).get('/') ...making GET requests: .. doctest:: >>> r = r.get('/my-page') ...making POST requests: .. doctest:: >>> r = r.post('/contact', data={'message': 'your father smells of elderberries'}) ...clicking links: .. doctest:: >>> # Click on a link with content 'foo' >>> r = r.click("foo") >>> # Click a link matching a regular expression >>> import re >>> r = r.click(re.compile('f.*o')) >>> # Find a link using a CSS selector >>> r = r("a#mylink").click() >>> # Or an XPath expression >>> r = r("//a[@id='mylink']").click() ...and submitting forms: .. doctest:: >>> r = r("form[name=login-form]").fill(username='me', password='123').submit() >>> r = r("form[name=contact] button[name=send]").submit() Finding elements ---------------- There are several methods for traversing the DOM. The simplest is usually to use CSS selectors: .. doctest:: >>> r.css("a.highlighted") For more complex requirements you can also use XPath, with :meth:`~flea.agent.Agent.find` or with dictionary-style access: .. doctest:: >>> r.find("//a[@class='highlighted']") >>> r["//a[@class='highlighted']"] You can also call the :class:`~flea.agent.Agent` directly, passing either an XPath expression or a CSS selector. Flea will autosense the expression type: .. doctest:: >>> r("a.highlighted") >>> r("//a[@class='highlighted']") If an expression could be interpreted as both a valid XPath and CSS selector, flea defaults to 'css'. You can force an expression to be interpreted as one or the other by passing a ``flavor`` argument: .. doctest:: >>> r("a.highlighted", 'css') >>> r("//a[@class='highlighted']", 'xpath') Filling and submitting forms ============================= Although you can fill fields by altering the necessary DOM properties: ``checked`` (checkboxes, radio buttons), ``selected`` (select options), ``text`` (textareas) and ``value`` for other input types, it's usually more convenient to use the :meth:`fill` method, which presents a common interface to all control types. When you fill in form fields, the underlying DOM is updated. This makes it really easy to check your form is correctly filled while developing tests: .. testcode:: app = Response([ '' '
' '' '
' :meth:`~flea.agent.Agent.fill` will raise an exception if you ask it to fill in a field that does not exist in the form. :meth:`~flea.agent.Agent.fill_sloppy` does not have this restriction, and will ignore any fields it can't find. Text inputs and textareas: .. testcode:: app = Response([ '' '
' '' '
>>> r('input[name=subject]').fill('hello') <...> >>> r('textarea[name=message]').fill('world') <...> >>> r('form').submit_data() [('subject', 'hello'), ('message', 'world')] Checkboxes: .. doctest:: >>> app = Response([ ... '' ... '
' ... '' ... '' ... '' ... '' ... '
' ... '' ... ]) >>> r = Agent(app).get('/') >>> r('input[name=opt-in]').fill(True) <...> >>> r('input[name=items]').fill(['two', 'three']) <...> >>> r('form').submit_data() [('opt-in', 'yes'), ('items', 'two'), ('items', 'three')] Radio buttons: .. doctest:: >>> app = Response([ ... '' ... '
' ... '' ... '' ... '' ... '
' ... '' ... ]) >>> r = Agent(app).get('/') >>> r('input[name=item]').fill('two') <...> >>> r('form').submit_data() [('item', 'two')] Select boxes .. doctest:: >>> app = Response([ ... '' ... '
' ... '' ... '' ... '
' ... '' ... ]).buffered() >>> r = Agent(app).get('/') >>> r('select[name="icecream"]').fill('strawberry') <...> >>> r('select[name="cake"]').fill(['chocolate', 'coffee']) <...> >>> r('form').submit_data() [('icecream', 'strawberry'), ('cake', 'chocolate'), ('cake', 'coffee')] There are some special functions :func:`flea.html.first`, :func:`flea.html.last`, :func:`flea.html.by_index` and :func:`flea.html.random_choice` for filling options from a select box or radio/checkbox group: .. doctest:: >>> from flea import first, by_index >>> agent = Agent(app).get('/') >>> agent('form').fill(icecream=first, cake=by_index(1)) <...> >>> agent('form').submit_data() [('icecream', 'strawberry'), ('cake', 'ginger')] File uploads ------------- To test file upload fields, you must pass a tuple of ``(filename, content-type, data)`` to :meth:`~flea.agent.Agent.fill`. The data part can either be a string: .. doctest:: >>> r = Agent(Response([ ... '' ... '
' ... '' ... '
' ... '' ... ])).get('/') >>> r("input[name=image]").fill(('icon.png', 'image/jpeg', 'testdata')) <...> Or a file-like object: .. doctest:: from StringIO import StringIO r("input[name=image]").fill(('icon.png', 'image/jpeg', StringIO('aaabbbccc'))) Filling forms in a single call ------------------------------ The :meth:`~flea.agent.Agent.fill` method, when called on a form element, is a useful shortcut to filling in an entire form with a single call. Keyword arguments are used to populate input controls by id or name: .. testcode:: r = Agent(Response([ '' '
' '' '' '
' '' ]).buffered()).get('/') r = r["//form[@name='login-form']"].fill( username='fred', password='secret' ).submit() XPath or CSS selector expressions may be used for fields whose names can't be represented as python identifiers or when you need more control over exactly which fields are selected: .. testcode:: r = r("form[name=login-form]").fill(('.//input[1]', 'fred'), ('.//input[2]', 'secret')).submit() HTTP redirects -------------- HTTP redirect responses (301 or 302) are followed by default. If you want to explicitly check for a redirect, you'll need to specify ``follow=False`` when making the request. All methods associated with making a request - ``click``, ``submit``, ``get``, ``post`` etc - take this parameter. To follow a redirect manually: .. doctest:: >>> r = Agent(testapp).get('/') >>> r = r("form[name=register]").submit(follow=False) >>> r.request.path '/register' >>> r.response.status_code 302 >>> r = r.follow() >>> r.request.path '/' >>> r.response.status_code 200 Querying WSGI application responses ----------------------------------- Checking the content of the request ````````````````````````````````````` :: >>> print r.environ {...} >>> print r.request.path_info '/index.html' :attr:`~flea.agent.Agent.request` is a `fresco.request.Request `_ object, and all attributes of that class are available to examine. Checking the content of the response ````````````````````````````````````` .. testcode:: r = Agent(Response('tomato')).get('/') .. doctest:: >>> assert r.content_type == 'text/html; charset=UTF-8' >>> assert r.status == '200 OK' >>> assert r.status_code == 200 >>> assert 'tomato' in r.body You can also query the response directly, via :attr:`~flea.agent.Agent.response`. This is a `fresco.response.Response `_ object, and all attributes of that class are available. By default, responses are checked for a successful status code (2xx or 3xx), and an exception is raised for any other status code. If you want to bypass this checking, use the ``check_status`` argument: .. doctest:: >>> def myapp(environ, start_response): ... start_response('500 Error', [('Content-Type', 'text/plain')]) ... return [b'Sorry, an error occurred'] ... >>> Agent(myapp).get('/') Traceback (most recent call last): ... BadStatusError: GET '/' returned HTTP status '500 Error' >>> Agent(myapp).get('/', check_status=False) Testing JSON APIs `````````````````` Flea has a few methods to help write tests for JSON API endpoints: .. doctest:: >>> r = Agent(Response.json({'fruit': 'tomato', 'color': 'red'})).get('/') >>> assert r.json['fruit'] == 'tomato' >>> r.post_json('/fruits', {'fruit': 'aubergine', 'color': 'purple'}) >>> r.put_json('/fruits/tomato', {'fruit': 'tomato', 'color': 'green'}) Checking returned content ````````````````````````` The :attr:`~flea.agent.Agent.body` property contains the raw response from the server: .. doctest:: >>> r = Agent(Response(["

How now brown cow

"])).get('/') >>> assert 'cow' in r.body Any element selected via an xpath query has various helper methods useful for inspecting the document. :attr:`~flea.agent.Agent.body` is decoded according to the content type supplied in the response. For the raw response body, use :attr:`~flea.agent.Agent.body` instead. The :meth:`~flea.agent.Agent.striptags` method returns only the text node descendants of an HTML response. Whitespace is normalized (newlines, tabs and consecutive spaces are reduced to a single space character) in order to make comparisons more reliable in the face of formatting changes to HTML output. .. doctest:: >>> r = Agent(Response(["

How now brown cow

"])).get('/') >>> r.striptags() 'How now brown cow' Checking if strings are present in an HTML element `````````````````````````````````````````````````` .. doctest:: >>> assert 'cow' in r('p') Accessing the html of selected elements ``````````````````````````````````````` .. doctest:: >>> r('//p[1]').html() '

How now brown cow

' Note that this is the html parsed and reconstructed by lxml, so is unlikely to be the literal HTML emitted by your application - use :attr:`~flea.agent.Agent.body` for that. Accessing textual content of selected elements ```````````````````````````````````````````````` :meth:`~flea.agent.Agent.striptags` removes all HTML tags and normalizes whitespace to make string comparisons easier: .. doctest:: >>> r = Agent(Response([ ... """ ... ...

... How now ... brown ... cow ...

... ... """])).get('/') >>> r('//p[1]').striptags() ' How now brown cow ' WSGI environ ------------ Flea sets the key ``flea.testing`` in the WSGI environment so that WSGI applications can sense if they are in a test environment. This app will say "testing, testing" when called by flea, otherwise it says "hello!": .. doctest:: >>> def app(environ, start_response): ... start_response('200 OK', [('Content-Type', 'text/plain')]) ... if environ.get('flea.testing'): ... return [b'testing, testing'] ... return [b'hello!'] ... >>> Agent(app).get('/').body 'testing, testing' Inspecting and interacting with a web browser --------------------------------------------- Flea gives you two methods for viewing the application under test in a web browser. The :meth:`~flea.agent.Agent.showbrowser` method opens a web browser and displays the content of the most recently loaded request:: >>> r.get('/').showbrowser() The :meth:`~flea.agent.Agent.serve` method starts a HTTP server running your WSGI application and opens a web browser at the location corresponding to the most recent request. For example, the following code causes a web browser to open at ``http://localhost:8080/foobar``:: >>> r.get('/foobar').serve() If you want to change the default hostname and port for the webserver you must specify these when first initializing the :class:`~flea.agent.Agent` object:: >>> r = Agent(my_wsgi_app, host='192.168.1.1', port='8888') >>> r.get('/foobar').serve() Now the web browser would be opened at ``http://192.168.1.1:8888/foobar``. One final note: the first request to the application is handled by relaying the most recent response received to the web browser, including any cookies previously set by the application. Also, if any methods have been called that access the lxml representation of an HTML response – eg finding elements by an XPath query or filling form fields – then the lxml document in its current state will be converted to a string and served to the browser, meaning that while the document should be logically equivalent, it will no longer be a byte-for-byte copy of the response content received from the WSGI application. This **only** applies to the first request, and ensures that the web browser receives a copy of the page as currently in memory, with any form fields filled in and with any cookies set so that you can pick up in your web browser exactly where the :class:`~flea.agent.Agent` object left off. API documention ---------------- .. automodule:: flea.agent :members: .. automodule:: flea.exceptions :members: .. automodule:: flea.html :members: .. automodule:: flea.util :members: .. automodule:: flea.wsgi :members: