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
Provenance
- Commit
8fa5e32- Tree
b4fc090- Author
Markus Unterwaditzer <markus@unterwaditzer.net>- Committer
Markus Unterwaditzer <markus@unterwaditzer.net>- Parent
961db8a
24 files changed+421 added−530 removed
deleted:examples/blueprintexample/blueprintexample_test.py-36 removed
1-# -*- coding: utf-8 -*-2-"""3- Blueprint Example Tests4- ~~~~~~~~~~~~~~5-6- Tests the Blueprint example app7-"""8-import blueprintexample9-import unittest10-11-12-class BlueprintExampleTestCase(unittest.TestCase):13-14- 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- 35-if __name__ == '__main__':36- unittest.main()added:examples/blueprintexample/test_blueprintexample.py+33 added
1+# -*- coding: utf-8 -*-2+"""3+ Blueprint Example Tests4+ ~~~~~~~~~~~~~~5+6+ Tests the Blueprint example app7+"""8+import pytest9+10+import blueprintexample11+12+13+@pytest.fixture14+def client():15+ return blueprintexample.app.test_client()16+17+18+def test_urls(client):19+ r = client.get('/')20+ assert r.status_code == 20021+22+ r = client.get('/hello')23+ assert r.status_code == 20024+25+ r = client.get('/world')26+ assert r.status_code == 20027+28+ # second blueprint instance29+ r = client.get('/pages/hello')30+ assert r.status_code == 20031+32+ r = client.get('/pages/world')33+ assert r.status_code == 200deleted:examples/flaskr/flaskr_tests.py-76 removed
1-# -*- coding: utf-8 -*-2-"""3- Flaskr Tests4- ~~~~~~~~~~~~5-6- Tests the Flaskr application.7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-import os12-import flaskr13-import unittest14-import tempfile15-16-17-class FlaskrTestCase(unittest.TestCase):18-19- 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()26-27- 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'])31-32- def login(self, username, password):33- return self.app.post('/login', data=dict(34- username=username,35- password=password36- ), follow_redirects=True)37-38- def logout(self):39- return self.app.get('/logout', follow_redirects=True)40-41- # testing functions42-43- 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.data47-48- 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.data61-62- 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'<Hello>' in rv.data72- assert b'<strong>HTML</strong> allowed here' in rv.data73-74-75-if __name__ == '__main__':76- unittest.main()added:examples/flaskr/test_flaskr.py+77 added
1+# -*- coding: utf-8 -*-2+"""3+ Flaskr Tests4+ ~~~~~~~~~~~~5+6+ Tests the Flaskr application.7+8+ :copyright: (c) 2014 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import pytest13+14+import os15+import flaskr16+import tempfile17+18+19+@pytest.fixture20+def 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()26+27+ def teardown():28+ os.close(db_fd)29+ os.unlink(flaskr.app.config['DATABASE'])30+ request.addfinalizer(teardown)31+32+ return client33+34+35+def login(client, username, password):36+ return client.post('/login', data=dict(37+ username=username,38+ password=password39+ ), follow_redirects=True)40+41+42+def logout(client):43+ return client.get('/logout', follow_redirects=True)44+45+46+def test_empty_db(client):47+ """Start with a blank database."""48+ rv = client.get('/')49+ assert b'No entries here so far' in rv.data50+51+52+def 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.data65+66+67+def 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'<Hello>' in rv.data77+ assert b'<strong>HTML</strong> allowed here' in rv.datadeleted:examples/minitwit/minitwit_tests.py-150 removed
1-# -*- coding: utf-8 -*-2-"""3- MiniTwit Tests4- ~~~~~~~~~~~~~~5-6- Tests the MiniTwit application.7-8- :copyright: (c) 2014 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-import os12-import minitwit13-import unittest14-import tempfile15-16-17-class MiniTwitTestCase(unittest.TestCase):18-19- 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()25-26- 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'])30-31- # helper functions32-33- 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)45-46- 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)52-53- 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)57-58- def logout(self):59- """Helper function to logout"""60- return self.app.get('/logout', follow_redirects=True)61-62- 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 rv69-70- # testing functions71-72- 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.data87-88- 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.data98-99- 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'<test message 2>' in rv.data107-108- 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.data118-119- # 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.data123-124- # now let's follow foo125- rv = self.app.get('/foo/follow', follow_redirects=True)126- assert b'You are now following "foo"' in rv.data127-128- # 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.data132-133- # 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.data140-141- # now unfollow and check if that worked142- rv = self.app.get('/foo/unfollow', follow_redirects=True)143- assert b'You are no longer following "foo"' 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.data147-148-149-if __name__ == '__main__':150- unittest.main()added:examples/minitwit/test_minitwit.py+151 added
1+# -*- coding: utf-8 -*-2+"""3+ MiniTwit Tests4+ ~~~~~~~~~~~~~~5+6+ Tests the MiniTwit application.7+8+ :copyright: (c) 2014 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+import os12+import minitwit13+import tempfile14+import pytest15+16+17+@pytest.fixture18+def 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()23+24+ 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 client30+31+32+def 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)44+45+46+def login(client, username, password):47+ """Helper function to login"""48+ return client.post('/login', data={49+ 'username': username,50+ 'password': password51+ }, follow_redirects=True)52+53+54+def 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)58+59+60+def logout(client):61+ """Helper function to logout"""62+ return client.get('/logout', follow_redirects=True)63+64+65+def 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 rv72+73+74+def 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.data89+90+91+def 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.data101+102+103+def 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'<test message 2>' in rv.data111+112+113+def 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.data123+124+ # 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.data128+129+ # now let's follow foo130+ rv = client.get('/foo/follow', follow_redirects=True)131+ assert b'You are now following "foo"' in rv.data132+133+ # 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.data137+138+ # 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.data145+146+ # now unfollow and check if that worked147+ rv = client.get('/foo/unfollow', follow_redirects=True)148+ assert b'You are no longer following "foo"' 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.datamodified:tests/test_apps/importerror.py+1 added-1 removed
1-# NoImportsTestCase1+# TestNoImports2 raise NotImplementedErrormodified:tests/__init__.py+33 added-136 removed
9 unmodified lines10 :license: BSD, see LICENSE for more details.11 """12 13 from __future__ import print_function14+import pytest15 16 import os17 import sys18 import flask19 import warnings19-import unittest20 from functools import update_wrapper21 from contextlib import contextmanager22-from werkzeug.utils import import_string, find_modules23-from flask._compat import reraise, StringIO22+from flask._compat import StringIO23 24 25 def add_to_path(path):26 """Adds an entry to sys.path if it's not already there. This does14 unmodified lines41 sys.path[:] = [x for x in sys.path if not _samefile(path, x)]42 sys.path.insert(0, path)43 44 46-def 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()52-53-54-def 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- )67-68-45 @contextmanager46 def catch_warnings():47 """Catch warnings in a with block in a list"""48 # make sure deprecation warnings are active in tests2 unmodified lines51 filters = warnings.filters52 warnings.filters = filters[:]53 old_showwarning = warnings.showwarning54 log = []55+56 def showwarning(message, category, filename, lineno, file=None, line=None):57 log.append(locals())58 try:59 warnings.showwarning = showwarning23 unmodified lines83 self.assert_in('Modules are deprecated', str(entry['message']))84 return update_wrapper(new_f, f)85 86 110-class FlaskTestCase(unittest.TestCase):87+class 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 """92 93+ @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+ )99+100+ @pytest.fixture(autouse=True)101+ def leak_detector(self, request):102+ request.addfinalizer(self.ensure_clean_request_context)103+104 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, [])111 112+ def setup_method(self, method):113+ self.setup()114+115+ def teardown_method(self, method):116+ self.teardown()117+118 def setup(self):119 pass120 121 def teardown(self):122 pass123 130- def setUp(self):131- self.setup()132-133- def tearDown(self):134- unittest.TestCase.tearDown(self)135- self.ensure_clean_request_context()136- self.teardown()137-124 def assert_equal(self, x, y):139- return self.assertEqual(x, y)125+ assert x == y126 127 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)132 133 def assert_true(self, x, msg=None):149- self.assertTrue(x, msg)134+ assert x135 assert_ = assert_true136 137 def assert_false(self, x, msg=None):153- self.assertFalse(x, msg)138+ assert not x139 140 def assert_in(self, x, y):156- self.assertIn(x, y)141+ assert x in y142 143 def assert_not_in(self, x, y):159- self.assertNotIn(x, y)144+ assert x not in y145 146 def assert_isinstance(self, obj, cls):162- self.assertIsInstance(obj, cls)147+ assert isinstance(obj, cls)148 164- 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)167-168- def assertNotIn(self, x, y):169- assert x not in y, "%r unexpectedly in %r" % (x, y)170-171- def assertIsInstance(self, x, y):172- assert isinstance(x, y), "not isinstance(%r, %r)" % (x, y)173-174-175-class _ExceptionCatcher(object):176-177- def __init__(self, test_case, exc_type):178- self.test_case = test_case179- self.exc_type = exc_type180-181- def __enter__(self):182- return self183-184- 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 True192-193-194-class 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- """202-203- def getRootSuite(self):204- return suite()205-206- def loadTestsFromName(self, name, module=None):207- root = self.getRootSuite()208- if name == 'suite':209- return root210-211- 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)218-219- if not all_tests:220- raise LookupError('could not find test case for "%s"' % name)221-222- 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 rv228-229-230-def setup_path():231- add_to_path(os.path.abspath(os.path.join(232- os.path.dirname(__file__), 'test_apps')))233-234-235-def 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 suite246-247-248-def 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 lines10 """11 12 import flask13 import unittest14-from tests import FlaskTestCase14+from tests import TestFlask15 16 17-class AppContextTestCase(FlaskTestCase):17+class TestAppContext(TestFlask):18 19 def test_basic_url_generation(self):20 app = flask.Flask(__name__)21 app.config['SERVER_NAME'] = 'localhost'86 unmodified lines108 ['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'])113 114 115 def suite():116 suite = unittest.TestSuite()117- suite.addTest(unittest.makeSuite(AppContextTestCase))117+ suite.addTest(unittest.makeSuite(TestAppContext))118 return suitemodified:tests/test_basic.py+20 added-27 removed
15 unmodified lines16 import pickle17 import unittest18 from datetime import datetime19 from threading import Thread20-from tests import FlaskTestCase, emits_module_deprecation_warning20+from tests import TestFlask, emits_module_deprecation_warning21 from flask._compat import text_type22 from werkzeug.exceptions import BadRequest, NotFound, Forbidden23 from werkzeug.http import parse_date24 from werkzeug.routing import BuildError25 26 27-class BasicFunctionalityTestCase(FlaskTestCase):27+class TestBasicFunctionality(TestFlask):28 29 def test_options_work(self):30 app = flask.Flask(__name__)31 @app.route('/', methods=['GET', 'POST'])489 unmodified lines521 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')527 528 def test_teardown_request_handler(self):529 called = []530 app = flask.Flask(__name__)308 unmodified lines839 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')846 847 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')852 853 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')859 860 def test_url_generation(self):861 app = flask.Flask(__name__)862 @app.route('/hello/<name>', methods=['POST'])8 unmodified lines871 app = flask.Flask(__name__)872 873 # 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')876 877 # Verify the error is re-raised if not the current exception.878 try:879 with app.test_request_context():2 unmodified lines882 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', {})887 888 # Test a custom handler.889 def handler(error, endpoint, values):890 # Just a test.44 unmodified lines935 self.assert_true("Expected ValueError")936 937 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)940 941 def test_test_app_proper_environ(self):942 app = flask.Flask(__name__)943 app.config.update(260 unmodified lines1204 assert flask.url_for('bar') == '/bar/'1205 assert flask.url_for('123') == '/bar/123'1206 1207 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')1211 1212 def test_preserve_only_once(self):1213 app = flask.Flask(__name__)1214 app.debug = True70 unmodified lines1285 self.assert_equal('foos' in flask.g, False)1286 self.assert_equal(sorted(flask.g), ['bar', 'foo'])1287 1288 1289-class SubdomainTestCase(FlaskTestCase):1289+class TestSubdomain(TestFlask):1290 1291 def test_basic_support(self):1292 app = flask.Flask(__name__)1293 app.config['SERVER_NAME'] = 'localhost'60 unmodified lines1354 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')1358-1359-1360-def suite():1361- suite = unittest.TestSuite()1362- suite.addTest(unittest.makeSuite(BasicFunctionalityTestCase))1363- suite.addTest(unittest.makeSuite(SubdomainTestCase))1364- return suitemodified:tests/test_blueprints.py+11 added-11 removed
9 unmodified lines10 """11 12 import flask13 import unittest14-from tests import FlaskTestCase14+from tests import TestFlask15 from flask._compat import text_type16 from werkzeug.http import parse_cache_control_header17 from jinja2 import TemplateNotFound18 19 20-class BlueprintTestCase(FlaskTestCase):20+class TestBlueprint(TestFlask):21 22 def test_blueprint_specific_error_handling(self):23 frontend = flask.Blueprint('frontend', __name__)24 backend = flask.Blueprint('backend', __name__)277 unmodified lines302 def index():303 return flask.request.endpoint304 305 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')311 312 def test_route_decorator_custom_endpoint_with_dots(self):313 bp = flask.Blueprint('bp', __name__)314 21 unmodified lines336 337 def foo_foo_foo():338 pass339 340- 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 )346 347- self.assertRaises(347+ self.assert_raises(348 AssertionError,349 bp.route('/bar/123', endpoint='bar.123'),350 lambda: None351 )1 unmodified line353 app = flask.Flask(__name__)354 app.register_blueprint(bp, url_prefix='/py')355 356 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 lines580 self.assert_in(b'Success!', rv.data)581 582 def suite():583 suite = unittest.TestSuite()584- suite.addTest(unittest.makeSuite(BlueprintTestCase))584+ suite.addTest(unittest.makeSuite(TestBlueprint))585 return suitemodified:tests/test_config.py+8 added-8 removed
13 unmodified lines14 import flask15 import pkgutil16 import unittest17 from contextlib import contextmanager18-from tests import FlaskTestCase18+from tests import TestFlask19 from flask._compat import PY220 21 22-# config keys used for the ConfigTestCase22+# config keys used for the TestConfig23 TEST_KEY = 'foo'24 SECRET_KEY = 'devkey'25 26 27-class ConfigTestCase(FlaskTestCase):27+class TestConfig(TestFlask):28 29 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)33 34 def test_config_from_file(self):35 app = flask.Flask(__name__)36 app.config.from_pyfile(__file__.rsplit('.', 1)[0] + '.py')79 unmodified lines116 '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 = env123 124 def test_config_missing(self):81 unmodified lines206 finally:207 pkgutil.get_loader = old_get_loader208 209 210-class InstanceTestCase(FlaskTestCase):210+class TestInstance(TestFlask):211 212 def test_explicit_instance_paths(self):213 here = os.path.abspath(os.path.dirname(__file__))214 try:163 unmodified lines378 379 380 def 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 suitemodified:tests/test_deprecations.py+3 added-3 removed
9 unmodified lines10 """11 12 import flask13 import unittest14-from tests import FlaskTestCase, catch_warnings14+from tests import TestFlask, catch_warnings15 16 17-class DeprecationsTestCase(FlaskTestCase):17+class TestDeprecations(TestFlask):18 """not used currently"""19 20 21 def suite():22 suite = unittest.TestSuite()23- suite.addTest(unittest.makeSuite(DeprecationsTestCase))23+ suite.addTest(unittest.makeSuite(TestDeprecations))24 return suitemodified:tests/test_examples.py+4 added-4 removed
22 unmodified lines23 def 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 suitemodified:tests/test_ext.py+3 added-3 removed
13 unmodified lines14 try:15 from imp import reload as reload_module16 except ImportError:17 reload_module = reload18-from tests import FlaskTestCase18+from tests import TestFlask19 from flask._compat import PY220 21-class ExtImportHookTestCase(FlaskTestCase):21+class TestExtImportHook(TestFlask):22 23 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 our105 unmodified lines131 132 133 def suite():134 suite = unittest.TestSuite()135- suite.addTest(unittest.makeSuite(ExtImportHookTestCase))135+ suite.addTest(unittest.makeSuite(TestExtImportHook))136 return suitemodified:tests/test_helpers.py+17 added-17 removed
11 unmodified lines12 import os13 import flask14 import unittest15 from logging import StreamHandler16-from tests import FlaskTestCase, catch_warnings, catch_stderr16+from tests import TestFlask, catch_warnings, catch_stderr17 from werkzeug.http import parse_cache_control_header, parse_options_header18 from flask._compat import StringIO, text_type19 20 5 unmodified lines26 except LookupError:27 return False28 29 30-class JSONTestCase(FlaskTestCase):30+class TestJSON(TestFlask):31 32 def test_json_bad_requests(self):33 app = flask.Flask(__name__)34 @app.route('/json', methods=['POST'])112 unmodified lines147 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>"')152 153 def test_modified_url_encoding(self):154 class ModifiedRequest(flask.Request):155 url_charset = 'euc-kr'83 unmodified lines239 self.assert_equal(lines, sorted_by_int)240 except AssertionError:241 self.assert_equal(lines, sorted_by_str)242 243-class SendfileTestCase(FlaskTestCase):243+class TestSendfile(TestFlask):244 245 def test_send_file_regular(self):246 app = flask.Flask(__name__)247 with app.test_request_context():173 unmodified lines421 self.assert_equal(rv.data.strip(), b'Hello Subdomain')422 rv.close()423 424 425-class LoggingTestCase(FlaskTestCase):425+class TestLogging(TestFlask):426 427 def test_logger_cache(self):428 app = flask.Flask(__name__)429 logger1 = app.logger19 unmodified lines449 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 lines571 self.assert_equal(flask.url_for('myview', _method='POST'),572 '/myview/create')573 574 575-class NoImportsTestCase(FlaskTestCase):575+class TestNoImports(TestFlask):576 """Test Flasks are created without import.577 578 Avoiding ``__import__`` helps create Flask instances where there are errors579 at import time. Those runtime errors will be apparent to the user soon9 unmodified lines589 except NotImplementedError:590 self.fail('Flask(import_name) is importing import_name.')591 592 593-class StreamingTestCase(FlaskTestCase):593+class TestStreaming(TestFlask):594 595 def test_streaming_with_context(self):596 app = flask.Flask(__name__)597 app.testing = True5 unmodified lines603 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!')608 609 def test_streaming_with_context_as_decorator(self):610 app = flask.Flask(__name__)611 app.testing = True6 unmodified lines618 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!')623 624 def test_streaming_with_context_and_custom_close(self):625 app = flask.Flask(__name__)626 app.testing = True17 unmodified lines644 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])650 651 652 def 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 suitemodified:tests/test_regression.py+13 added-14 removed
7 unmodified lines8 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12+import pytest13+14 import os15 import gc16 import sys17 import flask18 import threading17-import unittest19 from werkzeug.exceptions import NotFound19-from tests import FlaskTestCase20+from tests import TestFlask21 22 23 _gc_lock = threading.Lock()24 26 unmodified lines51 _gc_lock.release()52 gc.enable()53 54 54-class MemoryTestCase(FlaskTestCase):55+@pytest.mark.skipif(os.environ.get('RUN_FLASK_MEMORY_TESTS') != '1',56+ reason='Turned off due to envvar.')57+class TestMemory(TestFlask):58 59 def assert_no_leak(self):60 return _NoLeakAsserter(self)61 62 def test_memory_consumption(self):63 app = flask.Flask(__name__)64+65 @app.route('/')66 def index():67 return flask.render_template('simple_template.html', whiskey=42)68 18 unmodified lines87 with self.assert_raises(NotFound):88 safe_join('/foo', '..')89 90 87-class ExceptionTestCase(FlaskTestCase):91+class TestException(TestFlask):92 93 def test_aborting(self):94 class Foo(Exception):95 whatever = 4296 app = flask.Flask(__name__)97 app.testing = True98+99 @app.errorhandler(Foo)100 def handle_foo(e):101 return str(e.whatever)102+103 @app.route('/')104 def index():105 raise flask.abort(flask.redirect(flask.url_for('test')))106+107 @app.route('/test')108 def test():109 raise Foo()110 111 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')109-110-111-def 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 lines14 try:15 from greenlet import greenlet16 except ImportError:17 greenlet = None18-from tests import FlaskTestCase18+from tests import TestFlask19 20 21-class RequestContextTestCase(FlaskTestCase):21+class TestRequestContext(TestFlask):22 23 def test_teardown_on_pop(self):24 buffer = []25 app = flask.Flask(__name__)170 unmodified lines196 197 198 def suite():199 suite = unittest.TestSuite()200- suite.addTest(unittest.makeSuite(RequestContextTestCase))200+ suite.addTest(unittest.makeSuite(TestRequestContext))201 return suitemodified:tests/test_signals.py+3 added-3 removed
9 unmodified lines10 """11 12 import flask13 import unittest14-from tests import FlaskTestCase14+from tests import TestFlask15 16 17-class SignalsTestCase(FlaskTestCase):17+class TestSignals(TestFlask):18 19 def test_template_rendered(self):20 app = flask.Flask(__name__)21 126 unmodified lines148 149 def suite():150 suite = unittest.TestSuite()151 if flask.signals_available:152- suite.addTest(unittest.makeSuite(SignalsTestCase))152+ suite.addTest(unittest.makeSuite(TestSignals))153 return suitemodified:tests/test_subclassing.py+3 added-3 removed
10 unmodified lines11 """12 import flask13 import unittest14 from logging import StreamHandler15-from tests import FlaskTestCase15+from tests import TestFlask16 from flask._compat import StringIO17 18 19-class FlaskSubclassingTestCase(FlaskTestCase):19+class TestFlaskSubclassing(TestFlask):20 21 def test_suppressed_exception_logging(self):22 class SuppressedFlask(flask.Flask):23 def log_exception(self, exc_info):17 unmodified lines41 42 43 def suite():44 suite = unittest.TestSuite()45- suite.addTest(unittest.makeSuite(FlaskSubclassingTestCase))45+ suite.addTest(unittest.makeSuite(TestFlaskSubclassing))46 return suitemodified:tests/test_templating.py+3 added-3 removed
12 unmodified lines13 import unittest14 import logging15 from jinja2 import TemplateNotFound16 17-from tests import FlaskTestCase17+from tests import TestFlask18 19 20-class TemplatingTestCase(FlaskTestCase):20+class TestTemplating(TestFlask):21 22 def test_context_processing(self):23 app = flask.Flask(__name__)24 @app.context_processor322 unmodified lines347 348 349 def suite():350 suite = unittest.TestSuite()351- suite.addTest(unittest.makeSuite(TemplatingTestCase))351+ suite.addTest(unittest.makeSuite(TestTemplating))352 return suitemodified:tests/test_testing.py+25 added-25 removed
6 unmodified lines7 8 :copyright: (c) 2014 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11+import pytest12 13 import flask14 import unittest14-from tests import FlaskTestCase15+from tests import TestFlask16 from flask._compat import text_type17 18 18-class TestToolsTestCase(FlaskTestCase):19+class TestTestTools(TestFlask):20 21 def test_environ_defaults_from_config(self):22 app = flask.Flask(__name__)23 app.testing = True188 unmodified lines212 self.assert_true('gin' in flask.request.form)213 self.assert_true('vodka' in flask.request.args)214 215 215-class SubdomainTestCase(FlaskTestCase):216+class TestSubdomain(TestFlask):217 217- 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'222 222- self._ctx = self.app.test_request_context()223- self._ctx.push()223+ ctx = app.test_request_context()224+ ctx.push()225 225- 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 app231 232+ @pytest.fixture233+ def client(self, app):234+ return app.test_client()235+229- 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_id240 241 url = flask.url_for('view', company_id='xxx')235- response = self.client.get(url)242+ response = client.get(url)243 244 self.assert_equal(200, response.status_code)245 self.assert_equal(b'xxx', response.data)246 247 241- 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_id252 253 url = flask.url_for('view', company_id='xxx')247- response = self.client.get(url)254+ response = client.get(url)255 256 self.assert_equal(200, response.status_code)257 self.assert_equal(b'xxx', response.data)251-252-253-def suite():254- suite = unittest.TestSuite()255- suite.addTest(unittest.makeSuite(TestToolsTestCase))256- suite.addTest(unittest.makeSuite(SubdomainTestCase))257- return suitemodified:tests/test_views.py+3 added-3 removed
10 unmodified lines11 12 import flask13 import flask.views14 import unittest15-from tests import FlaskTestCase15+from tests import TestFlask16 from werkzeug.http import parse_set_header17 18-class ViewTestCase(FlaskTestCase):18+class TestView(TestFlask):19 20 def common_test(self, app):21 c = app.test_client()22 141 unmodified lines164 165 166 def suite():167 suite = unittest.TestSuite()168- suite.addTest(unittest.makeSuite(ViewTestCase))168+ suite.addTest(unittest.makeSuite(TestView))169 return suitemodified:setup.cfg+3 added
1+[pytest]2+norecursedirs= scripts docs3+4 [aliases]5 release = egg_info -RDb ''6 7 [wheel]1 unmodified line