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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
| 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.
1
2
3
4
5
6
| class TestAccountController(ControllerTest):
def test_signin_signout(self):
Dummy_ldap.install()
# ... do stuff
|
Simple!