Source

flask-testing / flaskext / testing.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
# -*- coding: utf-8 -*-
"""
    flaskext.testing
    ~~~~~~~~~~~~~~~~~

    Flask unittest integration.

    :copyright: (c) 2010 by Dan Jacob.
    :license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import

import warnings

warnings.simplefilter("ignore")

import functools
import StringIO
import unittest
import twill
import simplejson
import nose.tools

from werkzeug import cached_property
from werkzeug import LocalStack, LocalProxy

from flask import Flask

# add more nose  tools

from nose.tools import ok_, eq_, make_decorator, raises, set_trace, \
    timed, assert_equal, assert_not_equal

__all__ = nose.tools.__all__
__all__ += ["assert_200",]


from alfajor import APIClient, WebBrowser

def assert_context(name, value):
    """
    Checks if given name exists in the template context
    and equals the given value.

    :versionadded: 0.2
    :param name: name of context variable
    :param value: value to check against
    """

def assert_redirects(response, location):
    """
    Checks if response is an HTTP redirect to the 
    given location.

    :param response: Flask response
    :param location: relative URL (i.e. without **http://localhost**)
    """
    assert response.status_code in (301, 302)
    assert response.location == "http://localhost" + location
 
def assert_status(response, status_code):
    """
    Helper method to check matching response status.
    
    :param response: Flask response
    :param status_code: response status code (e.g. 200)
    """
    assert response.status_code == status_code

def assert200(response):
    """
    Checks if response status code is 200 

    :param response: Flask response
    """

    assert assert_status(response, 200)


def assert403(self, response):
    """
    Checks if response status code is 403

    :versionadded: 0.2
    :param response: Flask response
    """

    self.assertStatus(response, 403)

assert_403 = assert403

def assert404(self, response):
    """
    Checks if response status code is 404

    :param response: Flask response
    """

    self.assertStatus(response, 404)

assert_404 = assert404

def assert405(self, response):
    """
    Checks if response status code is 405

    :versionadded: 0.2
    :param response: Flask response
    """

    self.assertStatus(response, 405)

assert_405 = assert405


try:
    # we'll use signals for template-related tests if
    # available in this version of Flask
    import blinker
    from flask import template_rendered
    _is_signals = True
except ImportError:
    _is_signals = False

__all__ = ["TestCase", "TwillTestCase"]

class ContextVariableDoesNotExist(Exception):
    pass

class JsonResponseMixin(object):
    """
    Mixin with testing helper methods
    """
    @cached_property
    def json(self):
        return simplejson.loads(self.data)


def _make_test_response(response_class):
    class TestResponse(response_class, JsonResponseMixin):
        pass

    return TestResponse

_testing_ctx_stack = LocalStack()

browser = LocalProxy(lambda: _testing_ctx_stack.top.browser)
client = LocalProxy(lambda: _testing_ctx_stack.top.client)
fixtures = LocalProxy(lambda: _testing_ctx_stack.top.fixtures)

class _GlobalFixtures(object):
    pass

class _TestContext(object):

    def __init__(self, app):

        self.app = app
        
        #self.client = APIClient()
        #self.client.configure_in_scope()
        
        #self.browser = WebBrowser()
        #self.browser.configure_in_scope()
    
        self.client = self.app.test_client()
        self.fixtures = _GlobalFixtures()

    def push(self):

        _testing_ctx_stack.push(self)

    def pop(self):

        _testing_ctx_stack.pop()
        
    def __enter__(self):
        self.push()
        return self

    def __exit__(self, exc_type, exc_value, tb):

        if tb is None:
            self.pop()

           
class _TestModule(object):

    def __init__(self, parent=None):

        self._parent = parent
        self._setup_funcs = []
        self._teardown_funcs = []

    def setup(self, func):
        self._setup_funcs.append(func)
        return func

    def teardown(self, func):
        self._teardown_funcs.append(func)
        return func

    def with_context(self, func):

        @functools.wraps(func)
        def decorate():

            if self._parent:
                app = self._parent.create_app()
            else:
                raise RuntimeError, "Not parent node nor parent set"

            _app_ctx = app.test_request_context()
            _app_ctx.push()

            _test_ctx = _TestContext(app)
            _test_ctx.push()

            if self._parent:
                for setup_func in self._parent._setup_funcs:
                    setup_func()

            for setup_func in self._setup_funcs:
                setup_func()

            try:
                return func()
                
            finally:
                for teardown_func in self._teardown_funcs:
                    teardown_func()

                if self._parent:
                    for teardown_func in self._parent._teardown_funcs:
                        teardown_func()

                _test_ctx.pop()
                _app_ctx.pop()
                
        return decorate

class Testing(_TestModule):

    """
    Works like this::

        from flaskext.testing import testing, browser, client

        testing = Testing(create_app)

    or::
        
        testing = Testing()
        testing.init_app(app)

    uses decorators::

        @testing.with_context
        def test_index_page():
        
            response = client.get("/")
            testing.assert_202(response)

    or::
        
        @testing.setup
        def create_db():
            db.create_all()

        @testing.teardown
        def drop_db():
            db.drop_all()
            db.session.remove()

        @testing.with_context
        def test_index_page():

            browser.open("/")
            assert browser.status_code == 200
            assert browser.document['#A'].tag == 'dl'
            

    """
    def __init__(self, app):
        
        self.init_app(app)

        super(Testing, self).__init__()

    def init_app(self, app):

        if isinstance(app, Flask):
            self.create_app = lambda: app

        else:
            self.create_app = app

    def register_module(self):
        return _TestModule(self)

# old unit-test based classes, for backward compatibility

class TestCase(unittest.TestCase):
    
    def __call__(self, result=None):
        """
        Does the required setup, doing it here
        means you don't have to call super.setUp
        in subclasses.
        """
        try:
            self._pre_setup()
            super(TestCase, self).__call__(result)
        finally:
            self._post_teardown()

    def _pre_setup(self):
        self.app = self._ctx = None

        self.app = self.create_app()

        self._orig_response_class = self.app.response_class
        self.app.response_class = _make_test_response(self.app.response_class)

        self.make_client()

        self._ctx = self.app.test_request_context()
        self._ctx.push()

        self.templates = []
        if _is_signals:
            template_rendered.connect(self._add_template)

    def _add_template(self, app, template, context):
        self.templates.append((template, context))

    def _post_teardown(self):
        if self._ctx is not None:
            self._ctx.pop()
        if self.app is not None:
            self.app.response_class = self._orig_response_class
        if _is_signals:
            template_rendered.disconnect(self._add_template)

    def make_client(self):

        #self.client = APIClient()
        #self.client.configure_in_scope()
        
        #self.browser = WebBrowser()
        #self.browser.configure_in_scope()

        self.client = self.app.test_client()

    def assertTemplateUsed(self, name):
        """
        Checks if a given template is used in the request. 
        Only works if your version of Flask has signals 
        support (0.6+) and blinker is installed.

        :versionadded: 0.2
        :param name: template name
        """
        if not _is_signals:
            raise RuntimeError, "Signals not supported"

        for template, context in self.templates:
            if template.name == name:
                return True
        raise AssertionError, "template %s not used" % name

    assert_template_used = assertTemplateUsed
    
    def get_context_variable(self, name):
        """
        Returns a variable from the context passed to the 
        template. Only works if your version of Flask
        has signals support (0.6+) and blinker is installed.

        Raises a ContextVariableDoesNotExist exception if does
        not exist in context.

        :versionadded: 0.2
        :param name: name of variable
        """
        if not _is_signals:
            raise RuntimeError, "Signals not supported"
        
        for template, context in self.templates:
            if name in context:
                return context[name]
        raise ContextVariableDoesNotExist

    def assertContext(self, name, value):
        """
        Checks if given name exists in the template context
        and equals the given value.

        :versionadded: 0.2
        :param name: name of context variable
        :param value: value to check against
        """

        try:
            assert self.get_context_variable(name) == value
        except ContextVariableDoesNotExist:
            assert False

    assert_context = assertContext

    def assertRedirects(self, response, location):
        """
        Checks if response is an HTTP redirect to the 
        given location.

        :param response: Flask response
        :param location: relative URL (i.e. without **http://localhost**)
        """
        assert response.status_code in (301, 302)
        assert response.location == "http://localhost" + location

    assert_redirects = assertRedirects

    def assertStatus(self, response, status_code):
        """
        Helper method to check matching response status.
        
        :param response: Flask response
        :param status_code: response status code (e.g. 200)
        """
        self.assertEqual(response.status_code, status_code)

    assert_status = assertStatus

    def assert200(self, response):
        """
        Checks if response status code is 200 

        :param response: Flask response
        """

        self.assertStatus(response, 200)

    assert_200 = assert200

    def assert403(self, response):
        """
        Checks if response status code is 403

        :versionadded: 0.2
        :param response: Flask response
        """

        self.assertStatus(response, 403)

    assert_403 = assert403

    def assert404(self, response):
        """
        Checks if response status code is 404

        :param response: Flask response
        """

        self.assertStatus(response, 404)

    assert_404 = assert404

    def assert405(self, response):
        """
        Checks if response status code is 405

        :versionadded: 0.2
        :param response: Flask response
        """

        self.assertStatus(response, 405)

    assert_405 = assert405

class TwillTestCase(TestCase):
    """
    TestCase with Twill helper methods.

    Creates a Twill ``browser`` instance and handles
    WSGI intercept.
    """

    twill_host = "127.0.0.1"
    twill_port = 5000
    twill_scheme = "http"

    def _pre_setup(self):
        super(TwillTestCase, self)._pre_setup()
        twill.set_output(StringIO.StringIO())
        twill.commands.clear_cookies()
        twill.add_wsgi_intercept(self.twill_host, 
                                 self.twill_port, 
                                 lambda: self.app)
    
        self.browser = twill.get_browser()

    def _post_teardown(self):

        twill.remove_wsgi_intercept(self.twill_host, 
                                    self.twill_port)

        twill.commands.reset_output()
        
        super(TwillTestCase, self)._post_teardown()

    def make_twill_url(self, url):
        """
        Makes complete URL based on host, port and scheme
        Twill settings.

        :param url: relative URL
        """
        return "%s://%s:%d%s" % (self.twill_scheme,
                                 self.twill_host, 
                                 self.twill_port,
                                 url)