0

I'm writing some tests for a view function in django. The view function is decorated with an @facebook.require_login decorator from the pyFacebook library. This deciorator checks whether the user is logged in to facebook and provides access to an object which represents the facebook api if they are. The checking and populating of the request is done in some middleware.

I want to be able to control what the view function sees from the facebook api and so I am attempting to mock the facebook api object using the mock library. The problem is, the facebook middleware makes the facebook api available as an attribute on the request, as far as I can tell the django test client does not give you access to the request object so I cannot insert the mock facebook api object into the view.

The only way I can see to test this is to basically copy most of the code from the test client and modify it to make the request object accessible to the test code before the test is run. I don't have a problem with doing this, but is this the best way to do it? I feel like there must be an easier way.

Also, is it normal for middleware to set attributes on the request, it seems like it would be conceptually cleaner for the middleware to make any extra data available as extra arguments to the decorated function (in this example, I am sure there are others where that doesn't apply).

1 Answer 1

0

Have you looked at the RequestFactory [1]?

[1] http://docs.djangoproject.com/en/dev/topics/testing/#the-request-factory

2
  • I have, and whilst it pretty much exactly solves my problem it is also only available in the development version of django. I'm working on 1.2 at the moment, I should probably have specified that in the question. Anyway, my current solution is basically to copy the code for RequestFactory from the development version into my testing libraries. It's a massive hack but it works.
    – Alex jg
    Feb 26, 2011 at 3:26
  • A bit of a hack for now, but at least your test code will be readily upgradable when 1.3 lands and then be quite clean.
    – DrMeers
    Feb 26, 2011 at 4:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.