source: TI05-delivery/trunk/test/test_embedded.py @ 1336

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI05-delivery/trunk/test/test_embedded.py@1336
Revision 1336, 10.0 KB checked in by spascoe, 13 years ago (diff)

Test cases automatically dump client output to bbftpc.log.

This saves inserting debug code on demand.

  • Property svn:executable set to *
Line 
1#!/usr/bin/env python
2"""
3Tests for the bbftp daemon when embedded in Python.
4
5@author: Stephen Pascoe
6@version: $Id$
7"""
8
9import unittest
10import sys, os, signal, time, stat
11from glob import glob
12import re, tempfile, getopt
13
14HOME = os.path.abspath(os.getenv('NDG_DELIVERY_HOME', os.curdir))
15BUILDDIR = glob('%s/build/lib.*' % HOME)[0]
16BBFTP = glob('%s/src/bbftp-client*/bbftpc/bbftp' % HOME)[0]
17DATADIR = '%s/test/data' % HOME
18VERSION = open('%s/VERSION' % HOME).read()
19NDG_MESSAGE_LEN = 256
20
21NDG_HANDSHAKE = "NDG-Delivery-server %s" % VERSION
22
23sys.path.append(BUILDDIR)
24
25import pybbftp.server as server
26import traceback
27
28
29class TestAuthHandler(server.AuthHandler):
30   
31    def authenticate(self):
32        # Dump the pid so that gdm can pick it up
33        fh = open('./DS_conn.pid', 'w')
34        print >>fh, os.getpid()
35        fh.close()
36        #time.sleep(15)
37
38        msg = self.recv()
39        self.log(server.LOG_DEBUG, 'AuthContext received Auth message: %s' % msg)
40               
41        self.send(NDG_HANDSHAKE)
42
43        privatestr = self.recv()
44        self.log(server.LOG_DEBUG, "AuthContext received privatestr: %s" % privatestr)
45       
46        return self.makeAuthzHandler(msg, "TestCaseUser")
47
48    def makeAuthzHandler(self, msg, user):
49        return TestAuthzHandler(msg, "TestCaseUser")
50
51
52class TestAuthzHandler(server.LiberalAuthzHandler):
53    def __init__(self, version, username):
54        super(TestAuthzHandler, self).__init__(username)
55        self.version = version
56
57
58
59
60class TestFailAuthHandler(server.AuthHandler):
61    def authorise(self):
62        raise server.AuthenticationFailure, "TestFailAuthHandler"
63
64
65class TestPermAuthHandler(TestAuthHandler):
66    def makeAuthzHandler(self, msg, user):
67        return TestPermAuthzHandler(msg, "TestCaseUser")
68
69class TestPermAuthzHandler(TestAuthzHandler):
70    """Check's the path's other read permission and authorises accordingly.
71    """
72
73    def authzControl(self, msgcode, transferopt, path):
74        self.log(server.LOG_DEBUG, 'TestPermAuthzHandler.authzControl: msgcode = %s' % hex(msgcode))
75        return self.authzPath(path)
76
77    def authzRetr(self, path):
78        return self.authzPath(path)
79
80    def authzStore(self, path):
81        return self.authzPath(path)
82
83    def authzPath(self, path):
84        mode = stat.S_IMODE(os.stat(path)[stat.ST_MODE])
85        if (mode & 0004):
86            self.log(server.LOG_DEBUG, 'TestPermAuthzHandler OK')
87            return True
88        else:
89            self.log(server.LOG_DEBUG, 'TestPermAuthzHandler FAIL')
90            raise server.AuthorisationFailure, "TestPermAuthzHandler: no read perms"
91
92
93class BaseFixture(unittest.TestCase):
94
95    authContext = TestAuthHandler()
96
97    def setUp(self):
98        self._clearLog()
99        self._startServer()
100
101    def tearDown(self):
102        self._stopServer()
103
104    #----------------------------------------------------------------------------------
105
106
107    def _startServer(self):
108        # Start the server and store it's PID
109        self.pid = server.start(self.authContext, ['-l', 'DEBUG'])
110
111    def _stopServer(self):
112        # Stop the server process
113        os.kill(self.pid, signal.SIGTERM)
114        os.waitpid(self.pid, 0)
115
116
117    def _runClient(self, cmd, debug=False, user="testcase", privatestr=None):
118        """Run the client.
119        """
120
121        if debug:
122            f = "-d"
123        else:
124            f = "-m"
125
126        if privatestr == None:
127            p = ""
128        else:
129            p = "-P %s" % repr(privatestr)
130
131        # This is ugly but I need to redirect stderr to stdout
132        fh = os.popen('sh -c "%s %s %s -u %s -r 1 -e \'%s\' localhost" 2>&1 ' % (BBFTP, f, p, user, cmd))
133
134        output = fh.read()
135        print >>open('./bbftpc.log', 'w'), output
136
137        return output
138
139
140    def _clearLog(self, logfile="./bbftpd.log"):
141        if os.path.exists(logfile):
142            os.remove(logfile)
143
144    def _readLog(self, logfile="./bbftpd.log"):
145        return open(logfile).read()
146   
147
148
149    def _findLines(self, lines, string):
150        """Look for lines matching each regular expression in lines.
151       
152        @return: True if all lines are found, else False
153        """
154       
155        for line in lines:
156            if not re.search('^%s$' % line, string, re.M):
157                return False
158           
159        return True
160
161
162    def assertLines(self, lines, string):
163        """Assert that there is a line in string matching each regular expression in lines.
164        """
165
166        for line in lines:
167            self.assert_(re.search('^%s$' % line, string, re.M))
168
169
170
171class AuthOK(BaseFixture):
172    """Test the bbftpd module.
173    """
174   
175    def testStartup(self):
176        lines = self._readLog()
177        self.assertLines(['.*Starting bbftpd'], lines)
178
179    def testDir(self):
180        """Try connecting the client and listing a directory.
181        """
182
183        output = self._runClient("dir %s" % DATADIR)
184
185        self.assertLines([r'dir .*/data', r' d .*/\.', r' d .*/\.\.',
186                        r' f .*/foo', r' f .*/bar', r' f .*/baz'], output)
187
188        lines = self._readLog()
189        self.assertLines(['.*Getting new bbftp connexion.*',
190                          r'.*Authz: MSG_LIST_V2 .*/test/data/\*.*',
191                          r'.*User TestCaseUser disconnected.*'], lines)
192
193
194    def testHandshake(self):
195        """Verify handshake messages are exchanged.
196        """
197
198        output = self._runClient("dir .", debug=True)
199
200        self.assertLines(['Received Auth handshake: NDG-Delivery-server %s' % VERSION], output)
201
202        lines = self._readLog()
203
204        self.assertLines(['.*AuthContext received Auth message: NDG-Delivery-client %s' % VERSION], lines)
205
206    def testPrivateStr(self):
207        """Verify the private string is sent to server.
208        """
209
210        output = self._runClient("dir .", privatestr="testPrivateStr")
211
212        lines = self._readLog()
213        self.assertLines(['.*AuthContext received privatestr: testPrivateStr'], lines)
214
215    def testRetr(self):
216        """Try retrieving a file.
217        """
218
219        tmp = tempfile.mktemp('test_bbftpd')
220        output = self._runClient("get %s/foo %s" % (DATADIR, tmp))
221
222        # Check the client output
223        self.assertLines(['get.*nogzip'], output)
224
225        # Check retrieved file
226        self.assert_(os.system('diff --brief %s/foo %s' % (DATADIR, tmp)) == 0)
227        os.remove(tmp)
228
229        # Check log
230        lines = self._readLog()
231        self.assertLines(['.*Authz: RETR .*/foo', '.*GET TestCaseUser .*/foo.*'], lines)
232
233    def testStore(self):
234        """Try storing a file.
235        """
236
237
238        src = '%s/bar' % (DATADIR)
239        dest = '%s/new_bar' % (DATADIR)
240        os.system('cp %s %s' % (src, dest))
241        output = self._runClient("put %s %s" % (src, dest))
242
243        # Check the client output
244        self.assertLines(['put .* nogzip'], output)
245
246
247        # Check sent file
248        self.assert_(os.system('diff --brief %s %s' % (dest, src)) == 0)
249        os.remove(dest)
250
251        # Check log
252        lines = self._readLog()
253        self.assertLines(['.*Authz: STORE .*/new_bar', '.*PUT TestCaseUser .*/new_bar.*'], lines)
254
255
256
257class AuthFail(BaseFixture):
258    authContext = TestFailAuthHandler()
259
260    def test(self):
261        """Fail authorisation
262        """
263
264        output = self._runClient("dir .", debug=True)
265
266        lines = self._readLog()
267
268        self.assertLines(['.*Error while private authentication.*'], output)
269        self.assertLines(['.*bbftpd_private_auth failed.*'], lines)
270
271
272class Authz(BaseFixture):
273    authContext = TestPermAuthHandler()
274
275    def setUp(self):
276        super(Authz, self).setUp()
277
278        # Set modes on test files
279        os.chmod('%s/bar' % (DATADIR), 0640)
280        os.chmod('%s/foo' % (DATADIR), 0655)
281
282    def testOK(self):
283        """Test dir of a readable file.
284        """
285
286        output = self._runClient("stat %s/foo" % (DATADIR), debug=True)
287
288        lines = self._readLog()
289
290
291        self.assertLines(['Connection and authentication correct', 'stat /.*/foo OK'], output)
292        self.assertLines(['.*Authz: MSG_STAT .*/foo', '.*TestPermAuthzHandler OK',
293                          '.*TestPermAuthzHandler.*msgcode = %s.*' % hex(server.MSG.STAT)], lines)
294
295    def testFail(self):
296        """Test dir of a non-readable file.
297        """
298
299        output = self._runClient("stat %s/bar" % (DATADIR), debug=True)
300
301        lines = self._readLog()
302
303        self.assertLines(['.* ndg_authz_control: AuthorisationFailure.* no read perms',
304                          'stat /.*/bar FAILED'], output)
305        self.assertLines(['.*Authz: MSG_STAT .*/bar', '.* TestPermAuthzHandler FAIL',
306                          '.* ndg_authz_control: AuthorisationFailure.* no read perms'], lines)
307
308
309class PythonClientAuthOK(AuthOK):
310    """Repeat AuthOK tests with a python-embedded client.
311    """
312
313    def testMultiCommand(self):
314        """Execute more than one command per connection.
315        """
316        output = self._runClient(["dir %s" % DATADIR, "stat %s/bar" % DATADIR])
317
318        self.assertLines([r'dir .*/data', r' d .*/\.', r' d .*/\.\.',
319                          r' f .*/foo', r' f .*/bar', r' f .*/baz',
320                          r'stat .*'], output)
321
322        lines = self._readLog()
323        self.assertLines(['.*Getting new bbftp connexion.*',
324                          r'.*Authz: MSG_LIST_V2 .*/test/data/\*.*',
325                          r'.*User TestCaseUser disconnected.*',
326                          r'.*: Receiving MSG_STAT.*'], lines)
327
328
329
330
331    def _runClient(self, cmds, debug=False, user="testcase", privatestr=None):
332        """Run the client.
333        """
334
335        if type(cmds) == type(''):
336            cmd_args = ['-e', repr(cmds)]
337        else:
338            cmd_args = []
339            for cmd in cmds:
340                cmd_args += ['-e', repr(cmd)]
341
342        if debug:
343            f = "-d"
344        else:
345            f = "-m"
346
347        args = cmd_args + [f, '-u', user,
348                '-r', '1']
349
350        if privatestr != None:
351            args += ['-P', privatestr]
352
353        args.append('localhost')
354
355        fh = os.popen('%s/test/runclient.py %s' % (HOME, ' '.join(args)))
356        output = fh.read()
357        print >>open('./bbftpc.log', 'w'), output
358
359        return output
360
361if __name__ == '__main__':
362    unittest.main()
Note: See TracBrowser for help on using the repository browser.