Skip to content
Myr

Tests pass now.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Markus Unterwaditzer · committed by Markus Unterwaditzer · parent 961db8a · Browse files · 24 files+421 added−530 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

24 files+421 added−530 removed

  • tests:+157 added−268 removed
  • other:+264 added−262 removed

24 files+421 added−530 removed

deleted:examples/blueprintexample/blueprintexample_test.py-36 removed
1# -*- coding: utf-8 -*-2"""3 Blueprint Example Tests4 ~~~~~~~~~~~~~~56 Tests the Blueprint example app7"""8import blueprintexample9import unittest101112class BlueprintExampleTestCase(unittest.TestCase):1314 def setUp(self):15 self.app = blueprintexample.app.test_client()16 17 def test_urls(self):18 r = self.app.get('/')19 self.assertEquals(r.status_code, 200)20 21 r = self.app.get('/hello')22 self.assertEquals(r.status_code, 200)23 24 r = self.app.get('/world')25 self.assertEquals(r.status_code, 200)26 27 #second blueprint instance28 r = self.app.get('/pages/hello')29 self.assertEquals(r.status_code, 200)30 31 r = self.app.get('/pages/world')32 self.assertEquals(r.status_code, 200)33 34 35if __name__ == '__main__':36 unittest.main()
added:examples/blueprintexample/test_blueprintexample.py+33 added
1# -*- coding: utf-8 -*-2"""3 Blueprint Example Tests4 ~~~~~~~~~~~~~~56 Tests the Blueprint example app7"""8import pytest910import blueprintexample111213@pytest.fixture14def client():15 return blueprintexample.app.test_client()161718def test_urls(client):19 r = client.get('/')20 assert r.status_code == 2002122 r = client.get('/hello')23 assert r.status_code == 2002425 r = client.get('/world')26 assert r.status_code == 2002728 # second blueprint instance29 r = client.get('/pages/hello')30 assert r.status_code == 2003132 r = client.get('/pages/world')33 assert r.status_code == 200
deleted:examples/flaskr/flaskr_tests.py-76 removed
1# -*- coding: utf-8 -*-2"""3 Flaskr Tests4 ~~~~~~~~~~~~56 Tests the Flaskr application.78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import os12import flaskr13import unittest14import tempfile151617class FlaskrTestCase(unittest.TestCase):1819 def setUp(self):20 """Before each test, set up a blank database"""21 self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()22 flaskr.app.config['TESTING'] = True23 self.app = flaskr.app.test_client()24 with flaskr.app.app_context():25 flaskr.init_db()2627 def tearDown(self):28 """Get rid of the database again after each test."""29 os.close(self.db_fd)30 os.unlink(flaskr.app.config['DATABASE'])3132 def login(self, username, password):33 return self.app.post('/login', data=dict(34 username=username,35 password=password36 ), follow_redirects=True)3738 def logout(self):39 return self.app.get('/logout', follow_redirects=True)4041 # testing functions4243 def test_empty_db(self):44 """Start with a blank database."""45 rv = self.app.get('/')46 assert b'No entries here so far' in rv.data4748 def test_login_logout(self):49 """Make sure login and logout works"""50 rv = self.login(flaskr.app.config['USERNAME'],51 flaskr.app.config['PASSWORD'])52 assert b'You were logged in' in rv.data53 rv = self.logout()54 assert b'You were logged out' in rv.data55 rv = self.login(flaskr.app.config['USERNAME'] + 'x',56 flaskr.app.config['PASSWORD'])57 assert b'Invalid username' in rv.data58 rv = self.login(flaskr.app.config['USERNAME'],59 flaskr.app.config['PASSWORD'] + 'x')60 assert b'Invalid password' in rv.data6162 def test_messages(self):63 """Test that messages work"""64 self.login(flaskr.app.config['USERNAME'],65 flaskr.app.config['PASSWORD'])66 rv = self.app.post('/add', data=dict(67 title='<Hello>',68 text='<strong>HTML</strong> allowed here'69 ), follow_redirects=True)70 assert b'No entries here so far' not in rv.data71 assert b'&lt;Hello&gt;' in rv.data72 assert b'<strong>HTML</strong> allowed here' in rv.data737475if __name__ == '__main__':76 unittest.main()
added:examples/flaskr/test_flaskr.py+77 added
1# -*- coding: utf-8 -*-2"""3 Flaskr Tests4 ~~~~~~~~~~~~56 Tests the Flaskr application.78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import os15import flaskr16import tempfile171819@pytest.fixture20def client(request):21 db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()22 flaskr.app.config['TESTING'] = True23 client = flaskr.app.test_client()24 with flaskr.app.app_context():25 flaskr.init_db()2627 def teardown():28 os.close(db_fd)29 os.unlink(flaskr.app.config['DATABASE'])30 request.addfinalizer(teardown)3132 return client333435def login(client, username, password):36 return client.post('/login', data=dict(37 username=username,38 password=password39 ), follow_redirects=True)404142def logout(client):43 return client.get('/logout', follow_redirects=True)444546def test_empty_db(client):47 """Start with a blank database."""48 rv = client.get('/')49 assert b'No entries here so far' in rv.data505152def test_login_logout(client):53 """Make sure login and logout works"""54 rv = login(client, flaskr.app.config['USERNAME'],55 flaskr.app.config['PASSWORD'])56 assert b'You were logged in' in rv.data57 rv = logout(client)58 assert b'You were logged out' in rv.data59 rv = login(client, flaskr.app.config['USERNAME'] + 'x',60 flaskr.app.config['PASSWORD'])61 assert b'Invalid username' in rv.data62 rv = login(client, flaskr.app.config['USERNAME'],63 flaskr.app.config['PASSWORD'] + 'x')64 assert b'Invalid password' in rv.data656667def test_messages(client):68 """Test that messages work"""69 login(client, flaskr.app.config['USERNAME'],70 flaskr.app.config['PASSWORD'])71 rv = client.post('/add', data=dict(72 title='<Hello>',73 text='<strong>HTML</strong> allowed here'74 ), follow_redirects=True)75 assert b'No entries here so far' not in rv.data76 assert b'&lt;Hello&gt;' in rv.data77 assert b'<strong>HTML</strong> allowed here' in rv.data
deleted:examples/minitwit/minitwit_tests.py-150 removed
1# -*- coding: utf-8 -*-2"""3 MiniTwit Tests4 ~~~~~~~~~~~~~~56 Tests the MiniTwit application.78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import os12import minitwit13import unittest14import tempfile151617class MiniTwitTestCase(unittest.TestCase):1819 def setUp(self):20 """Before each test, set up a blank database"""21 self.db_fd, minitwit.app.config['DATABASE'] = tempfile.mkstemp()22 self.app = minitwit.app.test_client()23 with minitwit.app.app_context():24 minitwit.init_db()2526 def tearDown(self):27 """Get rid of the database again after each test."""28 os.close(self.db_fd)29 os.unlink(minitwit.app.config['DATABASE'])3031 # helper functions3233 def register(self, username, password, password2=None, email=None):34 """Helper function to register a user"""35 if password2 is None:36 password2 = password37 if email is None:38 email = username + '@example.com'39 return self.app.post('/register', data={40 'username': username,41 'password': password,42 'password2': password2,43 'email': email,44 }, follow_redirects=True)4546 def login(self, username, password):47 """Helper function to login"""48 return self.app.post('/login', data={49 'username': username,50 'password': password51 }, follow_redirects=True)5253 def register_and_login(self, username, password):54 """Registers and logs in in one go"""55 self.register(username, password)56 return self.login(username, password)5758 def logout(self):59 """Helper function to logout"""60 return self.app.get('/logout', follow_redirects=True)6162 def add_message(self, text):63 """Records a message"""64 rv = self.app.post('/add_message', data={'text': text},65 follow_redirects=True)66 if text:67 assert b'Your message was recorded' in rv.data68 return rv6970 # testing functions7172 def test_register(self):73 """Make sure registering works"""74 rv = self.register('user1', 'default')75 assert b'You were successfully registered ' \76 b'and can login now' in rv.data77 rv = self.register('user1', 'default')78 assert b'The username is already taken' in rv.data79 rv = self.register('', 'default')80 assert b'You have to enter a username' in rv.data81 rv = self.register('meh', '')82 assert b'You have to enter a password' in rv.data83 rv = self.register('meh', 'x', 'y')84 assert b'The two passwords do not match' in rv.data85 rv = self.register('meh', 'foo', email='broken')86 assert b'You have to enter a valid email address' in rv.data8788 def test_login_logout(self):89 """Make sure logging in and logging out works"""90 rv = self.register_and_login('user1', 'default')91 assert b'You were logged in' in rv.data92 rv = self.logout()93 assert b'You were logged out' in rv.data94 rv = self.login('user1', 'wrongpassword')95 assert b'Invalid password' in rv.data96 rv = self.login('user2', 'wrongpassword')97 assert b'Invalid username' in rv.data9899 def test_message_recording(self):100 """Check if adding messages works"""101 self.register_and_login('foo', 'default')102 self.add_message('test message 1')103 self.add_message('<test message 2>')104 rv = self.app.get('/')105 assert b'test message 1' in rv.data106 assert b'&lt;test message 2&gt;' in rv.data107108 def test_timelines(self):109 """Make sure that timelines work"""110 self.register_and_login('foo', 'default')111 self.add_message('the message by foo')112 self.logout()113 self.register_and_login('bar', 'default')114 self.add_message('the message by bar')115 rv = self.app.get('/public')116 assert b'the message by foo' in rv.data117 assert b'the message by bar' in rv.data118119 # bar's timeline should just show bar's message120 rv = self.app.get('/')121 assert b'the message by foo' not in rv.data122 assert b'the message by bar' in rv.data123124 # now let's follow foo125 rv = self.app.get('/foo/follow', follow_redirects=True)126 assert b'You are now following &#34;foo&#34;' in rv.data127128 # we should now see foo's message129 rv = self.app.get('/')130 assert b'the message by foo' in rv.data131 assert b'the message by bar' in rv.data132133 # but on the user's page we only want the user's message134 rv = self.app.get('/bar')135 assert b'the message by foo' not in rv.data136 assert b'the message by bar' in rv.data137 rv = self.app.get('/foo')138 assert b'the message by foo' in rv.data139 assert b'the message by bar' not in rv.data140141 # now unfollow and check if that worked142 rv = self.app.get('/foo/unfollow', follow_redirects=True)143 assert b'You are no longer following &#34;foo&#34;' in rv.data144 rv = self.app.get('/')145 assert b'the message by foo' not in rv.data146 assert b'the message by bar' in rv.data147148149if __name__ == '__main__':150 unittest.main()
added:examples/minitwit/test_minitwit.py+151 added
1# -*- coding: utf-8 -*-2"""3 MiniTwit Tests4 ~~~~~~~~~~~~~~56 Tests the MiniTwit application.78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import os12import minitwit13import tempfile14import pytest151617@pytest.fixture18def client(request):19 db_fd, minitwit.app.config['DATABASE'] = tempfile.mkstemp()20 client = minitwit.app.test_client()21 with minitwit.app.app_context():22 minitwit.init_db()2324 def teardown():25 """Get rid of the database again after each test."""26 os.close(db_fd)27 os.unlink(minitwit.app.config['DATABASE'])28 request.addfinalizer(teardown)29 return client303132def register(client, username, password, password2=None, email=None):33 """Helper function to register a user"""34 if password2 is None:35 password2 = password36 if email is None:37 email = username + '@example.com'38 return client.post('/register', data={39 'username': username,40 'password': password,41 'password2': password2,42 'email': email,43 }, follow_redirects=True)444546def login(client, username, password):47 """Helper function to login"""48 return client.post('/login', data={49 'username': username,50 'password': password51 }, follow_redirects=True)525354def register_and_login(client, username, password):55 """Registers and logs in in one go"""56 register(client, username, password)57 return login(client, username, password)585960def logout(client):61 """Helper function to logout"""62 return client.get('/logout', follow_redirects=True)636465def add_message(client, text):66 """Records a message"""67 rv = client.post('/add_message', data={'text': text},68 follow_redirects=True)69 if text:70 assert b'Your message was recorded' in rv.data71 return rv727374def test_register(client):75 """Make sure registering works"""76 rv = register(client, 'user1', 'default')77 assert b'You were successfully registered ' \78 b'and can login now' in rv.data79 rv = register(client, 'user1', 'default')80 assert b'The username is already taken' in rv.data81 rv = register(client, '', 'default')82 assert b'You have to enter a username' in rv.data83 rv = register(client, 'meh', '')84 assert b'You have to enter a password' in rv.data85 rv = register(client, 'meh', 'x', 'y')86 assert b'The two passwords do not match' in rv.data87 rv = register(client, 'meh', 'foo', email='broken')88 assert b'You have to enter a valid email address' in rv.data899091def test_login_logout(client):92 """Make sure logging in and logging out works"""93 rv = register_and_login(client, 'user1', 'default')94 assert b'You were logged in' in rv.data95 rv = logout(client)96 assert b'You were logged out' in rv.data97 rv = login(client, 'user1', 'wrongpassword')98 assert b'Invalid password' in rv.data99 rv = login(client, 'user2', 'wrongpassword')100 assert b'Invalid username' in rv.data101102103def test_message_recording(client):104 """Check if adding messages works"""105 register_and_login(client, 'foo', 'default')106 add_message(client, 'test message 1')107 add_message(client, '<test message 2>')108 rv = client.get('/')109 assert b'test message 1' in rv.data110 assert b'&lt;test message 2&gt;' in rv.data111112113def test_timelines(client):114 """Make sure that timelines work"""115 register_and_login(client, 'foo', 'default')116 add_message(client, 'the message by foo')117 logout(client)118 register_and_login(client, 'bar', 'default')119 add_message(client, 'the message by bar')120 rv = client.get('/public')121 assert b'the message by foo' in rv.data122 assert b'the message by bar' in rv.data123124 # bar's timeline should just show bar's message125 rv = client.get('/')126 assert b'the message by foo' not in rv.data127 assert b'the message by bar' in rv.data128129 # now let's follow foo130 rv = client.get('/foo/follow', follow_redirects=True)131 assert b'You are now following &#34;foo&#34;' in rv.data132133 # we should now see foo's message134 rv = client.get('/')135 assert b'the message by foo' in rv.data136 assert b'the message by bar' in rv.data137138 # but on the user's page we only want the user's message139 rv = client.get('/bar')140 assert b'the message by foo' not in rv.data141 assert b'the message by bar' in rv.data142 rv = client.get('/foo')143 assert b'the message by foo' in rv.data144 assert b'the message by bar' not in rv.data145146 # now unfollow and check if that worked147 rv = client.get('/foo/unfollow', follow_redirects=True)148 assert b'You are no longer following &#34;foo&#34;' in rv.data149 rv = client.get('/')150 assert b'the message by foo' not in rv.data151 assert b'the message by bar' in rv.data
modified:tests/test_apps/importerror.py+1 added-1 removed
1# NoImportsTestCase1# TestNoImports2raise NotImplementedError
modified:tests/__init__.py+33 added-136 removed
9 unmodified lines
10 :license: BSD, see LICENSE for more details.11"""1213from __future__ import print_function14import pytest1516import os17import sys18import flask19import warnings19import unittest20from functools import update_wrapper21from contextlib import contextmanager22from werkzeug.utils import import_string, find_modules23from flask._compat import reraise, StringIO22from flask._compat import StringIO232425def add_to_path(path):26 """Adds an entry to sys.path if it's not already there. This does
14 unmodified lines
41 sys.path[:] = [x for x in sys.path if not _samefile(path, x)]42 sys.path.insert(0, path)434446def iter_suites():47 """Yields all testsuites."""48 for module in find_modules(__name__):49 mod = import_string(module)50 if hasattr(mod, 'suite'):51 yield mod.suite()525354def find_all_tests(suite):55 """Yields all the tests and their names from a given suite."""56 suites = [suite]57 while suites:58 s = suites.pop()59 try:60 suites.extend(s)61 except TypeError:62 yield s, '%s.%s.%s' % (63 s.__class__.__module__,64 s.__class__.__name__,65 s._testMethodName66 )676845@contextmanager46def catch_warnings():47 """Catch warnings in a with block in a list"""48 # make sure deprecation warnings are active in tests
2 unmodified lines
51 filters = warnings.filters52 warnings.filters = filters[:]53 old_showwarning = warnings.showwarning54 log = []5556 def showwarning(message, category, filename, lineno, file=None, line=None):57 log.append(locals())58 try:59 warnings.showwarning = showwarning
23 unmodified lines
83 self.assert_in('Modules are deprecated', str(entry['message']))84 return update_wrapper(new_f, f)8586110class FlaskTestCase(unittest.TestCase):87class TestFlask(object):88 """Baseclass for all the tests that Flask uses. Use these methods89 for testing instead of the camelcased ones in the baseclass for90 consistency.91 """9293 @pytest.fixture(autouse=True)94 def setup_path(self, monkeypatch):95 monkeypatch.syspath_prepend(96 os.path.abspath(os.path.join(97 os.path.dirname(__file__), 'test_apps'))98 )99100 @pytest.fixture(autouse=True)101 def leak_detector(self, request):102 request.addfinalizer(self.ensure_clean_request_context)103104 def ensure_clean_request_context(self):105 # make sure we're not leaking a request context since we are106 # testing flask internally in debug mode in a few cases107 leaks = []108 while flask._request_ctx_stack.top is not None:109 leaks.append(flask._request_ctx_stack.pop())110 self.assert_equal(leaks, [])111112 def setup_method(self, method):113 self.setup()114115 def teardown_method(self, method):116 self.teardown()117118 def setup(self):119 pass120121 def teardown(self):122 pass123130 def setUp(self):131 self.setup()132133 def tearDown(self):134 unittest.TestCase.tearDown(self)135 self.ensure_clean_request_context()136 self.teardown()137124 def assert_equal(self, x, y):139 return self.assertEqual(x, y)125 assert x == y126127 def assert_raises(self, exc_type, callable=None, *args, **kwargs):142 catcher = _ExceptionCatcher(self, exc_type)143 if callable is None:144 return catcher145 with catcher:146 callable(*args, **kwargs)128 if callable:129 return pytest.raises(exc_type, callable, *args, **kwargs)130 else:131 return pytest.raises(exc_type)132133 def assert_true(self, x, msg=None):149 self.assertTrue(x, msg)134 assert x135 assert_ = assert_true136137 def assert_false(self, x, msg=None):153 self.assertFalse(x, msg)138 assert not x139140 def assert_in(self, x, y):156 self.assertIn(x, y)141 assert x in y142143 def assert_not_in(self, x, y):159 self.assertNotIn(x, y)144 assert x not in y145146 def assert_isinstance(self, obj, cls):162 self.assertIsInstance(obj, cls)147 assert isinstance(obj, cls)148164 if sys.version_info[:2] == (2, 6):165 def assertIn(self, x, y):166 assert x in y, "%r unexpectedly not in %r" % (x, y)167168 def assertNotIn(self, x, y):169 assert x not in y, "%r unexpectedly in %r" % (x, y)170171 def assertIsInstance(self, x, y):172 assert isinstance(x, y), "not isinstance(%r, %r)" % (x, y)173174175class _ExceptionCatcher(object):176177 def __init__(self, test_case, exc_type):178 self.test_case = test_case179 self.exc_type = exc_type180181 def __enter__(self):182 return self183184 def __exit__(self, exc_type, exc_value, tb):185 exception_name = self.exc_type.__name__186 if exc_type is None:187 self.test_case.fail('Expected exception of type %r' %188 exception_name)189 elif not issubclass(exc_type, self.exc_type):190 reraise(exc_type, exc_value, tb)191 return True192193194class BetterLoader(unittest.TestLoader):195 """A nicer loader that solves two problems. First of all we are setting196 up tests from different sources and we're doing this programmatically197 which breaks the default loading logic so this is required anyways.198 Secondly this loader has a nicer interpolation for test names than the199 default one so you can just do ``run-tests.py ViewTestCase`` and it200 will work.201 """202203 def getRootSuite(self):204 return suite()205206 def loadTestsFromName(self, name, module=None):207 root = self.getRootSuite()208 if name == 'suite':209 return root210211 all_tests = []212 for testcase, testname in find_all_tests(root):213 if testname == name or \214 testname.endswith('.' + name) or \215 ('.' + name + '.') in testname or \216 testname.startswith(name + '.'):217 all_tests.append(testcase)218219 if not all_tests:220 raise LookupError('could not find test case for "%s"' % name)221222 if len(all_tests) == 1:223 return all_tests[0]224 rv = unittest.TestSuite()225 for test in all_tests:226 rv.addTest(test)227 return rv228229230def setup_path():231 add_to_path(os.path.abspath(os.path.join(232 os.path.dirname(__file__), 'test_apps')))233234235def suite():236 """A testsuite that has all the Flask tests. You can use this237 function to integrate the Flask tests into your own testsuite238 in case you want to test that monkeypatches to Flask do not239 break it.240 """241 setup_path()242 suite = unittest.TestSuite()243 for other_suite in iter_suites():244 suite.addTest(other_suite)245 return suite246247248def main():249 """Runs the testsuite as command line application."""250 try:251 unittest.main(testLoader=BetterLoader(), defaultTest='suite')252 except Exception as e:253 print('Error: %s' % e)149 def fail(self, msg):150 raise AssertionError(msg)
modified:tests/test_appctx.py+4 added-4 removed
9 unmodified lines
10"""1112import flask13import unittest14from tests import FlaskTestCase14from tests import TestFlask151617class AppContextTestCase(FlaskTestCase):17class TestAppContext(TestFlask):1819 def test_basic_url_generation(self):20 app = flask.Flask(__name__)21 app.config['SERVER_NAME'] = 'localhost'
86 unmodified lines
108 ['werkzeug.request'] is not None)109 return u''110 c = app.test_client()111 c.get('/')112 self.assertEqual(called, ['request', 'app'])112 self.assert_equal(called, ['request', 'app'])113114115def suite():116 suite = unittest.TestSuite()117 suite.addTest(unittest.makeSuite(AppContextTestCase))117 suite.addTest(unittest.makeSuite(TestAppContext))118 return suite
modified:tests/test_basic.py+20 added-27 removed
15 unmodified lines
16import pickle17import unittest18from datetime import datetime19from threading import Thread20from tests import FlaskTestCase, emits_module_deprecation_warning20from tests import TestFlask, emits_module_deprecation_warning21from flask._compat import text_type22from werkzeug.exceptions import BadRequest, NotFound, Forbidden23from werkzeug.http import parse_date24from werkzeug.routing import BuildError252627class BasicFunctionalityTestCase(FlaskTestCase):27class TestBasicFunctionality(TestFlask):2829 def test_options_work(self):30 app = flask.Flask(__name__)31 @app.route('/', methods=['GET', 'POST'])
489 unmodified lines
521 return response522 return 'Test'523 c = app.test_client()524 resp = c.get('/')525 self.assertEqual(resp.status_code, 200)526 self.assertEqual(resp.headers['X-Foo'], 'a header')525 self.assert_equal(resp.status_code, 200)526 self.assert_equal(resp.headers['X-Foo'], 'a header')527528 def test_teardown_request_handler(self):529 called = []530 app = flask.Flask(__name__)
308 unmodified lines
839 app = flask.Flask(__name__)840 with app.test_request_context():841 rv = flask.make_response(842 flask.jsonify({'msg': 'W00t'}), 400)843 self.assertEqual(rv.status_code, 400)844 self.assertEqual(rv.data, b'{\n "msg": "W00t"\n}')845 self.assertEqual(rv.mimetype, 'application/json')843 self.assert_equal(rv.status_code, 400)844 self.assert_equal(rv.data, b'{\n "msg": "W00t"\n}')845 self.assert_equal(rv.mimetype, 'application/json')846847 rv = flask.make_response(848 flask.Response(''), 400)849 self.assertEqual(rv.status_code, 400)850 self.assertEqual(rv.data, b'')851 self.assertEqual(rv.mimetype, 'text/html')849 self.assert_equal(rv.status_code, 400)850 self.assert_equal(rv.data, b'')851 self.assert_equal(rv.mimetype, 'text/html')852853 rv = flask.make_response(854 flask.Response('', headers={'Content-Type': 'text/html'}),855 400, [('X-Foo', 'bar')])856 self.assertEqual(rv.status_code, 400)857 self.assertEqual(rv.headers['Content-Type'], 'text/html')858 self.assertEqual(rv.headers['X-Foo'], 'bar')856 self.assert_equal(rv.status_code, 400)857 self.assert_equal(rv.headers['Content-Type'], 'text/html')858 self.assert_equal(rv.headers['X-Foo'], 'bar')859860 def test_url_generation(self):861 app = flask.Flask(__name__)862 @app.route('/hello/<name>', methods=['POST'])
8 unmodified lines
871 app = flask.Flask(__name__)872873 # Test base case, a URL which results in a BuildError.874 with app.test_request_context():875 self.assertRaises(BuildError, flask.url_for, 'spam')875 self.assert_raises(BuildError, flask.url_for, 'spam')876877 # Verify the error is re-raised if not the current exception.878 try:879 with app.test_request_context():
2 unmodified lines
882 error = err883 try:884 raise RuntimeError('Test case where BuildError is not current.')885 except RuntimeError:886 self.assertRaises(BuildError, app.handle_url_build_error, error, 'spam', {})886 self.assert_raises(BuildError, app.handle_url_build_error, error, 'spam', {})887888 # Test a custom handler.889 def handler(error, endpoint, values):890 # Just a test.
44 unmodified lines
935 self.assert_true("Expected ValueError")936937 def test_request_locals(self):938 self.assert_equal(repr(flask.g), '<LocalProxy unbound>')939 self.assertFalse(flask.g)939 self.assert_false(flask.g)940941 def test_test_app_proper_environ(self):942 app = flask.Flask(__name__)943 app.config.update(
260 unmodified lines
1204 assert flask.url_for('bar') == '/bar/'1205 assert flask.url_for('123') == '/bar/123'12061207 c = app.test_client()1208 self.assertEqual(c.get('/foo/').data, b'foo')1209 self.assertEqual(c.get('/bar/').data, b'bar')1210 self.assertEqual(c.get('/bar/123').data, b'123')1208 self.assert_equal(c.get('/foo/').data, b'foo')1209 self.assert_equal(c.get('/bar/').data, b'bar')1210 self.assert_equal(c.get('/bar/123').data, b'123')12111212 def test_preserve_only_once(self):1213 app = flask.Flask(__name__)1214 app.debug = True
70 unmodified lines
1285 self.assert_equal('foos' in flask.g, False)1286 self.assert_equal(sorted(flask.g), ['bar', 'foo'])128712881289class SubdomainTestCase(FlaskTestCase):1289class TestSubdomain(TestFlask):12901291 def test_basic_support(self):1292 app = flask.Flask(__name__)1293 app.config['SERVER_NAME'] = 'localhost'
60 unmodified lines
1354 rv = app.test_client().open('/')1355 self.assert_equal(rv.data, b'a')1356 rv = app.test_client().open('/b/')1357 self.assert_equal(rv.data, b'b')135813591360def suite():1361 suite = unittest.TestSuite()1362 suite.addTest(unittest.makeSuite(BasicFunctionalityTestCase))1363 suite.addTest(unittest.makeSuite(SubdomainTestCase))1364 return suite
modified:tests/test_blueprints.py+11 added-11 removed
9 unmodified lines
10"""1112import flask13import unittest14from tests import FlaskTestCase14from tests import TestFlask15from flask._compat import text_type16from werkzeug.http import parse_cache_control_header17from jinja2 import TemplateNotFound181920class BlueprintTestCase(FlaskTestCase):20class TestBlueprint(TestFlask):2122 def test_blueprint_specific_error_handling(self):23 frontend = flask.Blueprint('frontend', __name__)24 backend = flask.Blueprint('backend', __name__)
277 unmodified lines
302 def index():303 return flask.request.endpoint304305 c = app.test_client()306 self.assertEqual(c.get('/').data, b'index')307 self.assertEqual(c.get('/py/foo').data, b'bp.foo')308 self.assertEqual(c.get('/py/bar').data, b'bp.bar')309 self.assertEqual(c.get('/py/bar/123').data, b'bp.123')310 self.assertEqual(c.get('/py/bar/foo').data, b'bp.bar_foo')306 self.assert_equal(c.get('/').data, b'index')307 self.assert_equal(c.get('/py/foo').data, b'bp.foo')308 self.assert_equal(c.get('/py/bar').data, b'bp.bar')309 self.assert_equal(c.get('/py/bar/123').data, b'bp.123')310 self.assert_equal(c.get('/py/bar/foo').data, b'bp.bar_foo')311312 def test_route_decorator_custom_endpoint_with_dots(self):313 bp = flask.Blueprint('bp', __name__)314
21 unmodified lines
336337 def foo_foo_foo():338 pass339340 self.assertRaises(340 self.assert_raises(341 AssertionError,342 lambda: bp.add_url_rule(343 '/bar/123', endpoint='bar.123', view_func=foo_foo_foo344 )345 )346347 self.assertRaises(347 self.assert_raises(348 AssertionError,349 bp.route('/bar/123', endpoint='bar.123'),350 lambda: None351 )
1 unmodified line
353 app = flask.Flask(__name__)354 app.register_blueprint(bp, url_prefix='/py')355356 c = app.test_client()357 self.assertEqual(c.get('/py/foo').data, b'bp.foo')357 self.assert_equal(c.get('/py/foo').data, b'bp.foo')358 # The rule's didn't actually made it through359 rv = c.get('/py/bar')360 assert rv.status_code == 404361 rv = c.get('/py/bar/123')
218 unmodified lines
580 self.assert_in(b'Success!', rv.data)581582def suite():583 suite = unittest.TestSuite()584 suite.addTest(unittest.makeSuite(BlueprintTestCase))584 suite.addTest(unittest.makeSuite(TestBlueprint))585 return suite
modified:tests/test_config.py+8 added-8 removed
13 unmodified lines
14import flask15import pkgutil16import unittest17from contextlib import contextmanager18from tests import FlaskTestCase18from tests import TestFlask19from flask._compat import PY2202122# config keys used for the ConfigTestCase22# config keys used for the TestConfig23TEST_KEY = 'foo'24SECRET_KEY = 'devkey'252627class ConfigTestCase(FlaskTestCase):27class TestConfig(TestFlask):2829 def common_object_test(self, app):30 self.assert_equal(app.secret_key, 'devkey')31 self.assert_equal(app.config['TEST_KEY'], 'foo')32 self.assert_not_in('ConfigTestCase', app.config)32 self.assert_not_in('TestConfig', app.config)3334 def test_config_from_file(self):35 app = flask.Flask(__name__)36 app.config.from_pyfile(__file__.rsplit('.', 1)[0] + '.py')
79 unmodified lines
116 'file (No such file or directory):'))117 self.assert_true(msg.endswith("missing.cfg'"))118 else:119 self.fail('expected IOError')120 self.assertFalse(app.config.from_envvar('FOO_SETTINGS', silent=True))120 self.assert_false(app.config.from_envvar('FOO_SETTINGS', silent=True))121 finally:122 os.environ = env123124 def test_config_missing(self):
81 unmodified lines
206 finally:207 pkgutil.get_loader = old_get_loader208209210class InstanceTestCase(FlaskTestCase):210class TestInstance(TestFlask):211212 def test_explicit_instance_paths(self):213 here = os.path.abspath(os.path.dirname(__file__))214 try:
163 unmodified lines
378379380def suite():381 suite = unittest.TestSuite()382 suite.addTest(unittest.makeSuite(ConfigTestCase))383 suite.addTest(unittest.makeSuite(InstanceTestCase))382 suite.addTest(unittest.makeSuite(TestConfig))383 suite.addTest(unittest.makeSuite(TestInstance))384 return suite
modified:tests/test_deprecations.py+3 added-3 removed
9 unmodified lines
10"""1112import flask13import unittest14from tests import FlaskTestCase, catch_warnings14from tests import TestFlask, catch_warnings151617class DeprecationsTestCase(FlaskTestCase):17class TestDeprecations(TestFlask):18 """not used currently"""192021def suite():22 suite = unittest.TestSuite()23 suite.addTest(unittest.makeSuite(DeprecationsTestCase))23 suite.addTest(unittest.makeSuite(TestDeprecations))24 return suite
modified:tests/test_examples.py+4 added-4 removed
22 unmodified lines
23def suite():24 setup_path()25 suite = unittest.TestSuite()26 try:27 from minitwit_tests import MiniTwitTestCase27 from minitwit_tests import TestMiniTwit28 except ImportError:29 pass30 else:31 suite.addTest(unittest.makeSuite(MiniTwitTestCase))31 suite.addTest(unittest.makeSuite(TestMiniTwit))32 try:33 from flaskr_tests import FlaskrTestCase33 from flaskr_tests import TestFlaskr34 except ImportError:35 pass36 else:37 suite.addTest(unittest.makeSuite(FlaskrTestCase))37 suite.addTest(unittest.makeSuite(TestFlaskr))38 return suite
modified:tests/test_ext.py+3 added-3 removed
13 unmodified lines
14try:15 from imp import reload as reload_module16except ImportError:17 reload_module = reload18from tests import FlaskTestCase18from tests import TestFlask19from flask._compat import PY22021class ExtImportHookTestCase(FlaskTestCase):21class TestExtImportHook(TestFlask):2223 def setup(self):24 # we clear this out for various reasons. The most important one is25 # that a real flaskext could be in there which would disable our
105 unmodified lines
131132133def suite():134 suite = unittest.TestSuite()135 suite.addTest(unittest.makeSuite(ExtImportHookTestCase))135 suite.addTest(unittest.makeSuite(TestExtImportHook))136 return suite
modified:tests/test_helpers.py+17 added-17 removed
11 unmodified lines
12import os13import flask14import unittest15from logging import StreamHandler16from tests import FlaskTestCase, catch_warnings, catch_stderr16from tests import TestFlask, catch_warnings, catch_stderr17from werkzeug.http import parse_cache_control_header, parse_options_header18from flask._compat import StringIO, text_type1920
5 unmodified lines
26 except LookupError:27 return False282930class JSONTestCase(FlaskTestCase):30class TestJSON(TestFlask):3132 def test_json_bad_requests(self):33 app = flask.Flask(__name__)34 @app.route('/json', methods=['POST'])
112 unmodified lines
147 c = app.test_client()148 rv = c.post('/', data=flask.json.dumps({149 'x': {'_foo': 42}150 }), content_type='application/json')151 self.assertEqual(rv.data, b'"<42>"')151 self.assert_equal(rv.data, b'"<42>"')152153 def test_modified_url_encoding(self):154 class ModifiedRequest(flask.Request):155 url_charset = 'euc-kr'
83 unmodified lines
239 self.assert_equal(lines, sorted_by_int)240 except AssertionError:241 self.assert_equal(lines, sorted_by_str)242243class SendfileTestCase(FlaskTestCase):243class TestSendfile(TestFlask):244245 def test_send_file_regular(self):246 app = flask.Flask(__name__)247 with app.test_request_context():
173 unmodified lines
421 self.assert_equal(rv.data.strip(), b'Hello Subdomain')422 rv.close()423424425class LoggingTestCase(FlaskTestCase):425class TestLogging(TestFlask):426427 def test_logger_cache(self):428 app = flask.Flask(__name__)429 logger1 = app.logger
19 unmodified lines
449 with app.test_client() as c:450 with catch_stderr() as err:451 c.get('/')452 out = err.getvalue()453 self.assert_in('WARNING in helpers [', out)453 self.assert_in('WARNING in test_helpers [', out)454 self.assert_in(os.path.basename(__file__.rsplit('.', 1)[0] + '.py'), out)455 self.assert_in('the standard library is dead', out)456 self.assert_in('this is a debug statement', out)457
113 unmodified lines
571 self.assert_equal(flask.url_for('myview', _method='POST'),572 '/myview/create')573574575class NoImportsTestCase(FlaskTestCase):575class TestNoImports(TestFlask):576 """Test Flasks are created without import.577578 Avoiding ``__import__`` helps create Flask instances where there are errors579 at import time. Those runtime errors will be apparent to the user soon
9 unmodified lines
589 except NotImplementedError:590 self.fail('Flask(import_name) is importing import_name.')591592593class StreamingTestCase(FlaskTestCase):593class TestStreaming(TestFlask):594595 def test_streaming_with_context(self):596 app = flask.Flask(__name__)597 app.testing = True
5 unmodified lines
603 yield '!'604 return flask.Response(flask.stream_with_context(generate()))605 c = app.test_client()606 rv = c.get('/?name=World')607 self.assertEqual(rv.data, b'Hello World!')607 self.assert_equal(rv.data, b'Hello World!')608609 def test_streaming_with_context_as_decorator(self):610 app = flask.Flask(__name__)611 app.testing = True
6 unmodified lines
618 yield '!'619 return flask.Response(generate())620 c = app.test_client()621 rv = c.get('/?name=World')622 self.assertEqual(rv.data, b'Hello World!')622 self.assert_equal(rv.data, b'Hello World!')623624 def test_streaming_with_context_and_custom_close(self):625 app = flask.Flask(__name__)626 app.testing = True
17 unmodified lines
644 return flask.Response(flask.stream_with_context(645 Wrapper(generate())))646 c = app.test_client()647 rv = c.get('/?name=World')648 self.assertEqual(rv.data, b'Hello World!')649 self.assertEqual(called, [42])648 self.assert_equal(rv.data, b'Hello World!')649 self.assert_equal(called, [42])650651652def suite():653 suite = unittest.TestSuite()654 if flask.json_available:655 suite.addTest(unittest.makeSuite(JSONTestCase))656 suite.addTest(unittest.makeSuite(SendfileTestCase))657 suite.addTest(unittest.makeSuite(LoggingTestCase))658 suite.addTest(unittest.makeSuite(NoImportsTestCase))659 suite.addTest(unittest.makeSuite(StreamingTestCase))655 suite.addTest(unittest.makeSuite(TestJSON))656 suite.addTest(unittest.makeSuite(TestSendfile))657 suite.addTest(unittest.makeSuite(TestLogging))658 suite.addTest(unittest.makeSuite(TestNoImports))659 suite.addTest(unittest.makeSuite(TestStreaming))660 return suite
modified:tests/test_regression.py+13 added-14 removed
7 unmodified lines
8 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1314import os15import gc16import sys17import flask18import threading17import unittest19from werkzeug.exceptions import NotFound19from tests import FlaskTestCase20from tests import TestFlask212223_gc_lock = threading.Lock()24
26 unmodified lines
51 _gc_lock.release()52 gc.enable()535454class MemoryTestCase(FlaskTestCase):55@pytest.mark.skipif(os.environ.get('RUN_FLASK_MEMORY_TESTS') != '1',56 reason='Turned off due to envvar.')57class TestMemory(TestFlask):5859 def assert_no_leak(self):60 return _NoLeakAsserter(self)6162 def test_memory_consumption(self):63 app = flask.Flask(__name__)6465 @app.route('/')66 def index():67 return flask.render_template('simple_template.html', whiskey=42)68
18 unmodified lines
87 with self.assert_raises(NotFound):88 safe_join('/foo', '..')899087class ExceptionTestCase(FlaskTestCase):91class TestException(TestFlask):9293 def test_aborting(self):94 class Foo(Exception):95 whatever = 4296 app = flask.Flask(__name__)97 app.testing = True9899 @app.errorhandler(Foo)100 def handle_foo(e):101 return str(e.whatever)102103 @app.route('/')104 def index():105 raise flask.abort(flask.redirect(flask.url_for('test')))106107 @app.route('/test')108 def test():109 raise Foo()110111 with app.test_client() as c:112 rv = c.get('/')106 self.assertEqual(rv.headers['Location'], 'http://localhost/test')113 self.assert_equal(rv.headers['Location'], 'http://localhost/test')114 rv = c.get('/test')108 self.assertEqual(rv.data, b'42')109110111def suite():112 suite = unittest.TestSuite()113 if os.environ.get('RUN_FLASK_MEMORY_TESTS') == '1':114 suite.addTest(unittest.makeSuite(MemoryTestCase))115 suite.addTest(unittest.makeSuite(ExceptionTestCase))116 return suite115 self.assert_equal(rv.data, b'42')
modified:tests/test_reqctx.py+3 added-3 removed
13 unmodified lines
14try:15 from greenlet import greenlet16except ImportError:17 greenlet = None18from tests import FlaskTestCase18from tests import TestFlask192021class RequestContextTestCase(FlaskTestCase):21class TestRequestContext(TestFlask):2223 def test_teardown_on_pop(self):24 buffer = []25 app = flask.Flask(__name__)
170 unmodified lines
196197198def suite():199 suite = unittest.TestSuite()200 suite.addTest(unittest.makeSuite(RequestContextTestCase))200 suite.addTest(unittest.makeSuite(TestRequestContext))201 return suite
modified:tests/test_signals.py+3 added-3 removed
9 unmodified lines
10"""1112import flask13import unittest14from tests import FlaskTestCase14from tests import TestFlask151617class SignalsTestCase(FlaskTestCase):17class TestSignals(TestFlask):1819 def test_template_rendered(self):20 app = flask.Flask(__name__)21
126 unmodified lines
148149def suite():150 suite = unittest.TestSuite()151 if flask.signals_available:152 suite.addTest(unittest.makeSuite(SignalsTestCase))152 suite.addTest(unittest.makeSuite(TestSignals))153 return suite
modified:tests/test_subclassing.py+3 added-3 removed
10 unmodified lines
11"""12import flask13import unittest14from logging import StreamHandler15from tests import FlaskTestCase15from tests import TestFlask16from flask._compat import StringIO171819class FlaskSubclassingTestCase(FlaskTestCase):19class TestFlaskSubclassing(TestFlask):2021 def test_suppressed_exception_logging(self):22 class SuppressedFlask(flask.Flask):23 def log_exception(self, exc_info):
17 unmodified lines
414243def suite():44 suite = unittest.TestSuite()45 suite.addTest(unittest.makeSuite(FlaskSubclassingTestCase))45 suite.addTest(unittest.makeSuite(TestFlaskSubclassing))46 return suite
modified:tests/test_templating.py+3 added-3 removed
12 unmodified lines
13import unittest14import logging15from jinja2 import TemplateNotFound1617from tests import FlaskTestCase17from tests import TestFlask181920class TemplatingTestCase(FlaskTestCase):20class TestTemplating(TestFlask):2122 def test_context_processing(self):23 app = flask.Flask(__name__)24 @app.context_processor
322 unmodified lines
347348349def suite():350 suite = unittest.TestSuite()351 suite.addTest(unittest.makeSuite(TemplatingTestCase))351 suite.addTest(unittest.makeSuite(TestTemplating))352 return suite
modified:tests/test_testing.py+25 added-25 removed
6 unmodified lines
78 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import pytest1213import flask14import unittest14from tests import FlaskTestCase15from tests import TestFlask16from flask._compat import text_type171818class TestToolsTestCase(FlaskTestCase):19class TestTestTools(TestFlask):2021 def test_environ_defaults_from_config(self):22 app = flask.Flask(__name__)23 app.testing = True
188 unmodified lines
212 self.assert_true('gin' in flask.request.form)213 self.assert_true('vodka' in flask.request.args)214215215class SubdomainTestCase(FlaskTestCase):216class TestSubdomain(TestFlask):217217 def setUp(self):218 self.app = flask.Flask(__name__)219 self.app.config['SERVER_NAME'] = 'example.com'220 self.client = self.app.test_client()218 @pytest.fixture219 def app(self, request):220 app = flask.Flask(__name__)221 app.config['SERVER_NAME'] = 'example.com'222222 self._ctx = self.app.test_request_context()223 self._ctx.push()223 ctx = app.test_request_context()224 ctx.push()225225 def tearDown(self):226 if self._ctx is not None:227 self._ctx.pop()226 def teardown():227 if ctx is not None:228 ctx.pop()229 request.addfinalizer(teardown)230 return app231232 @pytest.fixture233 def client(self, app):234 return app.test_client()235229 def test_subdomain(self):230 @self.app.route('/', subdomain='<company_id>')236 def test_subdomain(self, app, client):237 @app.route('/', subdomain='<company_id>')238 def view(company_id):239 return company_id240241 url = flask.url_for('view', company_id='xxx')235 response = self.client.get(url)242 response = client.get(url)243244 self.assert_equal(200, response.status_code)245 self.assert_equal(b'xxx', response.data)246247241 def test_nosubdomain(self):242 @self.app.route('/<company_id>')248 def test_nosubdomain(self, app, client):249 @app.route('/<company_id>')250 def view(company_id):251 return company_id252253 url = flask.url_for('view', company_id='xxx')247 response = self.client.get(url)254 response = client.get(url)255256 self.assert_equal(200, response.status_code)257 self.assert_equal(b'xxx', response.data)251252253def suite():254 suite = unittest.TestSuite()255 suite.addTest(unittest.makeSuite(TestToolsTestCase))256 suite.addTest(unittest.makeSuite(SubdomainTestCase))257 return suite
modified:tests/test_views.py+3 added-3 removed
10 unmodified lines
1112import flask13import flask.views14import unittest15from tests import FlaskTestCase15from tests import TestFlask16from werkzeug.http import parse_set_header1718class ViewTestCase(FlaskTestCase):18class TestView(TestFlask):1920 def common_test(self, app):21 c = app.test_client()22
141 unmodified lines
164165166def suite():167 suite = unittest.TestSuite()168 suite.addTest(unittest.makeSuite(ViewTestCase))168 suite.addTest(unittest.makeSuite(TestView))169 return suite
modified:setup.cfg+3 added
1[pytest]2norecursedirs= scripts docs34[aliases]5release = egg_info -RDb ''67[wheel]
1 unmodified line