The thing that you need to implement when you do unit testing (which distinguishes functional tests) is that you are testing a small āunitā. This device (your opinion in this case) does not require a ārealā request and does not require a fully functional system. In this view, there are certain hopes that an object that calls itself a "request" may have, but about this, and it, of course, does not require everything available in a real request. This is where funny or dummy objects come into play. You want to test your opinion so that you can convey something in your view using the properties needed to verify that the job is complete. Let's say you have the following configuration:
def main(): config = Configurator() config.add_route('user', '/users/{uid}') return config.make_wsgi_app() @view_config(route_name='user', renderer='user_template.mako') def user_view(request): uid = request.matchdict['uid'] user = find_user(request, uid) if user is None: raise HTTPNotFound return {'user': user} def find_user(request, uid): return request.db.query(User).filter_by(id=uid).first()
Great, so this is a real view, and you will notice that the request requires only 2 attributes, matchdict and db . Ok, we can do this:
class Test_user_view(unittest.TestCase): def test_it(self): req = DummyRequest() req.db = DummyDB() req.matchdict = {'uid': '3'} result = user_view(req) self.assertEqual(result['user'].id, 3)
Now one thing that we are not considering here is the implementation of DummyDB , but the find_user find_user might be the best approach to return a dummy value. This simplifies testing and focuses on the view itself, without clogging up when talking to the database. This is a separate test.
The other answers here describe functional testing in more detail, and you should definitely take a look at using WebTest to help ensure that your entire application works as you expect, but this is not the unit test area.
source share