testing.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. # -*- coding: utf-8 -*-
  2. """
  3. flask.testsuite.testing
  4. ~~~~~~~~~~~~~~~~~~~~~~~
  5. Test client and more.
  6. :copyright: (c) 2011 by Armin Ronacher.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. import flask
  10. import unittest
  11. from flask.testsuite import FlaskTestCase
  12. from flask._compat import text_type
  13. class TestToolsTestCase(FlaskTestCase):
  14. def test_environ_defaults_from_config(self):
  15. app = flask.Flask(__name__)
  16. app.testing = True
  17. app.config['SERVER_NAME'] = 'example.com:1234'
  18. app.config['APPLICATION_ROOT'] = '/foo'
  19. @app.route('/')
  20. def index():
  21. return flask.request.url
  22. ctx = app.test_request_context()
  23. self.assert_equal(ctx.request.url, 'http://example.com:1234/foo/')
  24. with app.test_client() as c:
  25. rv = c.get('/')
  26. self.assert_equal(rv.data, b'http://example.com:1234/foo/')
  27. def test_environ_defaults(self):
  28. app = flask.Flask(__name__)
  29. app.testing = True
  30. @app.route('/')
  31. def index():
  32. return flask.request.url
  33. ctx = app.test_request_context()
  34. self.assert_equal(ctx.request.url, 'http://localhost/')
  35. with app.test_client() as c:
  36. rv = c.get('/')
  37. self.assert_equal(rv.data, b'http://localhost/')
  38. def test_redirect_keep_session(self):
  39. app = flask.Flask(__name__)
  40. app.secret_key = 'testing'
  41. @app.route('/', methods=['GET', 'POST'])
  42. def index():
  43. if flask.request.method == 'POST':
  44. return flask.redirect('/getsession')
  45. flask.session['data'] = 'foo'
  46. return 'index'
  47. @app.route('/getsession')
  48. def get_session():
  49. return flask.session.get('data', '<missing>')
  50. with app.test_client() as c:
  51. rv = c.get('/getsession')
  52. assert rv.data == b'<missing>'
  53. rv = c.get('/')
  54. assert rv.data == b'index'
  55. assert flask.session.get('data') == 'foo'
  56. rv = c.post('/', data={}, follow_redirects=True)
  57. assert rv.data == b'foo'
  58. # This support requires a new Werkzeug version
  59. if not hasattr(c, 'redirect_client'):
  60. assert flask.session.get('data') == 'foo'
  61. rv = c.get('/getsession')
  62. assert rv.data == b'foo'
  63. def test_session_transactions(self):
  64. app = flask.Flask(__name__)
  65. app.testing = True
  66. app.secret_key = 'testing'
  67. @app.route('/')
  68. def index():
  69. return text_type(flask.session['foo'])
  70. with app.test_client() as c:
  71. with c.session_transaction() as sess:
  72. self.assert_equal(len(sess), 0)
  73. sess['foo'] = [42]
  74. self.assert_equal(len(sess), 1)
  75. rv = c.get('/')
  76. self.assert_equal(rv.data, b'[42]')
  77. with c.session_transaction() as sess:
  78. self.assert_equal(len(sess), 1)
  79. self.assert_equal(sess['foo'], [42])
  80. def test_session_transactions_no_null_sessions(self):
  81. app = flask.Flask(__name__)
  82. app.testing = True
  83. with app.test_client() as c:
  84. try:
  85. with c.session_transaction() as sess:
  86. pass
  87. except RuntimeError as e:
  88. self.assert_in('Session backend did not open a session', str(e))
  89. else:
  90. self.fail('Expected runtime error')
  91. def test_session_transactions_keep_context(self):
  92. app = flask.Flask(__name__)
  93. app.testing = True
  94. app.secret_key = 'testing'
  95. with app.test_client() as c:
  96. rv = c.get('/')
  97. req = flask.request._get_current_object()
  98. self.assert_true(req is not None)
  99. with c.session_transaction():
  100. self.assert_true(req is flask.request._get_current_object())
  101. def test_session_transaction_needs_cookies(self):
  102. app = flask.Flask(__name__)
  103. app.testing = True
  104. c = app.test_client(use_cookies=False)
  105. try:
  106. with c.session_transaction() as s:
  107. pass
  108. except RuntimeError as e:
  109. self.assert_in('cookies', str(e))
  110. else:
  111. self.fail('Expected runtime error')
  112. def test_test_client_context_binding(self):
  113. app = flask.Flask(__name__)
  114. @app.route('/')
  115. def index():
  116. flask.g.value = 42
  117. return 'Hello World!'
  118. @app.route('/other')
  119. def other():
  120. 1 // 0
  121. with app.test_client() as c:
  122. resp = c.get('/')
  123. self.assert_equal(flask.g.value, 42)
  124. self.assert_equal(resp.data, b'Hello World!')
  125. self.assert_equal(resp.status_code, 200)
  126. resp = c.get('/other')
  127. self.assert_false(hasattr(flask.g, 'value'))
  128. self.assert_in(b'Internal Server Error', resp.data)
  129. self.assert_equal(resp.status_code, 500)
  130. flask.g.value = 23
  131. try:
  132. flask.g.value
  133. except (AttributeError, RuntimeError):
  134. pass
  135. else:
  136. raise AssertionError('some kind of exception expected')
  137. def test_reuse_client(self):
  138. app = flask.Flask(__name__)
  139. c = app.test_client()
  140. with c:
  141. self.assert_equal(c.get('/').status_code, 404)
  142. with c:
  143. self.assert_equal(c.get('/').status_code, 404)
  144. def test_test_client_calls_teardown_handlers(self):
  145. app = flask.Flask(__name__)
  146. called = []
  147. @app.teardown_request
  148. def remember(error):
  149. called.append(error)
  150. with app.test_client() as c:
  151. self.assert_equal(called, [])
  152. c.get('/')
  153. self.assert_equal(called, [])
  154. self.assert_equal(called, [None])
  155. del called[:]
  156. with app.test_client() as c:
  157. self.assert_equal(called, [])
  158. c.get('/')
  159. self.assert_equal(called, [])
  160. c.get('/')
  161. self.assert_equal(called, [None])
  162. self.assert_equal(called, [None, None])
  163. class SubdomainTestCase(FlaskTestCase):
  164. def setUp(self):
  165. self.app = flask.Flask(__name__)
  166. self.app.config['SERVER_NAME'] = 'example.com'
  167. self.client = self.app.test_client()
  168. self._ctx = self.app.test_request_context()
  169. self._ctx.push()
  170. def tearDown(self):
  171. if self._ctx is not None:
  172. self._ctx.pop()
  173. def test_subdomain(self):
  174. @self.app.route('/', subdomain='<company_id>')
  175. def view(company_id):
  176. return company_id
  177. url = flask.url_for('view', company_id='xxx')
  178. response = self.client.get(url)
  179. self.assert_equal(200, response.status_code)
  180. self.assert_equal(b'xxx', response.data)
  181. def test_nosubdomain(self):
  182. @self.app.route('/<company_id>')
  183. def view(company_id):
  184. return company_id
  185. url = flask.url_for('view', company_id='xxx')
  186. response = self.client.get(url)
  187. self.assert_equal(200, response.status_code)
  188. self.assert_equal(b'xxx', response.data)
  189. def suite():
  190. suite = unittest.TestSuite()
  191. suite.addTest(unittest.makeSuite(TestToolsTestCase))
  192. suite.addTest(unittest.makeSuite(SubdomainTestCase))
  193. return suite