[Twisted-Python] Direct access to main server class

Terry Jones terry at jon.es
Mon Aug 28 10:05:23 EDT 2006

Here's a hopefully not-too-dumb question...

I have a class that provides a service that I plan to make accessible via
Twisted. I wrote the class and various unit tests. So I could formerly do
simple things like:

    import unittest

    class myTest:
	def setUp():
	    self.c = MyClass()

	def tearDown():

	def testX():
	    self.assert_(self.c.X() == 4)

I recently added users, passwords, and permissions to the system. So now
many method calls need a requesting user object passed to them, and check
that the user has permission to carry out the action. I added simple
twisted.cred class to provide realms, avatars, portal with checkers, etc.

In the myApp.tac file, I create an instance of my top-level class (MyClass
above). In the case of providing access to my service via Nevow, I
instantiate a NevowSite and pass it the portal. That is all, I think, as it
should be.

But now I'm left wondering what happens to the old unit testing code. It
obviously cannot just create a MyClass instance. The unit testing code
should be using the service by authenticating itself just like any other
client. But I'm not sure how best to do that. The unit test code wants to
perform all manner of tests, and preferably this would be done by just
making available the instance of MyClass created in my app's .tac file,
allowing the test code to call its methods. But somehow that no longer
feels quite right - the connection is in fact local, but it's coming in
somehow through twisted.cred.

I hope I'm being more or less clear about my dilemma, and I suppose this
must be a situation people have to deal with all the time.

Two solutions come to mind:

  1) Fake it. Call directly into my code to make myself an authenticated
     user object, and then start passing it in to methods on my own
     class. This is ugly though, plus if the service is already running
     it's a bad solution because it goes behind the back of twisted and
     asks for trouble.

  2) Make all the methods of my class available via RPC and have all the
     unit test code use them. This seems like a major pain, though I
     suppose it would work.

I'd much rather just have the unit test code connect as a special local
user and get back the instance of MyClass created by my .tac file and call
its methods. Is that easy to do?

OK, sorry for another typically long posting....

Thanks for any help. Regards,

More information about the Twisted-Python mailing list