«back

spaceblog

RSS

mock LDAP server object

Wed, 26 Jul 2006 19:04

Today's big achievement was an LDAP mock object, similar to the SMTP mock object found in paste.fixture. I was refactoring the sign in and sign out code of an in-house application that uses LDAP as an authentication store, and I needed to test that the logic of the controllers was correct. So, referring back to Paste's lovely fixture module, I came up with the following:

import ldap

class Dummy_ldap(object):

    def __init__(self, server):
        print "dummy ldap init"
        self.server = server

    def install(cls):
        ldap.initialize = cls

    install = classmethod(install)

    def simple_bind_s(self, dn, passwd):
        return True

    def search(self, base, scope, search_filter):
        self.base = base
        self.filter = search_filter
        self.results = [(ldap.RES_SEARCH_ENTRY, [('dn', "cn=test,%s" % self.base),
                                                 ('mail', ['test'])]),
                        (ldap.RES_SEARCH_RESULT, []),
                        ]
        self.counter = 0
        return 1

    def result(self, rid, number):
        r = self.results[self.counter]
        self.counter += 1
        return r

A bit hackish, yes, but I'm not trying to reimplement LDAP here, I just want to trap the calls I use. Obviously a little bit of work is needed to, say, disallow the bind, or throw an exception, but these are trivial extensions.

Just as in Dummy_smtplib, you call the classmethod install to set it up (i.e. monkeypatch ldap.initialize) and you get to trap how it behaves.

class TestAccountController(ControllerTest):

    def test_signin_signout(self):
        Dummy_ldap.install()

        # ... do stuff

Simple!

All content Copyright © 2002-2005 Jamie Wilkinson. Entries in this blog are licensed under the Creative Commons Attribution-Sharealike v2 License.